aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
-rw-r--r--.gitignore12
-rw-r--r--.readthedocs.yaml20
-rw-r--r--Dockerfile4
-rw-r--r--INFO.yaml63
-rw-r--r--README.md66
-rw-r--r--WebContent/WEB-INF/music.properties.sample3
-rw-r--r--WebContent/WEB-INF/web.xml14
-rw-r--r--distribution/cassandra/docker-entrypoint.sh96
-rw-r--r--distribution/cassandra/music.cql20
-rw-r--r--distribution/cassandra/music_single.cql20
-rw-r--r--distribution/cassandra_job/Dockerfile9
-rw-r--r--distribution/cassandra_job/runcql.sh31
-rw-r--r--distribution/dockermusic/README.md48
-rw-r--r--distribution/dockermusic/logs/README.md1
-rwxr-xr-xdistribution/dockermusic/music.sh101
-rw-r--r--distribution/dockermusic/properties/music.properties19
-rw-r--r--distribution/tomcat/Dockerfile3
-rw-r--r--distribution/zookeeper/Dockerfile3
-rw-r--r--docs/.gitignore3
-rw-r--r--docs/MUSIC_USAGE.jpgbin0 -> 47005 bytes
-rw-r--r--docs/_static/css/ribbon.css63
-rwxr-xr-xdocs/_static/favicon.icobin0 -> 2102 bytes
-rw-r--r--docs/_static/logo_onap_2017.pngbin0 -> 12278 bytes
-rw-r--r--docs/architecture.rst51
-rw-r--r--docs/conf.py15
-rw-r--r--docs/conf.yaml7
-rw-r--r--docs/delivery.rst18
-rwxr-xr-xdocs/index.rst1
-rw-r--r--docs/multi.rst57
-rw-r--r--docs/offeredapis.rst16
-rw-r--r--docs/release-notes.rst50
-rw-r--r--docs/requirements-docs.txt15
-rw-r--r--docs/setup.rst11
-rw-r--r--docs/single.rst3
-rw-r--r--docs/swagger.json65
-rw-r--r--docs/tox.ini22
-rw-r--r--examples/VotingApp/README.md1
-rw-r--r--examples/VotingApp/pom.xml97
-rw-r--r--examples/VotingApp/src/main/java/main/JsonDelete.java53
-rw-r--r--examples/VotingApp/src/main/java/main/JsonInsert.java63
-rw-r--r--examples/VotingApp/src/main/java/main/JsonKeySpace.java51
-rw-r--r--examples/VotingApp/src/main/java/main/JsonTable.java37
-rw-r--r--examples/VotingApp/src/main/java/main/MusicConnector.java92
-rw-r--r--examples/VotingApp/src/main/java/main/Util.java2
-rw-r--r--examples/VotingApp/src/main/java/main/VotingApp.java860
-rwxr-xr-x[-rw-r--r--]jar/pom.xml89
-rw-r--r--jar/src/main/java/org/onap/music/datastore/MusicDataStore.java109
-rw-r--r--jar/src/main/java/org/onap/music/datastore/PreparedQueryObject.java1
-rw-r--r--jar/src/main/java/org/onap/music/datastore/jsonobjects/AAFResponse.java1
-rw-r--r--jar/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java18
-rw-r--r--jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java1
-rw-r--r--jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java1
-rw-r--r--jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java1
-rw-r--r--jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java1
-rwxr-xr-xjar/src/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java1
-rw-r--r--jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java1
-rw-r--r--jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java1
-rw-r--r--jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java1
-rw-r--r--jar/src/main/java/org/onap/music/datastore/jsonobjects/NameSpace.java1
-rw-r--r--jar/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java167
-rw-r--r--jar/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java1
-rw-r--r--jar/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java286
-rw-r--r--jar/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java127
-rw-r--r--jar/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java1
-rw-r--r--jar/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java27
-rw-r--r--jar/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java1
-rw-r--r--jar/src/main/java/org/onap/music/exceptions/MusicLockingException.java1
-rw-r--r--jar/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java1
-rw-r--r--jar/src/main/java/org/onap/music/exceptions/MusicQueryException.java1
-rw-r--r--jar/src/main/java/org/onap/music/lockingservice/LockListener.java1
-rw-r--r--jar/src/main/java/org/onap/music/lockingservice/MusicLockState.java9
-rw-r--r--jar/src/main/java/org/onap/music/lockingservice/MusicLockingService.java59
-rw-r--r--jar/src/main/java/org/onap/music/lockingservice/ProtocolSupport.java11
-rw-r--r--jar/src/main/java/org/onap/music/lockingservice/ZNodeName.java5
-rw-r--r--jar/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java43
-rw-r--r--jar/src/main/java/org/onap/music/lockingservice/ZooKeeperOperation.java1
-rwxr-xr-xjar/src/main/java/org/onap/music/main/CachingUtil.java55
-rw-r--r--jar/src/main/java/org/onap/music/main/CipherUtil.java270
-rw-r--r--jar/src/main/java/org/onap/music/main/CronJobManager.java1
-rw-r--r--jar/src/main/java/org/onap/music/main/MusicCore.java157
-rw-r--r--jar/src/main/java/org/onap/music/main/MusicDigest.java1
-rwxr-xr-xjar/src/main/java/org/onap/music/main/MusicUtil.java82
-rwxr-xr-xjar/src/main/java/org/onap/music/main/PropertiesListener.java5
-rw-r--r--jar/src/main/java/org/onap/music/main/ResultType.java7
-rw-r--r--jar/src/main/java/org/onap/music/main/ReturnType.java1
-rw-r--r--jar/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java33
-rwxr-xr-xjar/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java1
-rw-r--r--jar/src/main/java/org/onap/music/rest/RestMusicBmAPI.java1
-rwxr-xr-xjar/src/main/java/org/onap/music/rest/RestMusicDataAPI.java75
-rw-r--r--jar/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java103
-rw-r--r--jar/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java5
-rwxr-xr-xjar/src/main/java/org/onap/music/rest/RestMusicQAPI.java1
-rw-r--r--jar/src/main/java/org/onap/music/rest/RestMusicTestAPI.java43
-rw-r--r--jar/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java29
-rw-r--r--jar/src/main/resources/logback.xml6
-rw-r--r--jar/src/main/resources/project.properties3
-rw-r--r--jar/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java1
-rw-r--r--jar/src/test/java/org/onap/music/unittests/TestLockStore.java1
-rw-r--r--jar/src/test/java/org/onap/music/unittests/TestMusicCore.java1
-rw-r--r--jar/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java1
-rw-r--r--jar/src/test/java/org/onap/music/unittests/TestRestMusicData.java1
-rw-r--r--jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java1
-rw-r--r--jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java1
-rw-r--r--jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java1
-rw-r--r--jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonOnboardTest.java1
-rw-r--r--jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java1
-rw-r--r--jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java1
-rw-r--r--jar/version.properties2
-rwxr-xr-xmusic-core/pom.xml459
-rw-r--r--music-core/src/main/java/LICENSE.txt (renamed from src/main/java/LICENSE.txt)0
-rw-r--r--music-core/src/main/java/org/onap/music/datastore/Condition.java63
-rwxr-xr-xmusic-core/src/main/java/org/onap/music/datastore/MusicDataStore.java540
-rw-r--r--music-core/src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java127
-rw-r--r--music-core/src/main/java/org/onap/music/datastore/PreparedQueryObject.java176
-rw-r--r--music-core/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java (renamed from src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java)20
-rw-r--r--music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java313
-rw-r--r--music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonIndex.java120
-rw-r--r--music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java415
-rw-r--r--music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java163
-rw-r--r--music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java (renamed from src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java)14
-rw-r--r--music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonLock.java (renamed from src/main/java/org/onap/music/datastore/jsonobjects/AAFResponse.java)29
-rw-r--r--music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java208
-rw-r--r--music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java363
-rw-r--r--music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java436
-rw-r--r--music-core/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java130
-rw-r--r--music-core/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java (renamed from src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java)31
-rw-r--r--music-core/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java188
-rw-r--r--music-core/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java107
-rw-r--r--music-core/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java (renamed from src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java)1
-rw-r--r--music-core/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java (renamed from src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java)28
-rw-r--r--music-core/src/main/java/org/onap/music/exceptions/MusicDeadlockException.java75
-rw-r--r--music-core/src/main/java/org/onap/music/exceptions/MusicLockingException.java (renamed from src/main/java/org/onap/music/exceptions/MusicLockingException.java)1
-rw-r--r--music-core/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java (renamed from src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java)15
-rw-r--r--music-core/src/main/java/org/onap/music/exceptions/MusicQueryException.java (renamed from src/main/java/org/onap/music/exceptions/MusicQueryException.java)1
-rw-r--r--music-core/src/main/java/org/onap/music/exceptions/MusicServiceException.java (renamed from src/main/java/org/onap/music/exceptions/MusicServiceException.java)50
-rw-r--r--music-core/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java613
-rw-r--r--music-core/src/main/java/org/onap/music/lockingservice/cassandra/LockCleanUpDaemon.java133
-rw-r--r--music-core/src/main/java/org/onap/music/lockingservice/cassandra/LockType.java (renamed from musictrigger/src/JSONObject.java)24
-rw-r--r--music-core/src/main/java/org/onap/music/lockingservice/cassandra/MusicLockState.java (renamed from src/main/java/org/onap/music/lockingservice/MusicLockState.java)34
-rw-r--r--music-core/src/main/java/org/onap/music/main/CipherUtil.java279
-rw-r--r--music-core/src/main/java/org/onap/music/main/CorePropertiesLoader.java120
-rw-r--r--music-core/src/main/java/org/onap/music/main/DeadlockDetectionUtil.java152
-rw-r--r--music-core/src/main/java/org/onap/music/main/MusicCore.java264
-rw-r--r--music-core/src/main/java/org/onap/music/main/MusicUtil.java881
-rw-r--r--music-core/src/main/java/org/onap/music/main/ResultType.java (renamed from src/main/java/org/onap/music/main/ResultType.java)7
-rw-r--r--music-core/src/main/java/org/onap/music/main/ReturnType.java (renamed from src/main/java/org/onap/music/main/ReturnType.java)5
-rw-r--r--music-core/src/main/java/org/onap/music/service/MusicCoreService.java189
-rw-r--r--music-core/src/main/java/org/onap/music/service/impl/MusicCassaCore.java1236
-rw-r--r--music-core/src/main/resources/LICENSE.txt (renamed from src/main/resources/LICENSE.txt)0
-rw-r--r--music-core/src/main/resources/Resources.properties (renamed from src/main/resources/Resources.properties)0
-rw-r--r--music-core/src/main/resources/logback.xml273
-rw-r--r--music-core/src/main/resources/project.properties5
-rw-r--r--music-core/src/main/webapp/WEB-INF/.gitignore1
-rw-r--r--music-core/src/test/java/LICENSE.txt (renamed from src/test/java/LICENSE.txt)0
-rw-r--r--music-core/src/test/java/org/onap/music/cassandra/MusicUtilTest.java345
-rw-r--r--music-core/src/test/java/org/onap/music/datastore/ConditionTest.java61
-rw-r--r--music-core/src/test/java/org/onap/music/datastore/MusicDataStoreTest.java436
-rw-r--r--music-core/src/test/java/org/onap/music/datastore/PreparedQueryObjectTest.java101
-rw-r--r--music-core/src/test/java/org/onap/music/datastore/jsonobjects/JSONObjectTest.java54
-rw-r--r--music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonDeleteTest.java (renamed from src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java)47
-rw-r--r--music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonIndexTest.java (renamed from src/test/java/org/onap/music/unittests/jsonobjects/JsonOnboardTest.java)66
-rw-r--r--music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonInsertTest.java176
-rw-r--r--music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonKeySpaceTest.java (renamed from src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java)4
-rw-r--r--music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonLockTest.java50
-rw-r--r--music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonSelectTest.java (renamed from src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java)60
-rw-r--r--music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonTableTest.java (renamed from src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java)72
-rw-r--r--music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonUpdateTest.java (renamed from src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java)67
-rw-r--r--music-core/src/test/java/org/onap/music/datastore/jsonobjects/RowIdentifierTest.java60
-rw-r--r--music-core/src/test/java/org/onap/music/eelf/logging/format/AppMessagesTest.java65
-rw-r--r--music-core/src/test/java/org/onap/music/eelf/logging/format/ErrorSeverityTest.java41
-rw-r--r--music-core/src/test/java/org/onap/music/eelf/logging/format/ErrorTypesTest.java (renamed from src/test/java/org/onap/music/unittests/jsonobjects/AAFResponseTest.java)48
-rw-r--r--music-core/src/test/java/org/onap/music/exceptions/MusicDeadlockExceptionTest.java135
-rw-r--r--music-core/src/test/java/org/onap/music/exceptions/MusicLockingExceptionTest.java104
-rw-r--r--music-core/src/test/java/org/onap/music/exceptions/MusicPolicyVoilationExceptionTest.java106
-rw-r--r--music-core/src/test/java/org/onap/music/exceptions/MusicQueryExceptionTest.java118
-rw-r--r--music-core/src/test/java/org/onap/music/exceptions/MusicServiceExceptionTest.java145
-rw-r--r--music-core/src/test/java/org/onap/music/lockingservice/cassandra/CassaLockStoreTest.java311
-rw-r--r--music-core/src/test/java/org/onap/music/lockingservice/cassandra/MusicLockStateTest.java86
-rw-r--r--music-core/src/test/java/org/onap/music/main/CipherUtilTest.java55
-rw-r--r--music-core/src/test/java/org/onap/music/main/DeadlockDetectionUtilTest.java87
-rw-r--r--music-core/src/test/java/org/onap/music/main/MusicCoreTest.java391
-rw-r--r--music-core/src/test/java/org/onap/music/main/ResultTypeTest.java (renamed from src/test/java/org/onap/music/unittests/ResultTypeTest.java)3
-rw-r--r--music-core/src/test/java/org/onap/music/main/ReturnTypeTest.java (renamed from src/test/java/org/onap/music/unittests/ReturnTypeTest.java)11
-rw-r--r--music-core/src/test/java/org/onap/music/service/impl/MusicCassaCoreTest.java485
-rw-r--r--music-core/src/test/java/org/onap/music/unittests/jsonobjects/JSONObjectTest.java (renamed from src/main/java/org/onap/music/datastore/jsonobjects/NameSpace.java)39
-rw-r--r--music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java (renamed from src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java)8
-rw-r--r--music-core/src/test/java/org/onap/music/unittests/jsonobjects/MusicHealthCheckTest.java (renamed from src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java)31
-rw-r--r--music-core/src/test/resources/LICENSE.txt24
-rw-r--r--music-core/src/test/resources/Resources.properties50
-rw-r--r--music-core/src/test/resources/application.properties2
-rw-r--r--music-core/src/test/resources/cache.ccf (renamed from src/main/resources/cache.ccf)26
-rw-r--r--music-core/src/test/resources/logback.xml (renamed from src/main/resources/logback.xml)49
-rw-r--r--music-core/src/test/resources/mockito-extensions/org.mockito.plugins.MockMaker1
-rw-r--r--music-core/src/test/resources/mockito-extensions/org.mockito.plugins.StackTraceCleanerProvider1
-rw-r--r--music-core/src/test/resources/project.properties (renamed from src/main/resources/project.properties)0
-rw-r--r--music-rest/distribution/README.md (renamed from distribution/README.md)0
-rw-r--r--music-rest/distribution/cassandra/Dockerfile (renamed from distribution/cassandra/Dockerfile)0
-rw-r--r--music-rest/distribution/cassandra/cassandra.yaml (renamed from distribution/cassandra/cassandra.yaml)0
-rw-r--r--music-rest/distribution/cassandra/docker-entrypoint.sh107
-rw-r--r--music-rest/distribution/cassandra_job/Dockerfile30
-rw-r--r--music-rest/distribution/cassandra_job/admin.cql (renamed from distribution/cassandra_job/admin.cql)0
-rw-r--r--music-rest/distribution/cassandra_job/admin_pw.cql (renamed from distribution/cassandra_job/admin_pw.cql)0
-rw-r--r--music-rest/distribution/cassandra_job/runcql.sh112
-rw-r--r--music-rest/distribution/cassandra_job/test.cql (renamed from distribution/cassandra_job/test.cql)0
-rw-r--r--music-rest/distribution/music/Dockerfile35
-rw-r--r--music-rest/distribution/music/startup.sh68
-rwxr-xr-xmusic-rest/pom.xml385
-rw-r--r--music-rest/src/main/java/LICENSE.txt24
-rwxr-xr-xmusic-rest/src/main/java/org/onap/music/JerseyConfig.java87
-rwxr-xr-xmusic-rest/src/main/java/org/onap/music/MusicApplication.java208
-rw-r--r--music-rest/src/main/java/org/onap/music/authentication/AuthUtil.java276
-rw-r--r--music-rest/src/main/java/org/onap/music/authentication/AuthorizationError.java55
-rw-r--r--music-rest/src/main/java/org/onap/music/authentication/CadiAuthFilter.java65
-rw-r--r--music-rest/src/main/java/org/onap/music/authentication/MusicAuthorizationFilter.java122
-rw-r--r--music-rest/src/main/java/org/onap/music/conductor/conditionals/JsonConditional.java90
-rw-r--r--music-rest/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java391
-rw-r--r--music-rest/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java205
-rw-r--r--music-rest/src/main/java/org/onap/music/conductor/conditionals/UpdateDataObject.java119
-rw-r--r--music-rest/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java138
-rw-r--r--music-rest/src/main/java/org/onap/music/eelf/logging/MusicContainerFilter.java68
-rw-r--r--music-rest/src/main/java/org/onap/music/eelf/logging/MusicLoggingServletFilter.java207
-rw-r--r--music-rest/src/main/java/org/onap/music/exceptions/MusicAuthenticationException.java (renamed from src/main/java/org/onap/music/datastore/PreparedQueryObject.java)56
-rw-r--r--music-rest/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java (renamed from src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java)23
-rw-r--r--music-rest/src/main/java/org/onap/music/main/PropertiesLoader.java373
-rw-r--r--music-rest/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java (renamed from src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java)127
-rw-r--r--music-rest/src/main/java/org/onap/music/rest/Application.java79
-rwxr-xr-xmusic-rest/src/main/java/org/onap/music/rest/RestMusicDataAPI.java1052
-rw-r--r--music-rest/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java124
-rw-r--r--music-rest/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java632
-rwxr-xr-xmusic-rest/src/main/java/org/onap/music/rest/RestMusicQAPI.java443
-rw-r--r--music-rest/src/main/java/org/onap/music/rest/RestMusicTestAPI.java (renamed from src/main/java/org/onap/music/rest/RestMusicTestAPI.java)45
-rw-r--r--music-rest/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java (renamed from src/main/java/org/onap/music/rest/RestMusicVersionAPI.java)50
-rwxr-xr-xmusic-rest/src/main/resources/application.properties9
-rw-r--r--music-rest/src/main/resources/key.properties1
-rw-r--r--music-rest/src/test/java/LICENSE.txt24
-rw-r--r--music-rest/src/test/java/org/onap/music/JerseyConfigTest.java (renamed from src/main/java/org/onap/music/lockingservice/LockListener.java)42
-rw-r--r--music-rest/src/test/java/org/onap/music/conductor/conditionals/JsonConditionalTest.java82
-rw-r--r--music-rest/src/test/java/org/onap/music/conductor/conditionals/UpdateDataObjectTest.java98
-rw-r--r--music-rest/src/test/java/org/onap/music/eelf/healthcheck/MusicHealthCheckTest.java61
-rw-r--r--music-rest/src/test/java/org/onap/music/eelf/logging/MusicContainerFilterTest.java55
-rw-r--r--music-rest/src/test/java/org/onap/music/eelf/logging/MusicLoggingServletFilterTest.java64
-rw-r--r--music-rest/src/test/java/org/onap/music/exceptions/MusicExceptionMapperTest.java61
-rw-r--r--music-rest/src/test/java/org/onap/music/main/PropertiesLoaderTest.java146
-rw-r--r--music-rest/src/test/java/org/onap/music/rest/ApplicationTest.java94
-rw-r--r--music-rest/src/test/java/org/onap/music/rest/RestMusicTestAPITest.java66
-rw-r--r--music-rest/src/test/java/org/onap/music/rest/RestMusicVersionAPITest.java63
-rw-r--r--music-rest/src/test/java/org/onap/music/unittests/CassandraCQL.java (renamed from src/test/java/org/onap/music/unittests/CassandraCQL.java)77
-rw-r--r--music-rest/src/test/java/org/onap/music/unittests/JsonResponseTest.java (renamed from src/test/java/org/onap/music/unittests/JsonResponseTest.java)84
-rw-r--r--music-rest/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java (renamed from src/test/java/org/onap/music/unittests/MusicDataStoreTest.java)28
-rw-r--r--music-rest/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java (renamed from src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java)300
-rw-r--r--music-rest/src/test/java/org/onap/music/unittests/TestsUsingCassandra.java116
-rw-r--r--music-rest/src/test/java/org/onap/music/unittests/TstRestMusicConditionalAPI.java373
-rw-r--r--music-rest/src/test/java/org/onap/music/unittests/TstRestMusicDataAPI.java1161
-rw-r--r--music-rest/src/test/java/org/onap/music/unittests/TstRestMusicLockAPI.java768
-rw-r--r--music-rest/src/test/java/org/onap/music/unittests/authentication/AuthUtilTest.java123
-rw-r--r--music-rest/src/test/java/org/onap/music/unittests/authentication/AuthorizationErrorTest.java51
-rw-r--r--music-rest/src/test/java/org/onap/music/unittests/authentication/CadiAuthFilterTest.java63
-rw-r--r--music-rest/src/test/resources/logback.xml302
-rw-r--r--musictrigger/assembly.xml22
-rw-r--r--musictrigger/pom.xml62
-rwxr-xr-xmusictrigger/src/MusicTrigger.java221
-rwxr-xr-xpom.xml449
-rw-r--r--postman/MusicLocal.postman_collection.json1386
-rw-r--r--releases/3.2.34.yaml5
-rw-r--r--releases/3.2.35.yaml5
-rw-r--r--releases/3.2.38-container.yaml8
-rw-r--r--releases/3.2.38.yaml5
-rw-r--r--releases/3.2.39-container.yaml8
-rw-r--r--releases/3.2.39.yaml5
-rw-r--r--releases/3.2.40-container.yaml8
-rw-r--r--releases/3.2.40.yaml5
-rw-r--r--src/main/java/org/onap/music/conductor/conditionals/JsonConditional.java89
-rw-r--r--src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java358
-rw-r--r--src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java220
-rw-r--r--src/main/java/org/onap/music/datastore/MusicDataStore.java483
-rwxr-xr-xsrc/main/java/org/onap/music/datastore/jsonobjects/JSONCallbackResponse.java89
-rwxr-xr-xsrc/main/java/org/onap/music/datastore/jsonobjects/JsonCallback.java135
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java89
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java132
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java77
-rwxr-xr-xsrc/main/java/org/onap/music/datastore/jsonobjects/JsonNotification.java119
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/JsonNotifyClientResponse.java59
-rwxr-xr-xsrc/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java83
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java144
-rw-r--r--src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java133
-rw-r--r--src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java151
-rw-r--r--src/main/java/org/onap/music/eelf/logging/format/AppMessages.java183
-rw-r--r--src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java106
-rw-r--r--src/main/java/org/onap/music/lockingservice/MusicLockingService.java168
-rw-r--r--src/main/java/org/onap/music/lockingservice/ProtocolSupport.java210
-rw-r--r--src/main/java/org/onap/music/lockingservice/ZNodeName.java118
-rw-r--r--src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java363
-rw-r--r--src/main/java/org/onap/music/lockingservice/ZooKeeperOperation.java42
-rwxr-xr-xsrc/main/java/org/onap/music/main/CachingUtil.java441
-rw-r--r--src/main/java/org/onap/music/main/CronJobManager.java112
-rw-r--r--src/main/java/org/onap/music/main/MusicCore.java1002
-rw-r--r--src/main/java/org/onap/music/main/MusicDigest.java78
-rwxr-xr-xsrc/main/java/org/onap/music/main/MusicUtil.java633
-rwxr-xr-xsrc/main/java/org/onap/music/main/PropertiesListener.java156
-rwxr-xr-xsrc/main/java/org/onap/music/rest/RestMusicAdminAPI.java845
-rw-r--r--src/main/java/org/onap/music/rest/RestMusicBmAPI.java307
-rwxr-xr-xsrc/main/java/org/onap/music/rest/RestMusicDataAPI.java1467
-rw-r--r--src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java120
-rw-r--r--src/main/java/org/onap/music/rest/RestMusicLocksAPI.java424
-rwxr-xr-xsrc/main/java/org/onap/music/rest/RestMusicQAPI.java492
-rw-r--r--src/test/java/org/onap/music/unittests/MusicUtilTest.java207
-rw-r--r--src/test/java/org/onap/music/unittests/TestLockStore.java53
-rw-r--r--src/test/java/org/onap/music/unittests/TestMusicCore.java678
-rw-r--r--src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java176
-rw-r--r--src/test/java/org/onap/music/unittests/TestRestAdminData.java2244
-rw-r--r--src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java86
-rwxr-xr-xversion.properties4
312 files changed, 24698 insertions, 17032 deletions
diff --git a/.gitignore b/.gitignore
index c795c9e7..62501cf8 100644
--- a/.gitignore
+++ b/.gitignore
@@ -15,6 +15,10 @@ src/main/webapp
.DS_Store
._*
+# Ignore jars
+**/*.jar
+*.jar
+
.metadata
# Eclipse stuff
@@ -29,3 +33,11 @@ debug-logs/
docs/Makefile
docs/_build
docs/conf.py
+
+#VSCODE
+.VSCODE
+.attach_pid*
+
+
+#jmeter
+jmeter.log
diff --git a/.readthedocs.yaml b/.readthedocs.yaml
new file mode 100644
index 00000000..3797dc8b
--- /dev/null
+++ b/.readthedocs.yaml
@@ -0,0 +1,20 @@
+---
+# .readthedocs.yml
+# Read the Docs configuration file
+# See https://docs.readthedocs.io/en/stable/config-file/v2.html for details
+# Required
+version: 2
+
+formats:
+ - htmlzip
+
+build:
+ image: latest
+
+python:
+ version: 3.7
+ install:
+ - requirements: docs/requirements-docs.txt
+
+sphinx:
+ configuration: docs/conf.py
diff --git a/Dockerfile b/Dockerfile
deleted file mode 100644
index 0c06fba5..00000000
--- a/Dockerfile
+++ /dev/null
@@ -1,4 +0,0 @@
-FROM busybox:latest
-RUN mkdir -p app
-COPY maven/ app/
-CMD ["tail", "-f", "/dev/null"]
diff --git a/INFO.yaml b/INFO.yaml
index e69de29b..12fca82f 100644
--- a/INFO.yaml
+++ b/INFO.yaml
@@ -0,0 +1,63 @@
+---
+project: 'music'
+project_creation_date: '2018-01-17'
+lifecycle_state: 'Incubation'
+project_category: ''
+project_lead: &onap_releng_ptl
+ name: 'Bharath Balasubramanian'
+ email: 'bharathb@research.att.com'
+ id: 'bharathb'
+ company: 'ATT'
+ timezone: 'America/New_York'
+primary_contact: *onap_releng_ptl
+issue_tracking:
+ type: 'jira'
+ url: 'https://jira.onap.org/projects/MUSIC'
+ key: 'MUSIC'
+mailing_list:
+ type: 'groups.io'
+ url: 'lists.onap.org'
+ tag: '<[sub-project_name]>'
+realtime_discussion: ''
+meetings:
+ - type: 'zoom'
+ agenda: 'https://wiki.onap.org/display/DW/MUSIC+Project'
+ url: 'https://wiki.onap.org/display/DW/MUSIC+Project'
+ server: 'n/a'
+ channel: 'n/a'
+ repeats: 'weekly'
+ time: '14:00 UTC'
+repositories:
+ - 'music'
+ - 'music-distributed-kv-store'
+ - 'music-mdbc'
+ - 'music-prom'
+committers:
+ - <<: *onap_releng_ptl
+ - name: 'Thomas Nelson'
+ email: 'tn1381@att.com'
+ company: 'ATT'
+ id: 'arthurdent3'
+ timezone: 'America/New_York'
+ - name: 'Brendan Tschaen'
+ email: 'bptschaen@gmail.com'
+ company: 'ATT'
+ id: 'bptschaen'
+ timezone: 'America/New_York'
+ - name: 'Greg Waines'
+ email: 'greg.waines@windriver.com'
+ company: 'Windriver'
+ id: 'gwaines'
+ timezone: 'America/Canada'
+ - name: 'Viswanath Kumar Skand Priya'
+ email: 'viswanath.kumarskandpriya@verizon.com'
+ company: 'Verizon'
+ id: 'kspviswa-vz'
+ timezone: 'Asia/Kolkata'
+ - name: 'Shashank Kumar Shankar'
+ email: 'shashank.kumar.shankar@intel.com'
+ company: 'Intel'
+ id: 'shashank.kumar....'
+ timezone: 'America/Los_Angeles'
+tsc:
+ approval: 'https://lists.onap.org/pipermail/onap-tsc'
diff --git a/README.md b/README.md
index 3f83f2da..e826f7c0 100644
--- a/README.md
+++ b/README.md
@@ -1,6 +1,6 @@
## MUSIC - Multi-site State Coordination Service
-To achieve 5 9s of availability on 3 9s or lower software and infrastructure in a cost-effective manner, ONAP components need to work in a reliable, active-active manner across multiple sites (platform-maturity resiliency level 3). A fundamental aspect of this is state management across geo-distributed sites in a reliable, scalable, highly available and efficient manner. This is an important and challenging problem because of three fundamental reasons:
+To truly achieve 5 9s of availability on 3 9s or lower software and infrastructure in a cost-effective manner, ONAP components need to work in a reliable, active-active manner across multiple sites (platform-maturity resiliency level 3). A fundamental aspect of this is state management across geo-distributed sites in a reliable, scalable, highly available and efficient manner. This is an important and challenging problem because of three fundamental reasons:
* Current solutions for state-management of ONAP components like MariaDB clustering, that work very effectively within a site, may not scale across geo-distributed sites (e.g., Beijing, Amsterdam and Irvine) or allow partitioned operation (thereby compromising availability). This is mainly because WAN latencies are much higher across sites and frequent network partitions can occur.
@@ -32,25 +32,19 @@ MUSIC is to be installed in a single Dir.
/opt/app/music/etc
/opt/app/music/logs
```
-When installing Tomcat, Cassandra and Zookeeper they should also be installed here.
+When installing Cassandra it should also be installed here.
```bash
/opt/app/music/apache-cassandra-n.n.n
-/opt/app/music/zookeeper-n.n.n
-/opt/app/music/apache-tomcat-n.n.n
```
Its suggested you create links from install dirs to a common name ie:
```bash
ln -s /opt/app/music/apache-cassandra-n.n.n cassandra
-ln -s /opt/app/music/zookeeper-n.n.n zookeeper
-ln -s /opt/app/music/apache-tomcat-n.n.n tomcat
```
-Cassandra and Zookeeper have data dirs.
+Cassandra has data dirs.
```bash
# For cassandra it should be (This is the default)
/opt/app/music/cassandra/data
-# For Zookeeper it should be
-/opt/app/music/var/zookeeper/
```
If you are using a VM make sure it has at least 8 GB of RAM (It may work with 4 GB, but with 2 GB it
@@ -69,7 +63,6 @@ does give issues).
- Ensure you have java jdk 8 or above working on your machine.
- Download apache Apache Cassandra 3.2, install into /opt/app/music and follow these instructions http://cassandra.apache.org/doc/latest/getting_started/installing.html till and including Step
- By the end of this you should have Cassandra working.
-- Download Apache Zookeeper 3.4.6, install into /opt/app/music and follow these instructions https://zookeeper.apache.org/doc/trunk/zookeeperStarted.html pertaining to the standalone operation. By the end of this you should have Zookeeper working.
- Create a music.properties file and place it in /opt/app/music/etc/. Here is a sample of the file:
```properties
@@ -80,7 +73,6 @@ all.public.ips=localhost
#######################################
# Optional current values are defaults
#######################################
-#zookeeper.host=localhost
#cassandra.host=localhost
#music.ip=localhost
#debug=true
@@ -92,10 +84,11 @@ aaf.endpoint.url=http://aafendpoint/proxy/authz/nss/
```
- Make a dir /opt/app/music/logs MUSIC dir with MUSIC logs will be created in this dir after MUSIC starts.
-- Download the latest Apache Tomcat and install it using these instructions http://tecadmin.net/install-tomcat-9-on-ubuntu/ (this is for version 9).
-- Build the MUSIC.war (or download it from https://github.com/att/music/blob/master/MUSIC.war) and place it within the webapps folder of the tomcat installation.
- Authentications/AAF Setup For Authentication setup.
-- Start tomcat and you should now have MUSIC running.
+- Start MUSIC using the jar built in distribution/music folder
+```bash
+java -jar music.jar
+```
Extra Cassandra information for Authentication:
@@ -207,50 +200,6 @@ cassandra.password=<new_password>
To access keyspace through cqlsh, login with credentials that are passed to MUSIC while creating the keyspace.
-#### Zookeeper:
-
-Once zookeeper has been installed on all the nodes, modify the zk_install_location/conf/zoo.cfg on all the nodes with the following lines:
-```properties
-tickTime=2000
-dataDir=/opt/app/music/var/zookeeper
-clientPort=2181
-initLimit=5
-syncLimit=2
-quorumListenOnAllIPs=true
-server.1=public IP of node 1:2888:3888
-server.2=public IP of node 2:2888:3888
-server.3=public IP of node 3:2888:3888
-```
-In /opt/app/music/var/zookeeper in all the machines, create a file called myid that contains the id of the machine. The machine running node.i will contain just the number i in the file myid.
-
-Start each of the nodes one by one from the zk_install_location/bin folder using the command:
-```bash
-./zkServer.sh start
-```
-On each node check the file zookeeper.out in the zk_install_location/ bin to make sure all the machines are talking to each other and there are no errors. Note that while the machines are yet to come up there maybe error messages saying that connection has not yet been established. Clearly, this is ok.
-
-If there are no errors, then from zk_install_location/bin simply run the following to get command line access to zookeeper. ./zkCli.sh
-
-Run these commands on different machines to make sure the zk nodes are syncing.
-```bash
-[zkshell] ls /
-[zookeeper]
-```
-Next, create a new znode by running
-```bash
-create /zk_test my_data.
-```
-This creates a new znode and associates the string "my_data" with the node. You should see:
-```bash
-[zkshell] create /zk_test my_data
-Created /zk_test
-```
-Issue another ls / command to see what the directory looks like:
-```bash
-[zkshell] ls /
-[zookeeper, zk_test]
-```
-
#### MUSIC
Create a music.properties file and place it in /opt/app/music/etc at each node. Here is a sample of the file: If this location is to be changed please update the file project.properties in the src/main/resources directory before compiling MUSIC to a war.
@@ -263,7 +212,6 @@ all.public.ips=public IP of node 0:public IP of node 1:public IP of node 2
#######################################
# Optional current values are defaults
#######################################
-#zookeeper.host=localhost
#cassandra.host=localhost
#music.ip=localhost
#debug=true
diff --git a/WebContent/WEB-INF/music.properties.sample b/WebContent/WEB-INF/music.properties.sample
index d562429b..41b919fe 100644
--- a/WebContent/WEB-INF/music.properties.sample
+++ b/WebContent/WEB-INF/music.properties.sample
@@ -6,7 +6,6 @@ all.public.ips=12.13.14.45:12.13.14.46:12.13.14.47
#######################################
# Optional current values are defaults
#######################################
-#zookeeper.host=localhost
#cassandra.host=localhost
#music.ip=localhost
#debug=true
@@ -15,5 +14,7 @@ all.public.ips=12.13.14.45:12.13.14.46:12.13.14.47
# Cassandra Username and password
cassandra.user=cassandra
cassandra.password=cassandra
+cassandra.connecttimeoutms=5000
+cassandra.readtimeoutms=5000
# AAF Endpoint
aaf.endpoint.url=http://aafendpoint/proxy/authz/nss/ \ No newline at end of file
diff --git a/WebContent/WEB-INF/web.xml b/WebContent/WEB-INF/web.xml
index 7b6caf4c..f6c4986e 100644
--- a/WebContent/WEB-INF/web.xml
+++ b/WebContent/WEB-INF/web.xml
@@ -1,15 +1,17 @@
<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0">
<display-name>MUSIC</display-name>
+ <!--
<listener>
- <listener-class>
- org.onap.music.main.PropertiesListener
- </listener-class>
+ <listener-class>
+ org.onap.music.main.PropertiesListener
+ </listener-class>
</listener>
+ -->
<listener>
- <listener-class>
- org.onap.music.main.CronJobManager
- </listener-class>
+ <listener-class>
+ org.onap.music.main.CronJobManager
+ </listener-class>
</listener>
<servlet>
<servlet-name>music-servlet</servlet-name>
diff --git a/distribution/cassandra/docker-entrypoint.sh b/distribution/cassandra/docker-entrypoint.sh
deleted file mode 100644
index 20bf272f..00000000
--- a/distribution/cassandra/docker-entrypoint.sh
+++ /dev/null
@@ -1,96 +0,0 @@
-#!/bin/bash
-set -e
-
-# Removal for issues with Kubernetes - Need to make sure any injected files
-# Are chown 664 or ID is smae ID as Cassandra in Container.
-#for f in /docker-entrypoint-initdb.d/*.cql; do
-# chown cassandra.root "$f"
-#done
-
-
-# first arg is `-f` or `--some-option`
-# or there are no args
-if [ "$#" -eq 0 ] || [ "${1#-}" != "$1" ]; then
- set -- cassandra -f "$@"
-fi
-
-# allow the container to be started with `--user`
-if [ "$1" = 'cassandra' -a "$(id -u)" = '0' ]; then
- chown -R cassandra /var/lib/cassandra /var/log/cassandra "$CASSANDRA_CONFIG"
- exec gosu cassandra "$BASH_SOURCE" "$@"
-fi
-
-if [ "$1" = 'cassandra' ]; then
- : ${CASSANDRA_RPC_ADDRESS='0.0.0.0'}
-
- : ${CASSANDRA_LISTEN_ADDRESS='auto'}
- if [ "$CASSANDRA_LISTEN_ADDRESS" = 'auto' ]; then
- CASSANDRA_LISTEN_ADDRESS="$(hostname --ip-address)"
- fi
-
- : ${CASSANDRA_BROADCAST_ADDRESS="$CASSANDRA_LISTEN_ADDRESS"}
-
- if [ "$CASSANDRA_BROADCAST_ADDRESS" = 'auto' ]; then
- CASSANDRA_BROADCAST_ADDRESS="$(hostname --ip-address)"
- fi
- : ${CASSANDRA_BROADCAST_RPC_ADDRESS:=$CASSANDRA_BROADCAST_ADDRESS}
-
- if [ -n "${CASSANDRA_NAME:+1}" ]; then
- : ${CASSANDRA_SEEDS:="cassandra"}
- fi
- : ${CASSANDRA_SEEDS:="$CASSANDRA_BROADCAST_ADDRESS"}
-
- sed -ri 's/(- seeds:).*/\1 "'"$CASSANDRA_SEEDS"'"/' "$CASSANDRA_CONFIG/cassandra.yaml"
-
- for yaml in \
- broadcast_address \
- broadcast_rpc_address \
- cluster_name \
- endpoint_snitch \
- listen_address \
- num_tokens \
- rpc_address \
- start_rpc \
- ; do
- var="CASSANDRA_${yaml^^}"
- val="${!var}"
- if [ "$val" ]; then
- sed -ri 's/^(# )?('"$yaml"':).*/\2 '"$val"'/' "$CASSANDRA_CONFIG/cassandra.yaml"
- fi
- done
-
- for rackdc in dc rack; do
- var="CASSANDRA_${rackdc^^}"
- val="${!var}"
- if [ "$val" ]; then
- sed -ri 's/^('"$rackdc"'=).*/\1 '"$val"'/' "$CASSANDRA_CONFIG/cassandra-rackdc.properties"
- fi
- done
-fi
-
-echo "Updating username and password"
-for f in /docker-entrypoint-initdb.d/music*.cql; do
- if [ "${CASSUSER}" ]; then
- sed -ri 's/CASSUSER/'${CASSUSER}'/' "$f"
- fi
- if [ "${CASSPASS}" ]; then
- sed -ri 's/CASSPASS/'${CASSPASS}'/' "$f"
- fi
-done
-echo "Updating username and password - Complete"
-
-
-
-
-echo "################################ Let run cql's ##############################"
-for f in /docker-entrypoint-initdb.d/*; do
-
- case "$f" in
- *.cql)
- echo "$0: running $f" && until cqlsh -u cassandra -p cassandra -f "$f"; do >&2 echo "Cassandra is unavailable - sleeping"; sleep 2; done & ;;
- *) echo "$0: ignoring $f" ;;
- esac
- echo
-done
-
-exec "$@"
diff --git a/distribution/cassandra/music.cql b/distribution/cassandra/music.cql
deleted file mode 100644
index d991a514..00000000
--- a/distribution/cassandra/music.cql
+++ /dev/null
@@ -1,20 +0,0 @@
-CREATE KEYSPACE admin
- WITH REPLICATION = {
- 'class' : 'SimpleStrategy',
- 'replication_factor': 1
- }
- AND DURABLE_WRITES = true;
-
-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)
-);
-
-CREATE USER nelson24 WITH PASSWORD ‘winman123’ SUPERUSER;
-ALTER USER cassandra WITH PASSWORD ‘SomeLongRandomStringNoonewillthinkof’;
diff --git a/distribution/cassandra/music_single.cql b/distribution/cassandra/music_single.cql
deleted file mode 100644
index b8a60cd1..00000000
--- a/distribution/cassandra/music_single.cql
+++ /dev/null
@@ -1,20 +0,0 @@
-CREATE KEYSPACE IF NOT EXISTS admin
- WITH REPLICATION = {
- 'class' : 'SimpleStrategy',
- 'replication_factor': 1
- }
- AND DURABLE_WRITES = true;
-
-CREATE TABLE IF NOT EXISTS admin.keyspace_master (
- uuid uuid,
- keyspace_name text,
- application_name text,
- is_api boolean,
- password text,
- username text,
- is_aaf boolean,
- PRIMARY KEY (uuid)
-);
-
-CREATE ROLE IF NOT EXISTS CASSUSER WITH PASSWORD = 'CASSPASS' AND SUPERUSER = True AND LOGIN = True;
-ALTER ROLE cassandra WITH PASSWORD = 'SomeLongRandomStringNoonewillthinkof';
diff --git a/distribution/cassandra_job/Dockerfile b/distribution/cassandra_job/Dockerfile
deleted file mode 100644
index 528c3bf4..00000000
--- a/distribution/cassandra_job/Dockerfile
+++ /dev/null
@@ -1,9 +0,0 @@
-#registry.hub.docker.com/
-FROM library/cassandra:3.11
-ENV DEF_USER=cassandra
-ENV DEF_PASS=cassandra
-COPY runcql.sh /
-RUN mkdir -p cql/extra && \
- chmod 755 runcql.sh && \
- chown cassandra runcql.sh
-CMD ["/runcql.sh"]
diff --git a/distribution/cassandra_job/runcql.sh b/distribution/cassandra_job/runcql.sh
deleted file mode 100644
index e1fb31fc..00000000
--- a/distribution/cassandra_job/runcql.sh
+++ /dev/null
@@ -1,31 +0,0 @@
-#! /bin/bash
-if [ $CASS_HOSTNAME ]; then
- echo "#############################################"
- echo "############## Let run cql's ################"
- echo "#############################################"
- echo "admin.cql file:"
- cat /cql/admin.cql
- echo "Running cqlsh -u $DEF_USER -p $DEF_PASS -f /cql/admin.cql ${CASS_HOSTNAME} ${PORT}"
- sleep 1;
- if cqlsh -u $DEF_USER -p $DEF_PASS -f /cql/admin.cql ${CASS_HOSTNAME} ${PORT}; then echo "success"; else echo "failure" && exit 1;fi
- echo "admin_pw.cql file:"
- cat /cql/admin_pw.cql
- echo "Running cqlsh -u $DEF_USER -p $DEF_PASS -f /cql/admin_pw.cql ${CASS_HOSTNAME} ${PORT}"
- sleep 1;
- if cqlsh -u $DEF_USER -p $DEF_PASS -f /cql/admin_pw.cql ${CASS_HOSTNAME} ${PORT}; then echo "success"; else echo "failure" && exit 1;fi
-
- for f in /cql/extra/*; do
- case "$f" in
- *.cql)
- echo "$0: running $f" && cqlsh -u ${USERNAME} -p ${PASSWORD} -f "$f" ${CASS_HOSTNAME} ${PORT};
- ;;
- *)
- echo "$0: ignoring $f"
- ;;
- esac
- done
-else
- echo "Missing CASS_HOSTNAME";
- exit 1;
-fi
-
diff --git a/distribution/dockermusic/README.md b/distribution/dockermusic/README.md
deleted file mode 100644
index a645ce70..00000000
--- a/distribution/dockermusic/README.md
+++ /dev/null
@@ -1,48 +0,0 @@
-### Docker Setup for Single instance of MUSIC
-
-<p>Please update the <b>properties/music.properties</b> file to fit your env.<br/>
-Update the music.sh file.<br/>
-The beginning of the <b>music.sh</b> file contains various variables.<br/></p>
-NEXUS_DOCKER_REPO - default REPO - Will read /opt/config/nexus_docker_repo.txt if other is needed.<br/>
-CASS_IMG - Cassandra Image<br/>
-TOMCAT_IMG - Tomcat Image<br/>
-ZK_IMG - Zookeeper Image<br/>
-MUSIC_IMG - Music Image containing the MUSIC war file.<br/>
-WORK_DIR - Default to PWD.<br/>
-CASS_USERNAME - Username for Cassandra - should match cassandra.user in music.properties
-file<br/>
-CASS_PASSWORD - Password for Cassandra - should match cassandra.password in music.properties.<br/>
-
-MUSIC Logs will be saved in logs/MUSIC after start of tomcat.<br/>
-
-```bash
-# Start containers
-./music.sh start
-# Stop containers
-./music.sh stop
-```
-
-If you want to check out Cassandra db with cqlsh.
-```bash
-docker exec –it music-db bash
-#at the prompt youcan run cqlsh as:
-cqlsh –u <user> -p <password>
-```
-
-Zookeeper:
-
-```bash
-docker exec –it music-zk bash
-#and then run:
-zkCli.sh
-```
-
-For other logs do <br/>
-```bash
-docker logs music-tomcat (tomcat)<br/>
-```
-to have rolling logs use –f as docker logs –f music-tomcat<br/>
-```bash
-docker logs music-zk (zookeeper)<br/>
-docker logs music-db (Cassandra )<br/>
-``` \ No newline at end of file
diff --git a/distribution/dockermusic/logs/README.md b/distribution/dockermusic/logs/README.md
deleted file mode 100644
index 88c252a7..00000000
--- a/distribution/dockermusic/logs/README.md
+++ /dev/null
@@ -1 +0,0 @@
-This folder is where the logs will be stored for MUSIC. \ No newline at end of file
diff --git a/distribution/dockermusic/music.sh b/distribution/dockermusic/music.sh
deleted file mode 100755
index b7a66f1e..00000000
--- a/distribution/dockermusic/music.sh
+++ /dev/null
@@ -1,101 +0,0 @@
-#
-# -------------------------------------------------------------------------
-# 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.
-#
-# -------------------------------------------------------------------------
-# In this example we are building a docker bridge network(music-net) for all
-# the containers
-# Then we connect the host bridge network(bridge) to the internal network(music-net)
-#
-#
-#
-SS=0
-if [ -e /opt/config/nexus_docker_repo.txt ]
-then
- NEXUS_DOCKER_REPO=$(cat /opt/config/nexus_docker_repo.txt)
-else
- NEXUS_DOCKER_REPO=nexus3.onap.org:10001
-fi
-echo "Using ${NEXUS_DOCKER_REPO} for docker Repo"
-
-CASS_IMG=${NEXUS_DOCKER_REPO}/onap/music/cassandra_music:latest
-MUSIC_IMG=${NEXUS_DOCKER_REPO}/onap/music/music:latest
-TOMCAT_IMG=library/tomcat:8.5
-ZK_IMG=library/zookeeper:3.4
-WORK_DIR=${PWD}
-CASS_USERNAME=cassandra1
-CASS_PASSWORD=cassandra1
-
-if [ "$1" = "start" ]; then
-
-# Create Volume for mapping war file and tomcat
-docker volume create music-vol;
-
-# Create a network for all the containers to run in.
-docker network create music-net;
-
-# Start Cassandra
-docker run -d --rm --name music-db --network music-net \
--p "7000:7000" -p "7001:7001" -p "7199:7199" -p "9042:9042" -p "9160:9160" \
--e CASSUSER=${CASS_USERNAME} \
--e CASSPASS=${CASS_PASSWORD} \
-${CASS_IMG};
-
-# Start Music war
-docker run -d --rm --name music-war \
--v music-vol:/app \
-${MUSIC_IMG};
-
-# Start Zookeeper
-docker run -d --rm --name music-zk --network music-net \
--p "2181:2181" -p "2888:2888" -p "3888:3888" \
-${ZK_IMG};
-
-# Delay for Cassandra
-sleep 20;
-
-# Start Up tomcat - Needs to have properties,logs dir and war file volume mapped.
-docker run -d --rm --name music-tomcat --network music-net -p "8080:8080" \
--v music-vol:/usr/local/tomcat/webapps \
--v ${WORK_DIR}/properties:/opt/app/music/etc:ro \
--v ${WORK_DIR}/logs:/opt/app/music/logs \
-${TOMCAT_IMG};
-
-# Connect tomcat to host bridge network so that its port can be seen.
-docker network connect bridge music-tomcat;
-SS=1;
-fi
-
-
-# Shutdown and clean up.
-if [ "$1" = "stop" ]; then
-docker stop music-war;
-docker stop music-db;
-docker stop music-zk;
-docker stop music-tomcat;
-docker network rm music-net;
-sleep 5;
-docker volume rm music-vol;
-SS=1
-fi
-
-if [ $SS = 0 ]; then
- echo "Please type ${0} start or ${0} stop"
-fi
-
-
-
-
-
diff --git a/distribution/dockermusic/properties/music.properties b/distribution/dockermusic/properties/music.properties
deleted file mode 100644
index 65378d8c..00000000
--- a/distribution/dockermusic/properties/music.properties
+++ /dev/null
@@ -1,19 +0,0 @@
-my.public.ip=localhost
-all.public.ips=localhost
-my.id=0
-all.ids=0
-#######################################
-# Optional current values are defaults
-#######################################
-zookeeper.host=music-zk
-cassandra.host=music-db
-#music.ip=localhost
-#debug=true
-#music.rest.ip=localhost
-#lock.lease.period=6000
-cassandra.user=cassandra1
-cassandra.password=cassandra1
-# AAF Endpoint if using AAF
-aaf.endpoint.url=https://aaf.api.simpledemo.onap.org
-
-
diff --git a/distribution/tomcat/Dockerfile b/distribution/tomcat/Dockerfile
deleted file mode 100644
index 7d4f2ad9..00000000
--- a/distribution/tomcat/Dockerfile
+++ /dev/null
@@ -1,3 +0,0 @@
-FROM library/tomcat:8.5
-LABEL purpose="Tomcat for MUSIC"
-
diff --git a/distribution/zookeeper/Dockerfile b/distribution/zookeeper/Dockerfile
deleted file mode 100644
index fdc89dc0..00000000
--- a/distribution/zookeeper/Dockerfile
+++ /dev/null
@@ -1,3 +0,0 @@
-FROM library/zookeeper:3.4
-LABEL purpose="For MUSIC"
-
diff --git a/docs/.gitignore b/docs/.gitignore
new file mode 100644
index 00000000..43ca5b67
--- /dev/null
+++ b/docs/.gitignore
@@ -0,0 +1,3 @@
+/.tox
+/_build/*
+/__pycache__/*
diff --git a/docs/MUSIC_USAGE.jpg b/docs/MUSIC_USAGE.jpg
new file mode 100644
index 00000000..66773c6c
--- /dev/null
+++ b/docs/MUSIC_USAGE.jpg
Binary files differ
diff --git a/docs/_static/css/ribbon.css b/docs/_static/css/ribbon.css
new file mode 100644
index 00000000..6008cb1a
--- /dev/null
+++ b/docs/_static/css/ribbon.css
@@ -0,0 +1,63 @@
+.ribbon {
+ z-index: 1000;
+ background-color: #a00;
+ overflow: hidden;
+ white-space: nowrap;
+ position: fixed;
+ top: 25px;
+ right: -50px;
+ -webkit-transform: rotate(45deg);
+ -moz-transform: rotate(45deg);
+ -ms-transform: rotate(45deg);
+ -o-transform: rotate(45deg);
+ transform: rotate(45deg);
+ -webkit-box-shadow: 0 0 10px #888;
+ -moz-box-shadow: 0 0 10px #888;
+ box-shadow: 0 0 10px #888;
+
+}
+
+.ribbon a {
+ border: 1px solid #faa;
+ color: #fff;
+ display: block;
+ font: bold 81.25% 'Helvetica Neue', Helvetica, Arial, sans-serif;
+ margin: 1px 0;
+ padding: 10px 50px;
+ text-align: center;
+ text-decoration: none;
+ text-shadow: 0 0 5px #444;
+ transition: 0.5s;
+}
+
+.ribbon a:hover {
+ background: #c11;
+ color: #fff;
+}
+
+
+/* override table width restrictions */
+@media screen and (min-width: 767px) {
+
+ .wy-table-responsive table td, .wy-table-responsive table th {
+ /* !important prevents the common CSS stylesheets from overriding
+ this as on RTD they are loaded after this stylesheet */
+ white-space: normal !important;
+ }
+
+ .wy-table-responsive {
+ overflow: visible !important;
+ }
+}
+
+@media screen and (max-width: 767px) {
+ .wy-table-responsive table td {
+ white-space: nowrap;
+ }
+}
+
+/* fix width of the screen */
+
+.wy-nav-content {
+ max-width: none;
+}
diff --git a/docs/_static/favicon.ico b/docs/_static/favicon.ico
new file mode 100755
index 00000000..cb712ebd
--- /dev/null
+++ b/docs/_static/favicon.ico
Binary files differ
diff --git a/docs/_static/logo_onap_2017.png b/docs/_static/logo_onap_2017.png
new file mode 100644
index 00000000..5d064f43
--- /dev/null
+++ b/docs/_static/logo_onap_2017.png
Binary files differ
diff --git a/docs/architecture.rst b/docs/architecture.rst
index ae29f9e0..73cfbc2d 100644
--- a/docs/architecture.rst
+++ b/docs/architecture.rst
@@ -1,19 +1,60 @@
.. This work is licensed under a Creative Commons Attribution 4.0 International License.
.. http://creativecommons.org/licenses/by/4.0
+.. _architecture:
Architecture
============
-` See ONAP Wiki <https://wiki.onap.org/display/DW/MUSIC-Multi-site+State+Coordination+Service>`_
+Project Description
+-------------------
+To achieve five 9s of availability on three 9s or lower software and infrastructure in a cost-effective manner, ONAP components need to work in a reliable, active-active manner across multiple sites (platform-maturity resiliency level 3). A fundamental aspect of this is state management across geo-distributed sites in a reliable, scalable, highly available and efficient manner. This is an important and challenging problem because of three fundamental reasons:
-Capabilities
+- Current solutions for state-management of ONAP components like MariaDB clustering, that work very effectively within a site, may not scale across geo-distributed sites (e.g., Beijing, Amsterdam and Irvine) or allow partitioned operation (thereby compromising availability). This is mainly because WAN latencies are much higher across sites and frequent network partitions can occur.
+
+- ONAP components often have a diverse range of requirements in terms of state replication. While some components need to synchronously manage state across replicas, others may tolerate asynchronous replication. This diversity needs to be leveraged to provide better performance and higher availability across sites.
+
+- ONAP components often need to partition state across different replicas, perform consistent operations on them and ensure that on failover, the new owner has access to the latest state. The distributed protocols to achieve such consistent ownership is complex and replete with corners cases, especially in the face of network partitions. Currently, each component is building its own handcrafted solution which is wasteful and worse, can be erroneous.
+
+In this project, we identify common state management concerns across ONAP components and provide a multi-site state coordination/management service (MUSIC) with a rich suite of recipes that each ONAP component can simply configure and use for their state-management needs.
+
+
+Functionality
+-------------
+
+At its core, MUSIC provides a scalable sharded eventually-consistent data-store (Cassandra) wherein the access to the keys can be protected using a locking service (built on Zookeeper) that is tightly coupled with the data-store. ONAP components can use the MUSIC API directly to store and access their state across geo-distributed sites. This API enables ONAP components to achieve fine-grained flexible consistency on their state.
+
+MUSIC also provides a rich set of recipes (mdbc, prom, musicCAS, musicQ) that ONAP components can use to build multi-site active-active/active-passive/federated state-management solutions:
+
+- mdbc: The most crucial recipe is a multi-site database cache (mdbc) that enable ONAP components that maintain state in a SQL database to avail the benefits of MUSIC without compromising their need to use transactional SQL DBs. These ONAP components can rely on existing db clustering techniques like MariaDB for transactionality and complex querying within a site. mdbc will intercept each of these read/write calls to the db cluster and mirror this state to other geo-distributed sites through MUSIC either synchronously or asynchronously (configurable at a table-level). For example, components like the ONAP Service Orchestrator that use MariaDB to maintain state can directly use this recipe with no change to their SQL code.
+
+- prom: MUSIC provides a recipe for policy-driven ownership management (prom) of state for ONAP components to (1) partition state across replicas during both initial placement and during failures based on their individual policies (2) ensure correct transfer of state ownership across replicas during site failures and network partitions (3) ensure that the new owner has access to the most recent version of state (if needed).
+
+- musicCAS: The distributed compare and set is a powerful primitive that will allow ONAP components to update shared state in an atomic manner. This is currently being used by the ONAP HAS (homing service) that is structured a job scheduler with multiple workers trying to pick up client-submitted jobs, while ensuring that only one of them actually performs the job.
+
+- musicQ: Implementing a geo-distributed queue is a hard problem with many performance implications when data belonging to a queue is sharded across nodes. MUSIC provides a queue API that carefully structures the data to ensure good performance. ONAP HAS (mentioned above) uses this as its job queue.
+
+
+Scope
+-----
+MUSIC is a shared service with recipes that individual ONAP components and micro-service can use for state replication, consistency management and state ownership across geo-distributed sites. MUSIC will make sure that the right service data is available at the right place, and at the right time to enable federated active-active operation of ONAP. For example, we envisage the use of MUSIC for multi-site state management in SO (to store Camunda state across sites), <SDN-C, AppC> (to store ODL related state across sites) , A&AI (to store its graph data) and most other ONAP components that need to manage state across sites.
+
+
+Out of Scope
------------
+While MUSIC is an optional solution for state-management of ONAP components across sites, OOM will continue to manage component level and platform level deployment, scalability, redundancy, resiliency, self-healing and high availability on top of Kubernetes across sites for ONAP.
-Usage Scenarios
----------------
+Usage
+-----
+MUSIC and its recipes export a REST API apart from mdbc which is implemented as a jdbc driver to enable seamless integration with SQL-based ONAP components.
-Interactions
+
+Architecture
------------
+The figures below how MUSIC can be used in a general context and also provide a specific example of its potential usage in ONAP SO.
+
+.. image:: MUSIC_USAGE.jpg
+
+
diff --git a/docs/conf.py b/docs/conf.py
new file mode 100644
index 00000000..96a85251
--- /dev/null
+++ b/docs/conf.py
@@ -0,0 +1,15 @@
+from docs_conf.conf import *
+
+branch = 'latest'
+master_doc = 'index'
+
+linkcheck_ignore = [
+ 'http://localhost',
+]
+
+intersphinx_mapping = {}
+
+html_last_updated_fmt = '%d-%b-%y %H:%M'
+
+def setup(app):
+ app.add_stylesheet("css/ribbon.css") \ No newline at end of file
diff --git a/docs/conf.yaml b/docs/conf.yaml
new file mode 100644
index 00000000..ab592813
--- /dev/null
+++ b/docs/conf.yaml
@@ -0,0 +1,7 @@
+---
+project_cfg: onap
+project: onap
+
+# Change this to ReleaseBranchName to modify the header
+default-version: latest
+#
diff --git a/docs/delivery.rst b/docs/delivery.rst
index f3f083a7..c90ff818 100644
--- a/docs/delivery.rst
+++ b/docs/delivery.rst
@@ -27,17 +27,17 @@ Example use of a block diagram.
m -> y;
m -> z;
group l1 {
- color = blue;
- x; y; z;
- }
+ color = blue;
+ x; y; z;
+ }
group l2 {
- color = yellow;
- m; n;
- }
+ color = yellow;
+ m; n;
+ }
group l3 {
- color = orange;
- a; b; c;
- }
+ color = orange;
+ a; b; c;
+ }
}
diff --git a/docs/index.rst b/docs/index.rst
index 437a50d8..19822636 100755
--- a/docs/index.rst
+++ b/docs/index.rst
@@ -1,6 +1,7 @@
.. This work is licensed under a Creative Commons Attribution 4.0 International License.
.. http://creativecommons.org/licenses/by/4.0
.. Copyright 2017 AT&T Intellectual Property. All rights reserved.
+.. _master_index:
Music Developer Documentation
=============================
diff --git a/docs/multi.rst b/docs/multi.rst
index bc26465f..380f4ea5 100644
--- a/docs/multi.rst
+++ b/docs/multi.rst
@@ -72,63 +72,6 @@ To access keyspace through cqlsh, login with credentials that are passed to MUSI
-Zookeeper:
-----------
-Once zookeeper has been installed on all the nodes, modify the **zk_install_location/conf/zoo.cfg** on all the nodes with the following lines:
-
-::
-
- tickTime=2000
- dataDir=/opt/app/music/var/zookeeper
- clientPort=2181
- initLimit=5
- syncLimit=2
- quorumListenOnAllIPs=true
- server.1=public IP of node 1:2888:3888
- server.2=public IP of node 2:2888:3888
- server.3=public IP of node 3:2888:3888
-
-Create the directory /var/zookeeper in all the machines and within that create a file called myid that contains the id of the machine. The machine running node.i will contain just the number i in the file myid.
-
-Start each of the nodes one by one from the zk_install_location/bin folder using the command:
-
-
-
- ./zkServer.sh start
-
-On each node check the file zookeeper.out in the zk_install_location/ bin to make sure all the machines are talking to each other and there are no errors. Note that while the machines are yet to come up there maybe error messages saying that connection has not yet been established. Clearly, this is ok.
-
-
-If there are no errors, then from zk_install_location/bin simply run the following to get command line access to zookeeper. ./zkCli.sh
-
-
-Run these commands on different machines to make sure the zk nodes are syncing.
-
-::
-
- [zkshell] ls /
- [zookeeper]
-
-Next, create a new znode by running
-
-::
-
- create /zk_test my_data.
-
-This creates a new znode and associates the string "my_data" with the node. You should see:
-
-::
-
- [zkshell] create /zk_test my_data
- Created /zk_test
-
-Issue another ls / command to see what the directory looks like:
-
-::
-
- [zkshell] ls /
- [zookeeper, zk_test]
-
MUSIC
Create a music.properties file and place it in /opt/app/music/etc at each node. Here is a sample of the file:
cassandra.yaml::
diff --git a/docs/offeredapis.rst b/docs/offeredapis.rst
index 3dcc7962..c75bd0c0 100644
--- a/docs/offeredapis.rst
+++ b/docs/offeredapis.rst
@@ -1,16 +1,16 @@
-.. This work is licensed under a Creative Commons Attribution 4.0 International License.
+.. This work is licensed under a
+ Creative Commons Attribution 4.0 International License.
.. http://creativecommons.org/licenses/by/4.0
+.. _offeredapis:
Offered APIs
============
-.. note::
- * This section is used to describe the external interfaces offered by a software component
-
- * This section is typically: provided for a platform-component and sdk; and
- referenced in developer guides and api reference manuals.
-
- * This note must be removed after content has been added.
+This document describes the MUSIC (Multi-site State Coordination Service) API
+To view API documentation in the interactive swagger UI download the following
+and paste into the swagger tool here: https://editor.swagger.io
+
+:download:`swagger.json <swagger.json>`
.. swaggerv2doc:: swagger.json
diff --git a/docs/release-notes.rst b/docs/release-notes.rst
index 766fb123..5e8885da 100644
--- a/docs/release-notes.rst
+++ b/docs/release-notes.rst
@@ -1,60 +1,70 @@
-.. This work is licensed under a Creative Commons Attribution 4.0 International License.
+.. This work is licensed under a
+.. Creative Commons Attribution 4.0 International License.
.. http://creativecommons.org/licenses/by/4.0
+.. _release_notes:
Release Notes
=============
-Initial Release for Beijing
+Initial Release for Frankfurt
-Version: 2.5.4
---------------
+Version: 3.2.40
+---------------
-:Release Date: 2018-06-07
+:Release Date: 2020-05-20
**New Features**
-MUSIC provides a service with recipes that individual ONAP components and microservice can use for
- - state replication across multiple geo-distributed sites
- - flexible fine-grained consistency management of state
- - policy driven state-ownership across replicas of the service
+- MUSIC now runs on a springboot server, instead of a standalone tomcat server
+- HTTPS support for clients through AAF certificates
-**Bug Fixes**
+- A background lock clean up daemon will periodically check the status of
+ current locks, cleaning up 'stale' references.
+ Clients should see a performance boost if they were previously dealing with
+ many stale locks.
+
+- Improved error messaging to the user, allowing clients to better debug their
+ applications
+
+- Continued adherence to ONAP S3P requirements
- - `MUSIC-33 <https://jira.onap.org/projects/MUSIC/issues/MUSIC-33>`_ CriticalPut is causing HTTP Status 500 – Internal Server Error
- - `MUSIC-34 <https://jira.onap.org/projects/MUSIC/issues/MUSIC-34>`_ CreateTable,InsertIntoTable,UpdateTable,DeleteFromTable,DropTable don't check resource existence
+**Bug Fixes**
+ - `MUSIC-573 <https://jira.onap.org/projects/MUSIC/issues/MUSIC-573>`_ Pods still run as root
+
+ - `MUSIC-557 <https://jira.onap.org/projects/MUSIC/issues/MUSIC-557>`_ Test coverage goals met, and migrated to new sonar location
- - `MUSIC-35 <https://jira.onap.org/projects/MUSIC/issues/MUSIC-35>`_ Onboarding issues
+ - `MUSIC-530 <https://jira.onap.org/browse/MUSIC-530>`_ Security Vulnerability in pom.xml fix
- - `MUSIC-36 <https://jira.onap.org/projects/MUSIC/issues/MUSIC-36>`_ Test Case failing
- - `MUSIC-37 <https://jira.onap.org/projects/MUSIC/issues/MUSIC-37>`_ Acquire lock to return more information
**Known Issues**
N/A
**Security Notes**
-MUSIC code has been formally scanned during build time using NexusIQ and all Critical vulnerabilities have been addressed, items that remain open have been assessed for risk and determined to be false positive. The MUSIC open Critical security vulnerabilities and their risk assessment have been documented as part of the `project <https://wiki.onap.org/pages/viewpage.action?pageId=25439359>`_.
+MUSIC code has been formally scanned during build time using NexusIQ and all Critical vulnerabilities have been addressed, items that remain open have been assessed for risk and determined to be false positive. The MUSIC open Critical security vulnerabilities and their risk assessment have been documented as part of the `project <https://wiki.onap.org/pages/viewpage.action?pageId=45285410>`_.
Quick Links:
- `MUSIC project page <https://wiki.onap.org/display/DW/MUSIC+Project>`_
+- `MUSIC Frankfurt Release <https://wiki.onap.org/display/DW/MUSIC+Frankfurt>`_
- `Passing Badge information for MUSIC <https://bestpractices.coreinfrastructure.org/en/projects/1722>`_
-- `Project Vulnerability Review Table for MUSIC <https://wiki.onap.org/pages/viewpage.action?pageId=25439359>`_
+- `MUSIC Architecture Page <TBD>`_
+- `Project Vulnerability Review Table for MUSIC <https://wiki.onap.org/pages/viewpage.action?pageId=64004601>`_
**Upgrade Notes**
- N/A
+ N/A
**Deprecation Notes**
- N/A
+ N/A
**Other**
- N/A
+ N/A
===========
diff --git a/docs/requirements-docs.txt b/docs/requirements-docs.txt
new file mode 100644
index 00000000..b3188ddd
--- /dev/null
+++ b/docs/requirements-docs.txt
@@ -0,0 +1,15 @@
+tox
+Sphinx
+doc8
+docutils
+setuptools
+six
+sphinx_rtd_theme>=0.4.3
+sphinxcontrib-blockdiag
+sphinxcontrib-needs>=0.2.3
+sphinxcontrib-nwdiag
+sphinxcontrib-seqdiag
+sphinxcontrib-swaggerdoc
+sphinxcontrib-plantuml
+sphinx_bootstrap_theme
+lfdocs-conf
diff --git a/docs/setup.rst b/docs/setup.rst
index b12acd04..7fb5bf49 100644
--- a/docs/setup.rst
+++ b/docs/setup.rst
@@ -17,27 +17,20 @@ The main MUSIC dir should be::
# These also need to be set up
/opt/app/music/etc
/opt/app/music/logs
- /opt/app/music/lib/zookeeper
-When installing Tomcat, Cassandra and Zookeeper they should also be installed here.::
+When installing, Cassandra should also be installed here.::
/opt/app/music/apache-cassandra-n.n.n
- /opt/app/music/zookeeper-n.n.n
- /opt/app/music/apache-tomcat-n.n.n
You could also create links from install dirs to a common name ie\:::
ln -s /opt/app/music/apache-cassandra-n.n.n cassandra
- ln -s /opt/app/music/zookeeper-n.n.n zookeeper
- ln -s /opt/app/music/apache-tomcat-n.n.n tomcat
-Cassandra and Zookeeper have data dirs.::
+Cassandra has data dirs.::
# For cassandra it should be (This is the default)
/opt/app/music/cassandra/data
- # For Zookeeper it should be
- /opt/app/music/zookeeper/
Continue by selecting the link to the setup you are doing.
diff --git a/docs/single.rst b/docs/single.rst
index 060f02b4..632db5ac 100644
--- a/docs/single.rst
+++ b/docs/single.rst
@@ -15,8 +15,6 @@ Instructions
- Ensure you have OpenJDK 8 on your machine.
- Download Apache Cassandra 3.0, install into /opt/app/music and follow these instructions http://cassandra.apache.org/doc/latest/getting_started/installing.html till and including Step
- By the end of this you should have Cassandra working.
-- Download Apache Zookeeper 3.4.6, install into /opt/app/music and follow these instructions https://zookeeper.apache.org/doc/r3.4.6/zookeeperStarted.html pertaining to the standalone operation. By the end of this you should have Zookeeper working.
-- Download the Version 8.5 Apache Tomcat and install it using these instructions https://tomcat.apache.org/download-80.cgi (this is for version 8.5).
- Create a music.properties file and place it in /opt/app/music/etc/. Here is a sample of the file:
music.properties::
@@ -30,7 +28,6 @@ music.properties::
# Optional current values are defaults
######################################
# If using docker this would point to the specific docker name.
- #zookeeper.host=localhost
#cassandra.host=localhost
#music.ip=localhost
diff --git a/docs/swagger.json b/docs/swagger.json
index 27db769f..3bc67050 100644
--- a/docs/swagger.json
+++ b/docs/swagger.json
@@ -875,26 +875,43 @@
}
}
},
- "/v{version}/service/pingCassandra/{consistency}": {
+ "/v{version}/service/pingZookeeper": {
"get": {
"tags": [
"Healthcheck Api"
],
"summary": "Get Health Status",
"description": "",
- "operationId": "cassandraStatus",
+ "operationId": "ZKStatus",
"produces": [
"application/json"
],
- "parameters": [
- {
- "name": "consistency",
- "in": "path",
- "description": "Consistency level",
- "required": true,
- "type": "string"
+ "parameters": [],
+ "responses": {
+ "200": {
+ "description": "successful operation",
+ "schema": {
+ "type": "object",
+ "additionalProperties": {
+ "type": "object"
+ }
+ }
}
+ }
+ }
+ },
+ "/v{version}/service/musicHealthCheck": {
+ "get": {
+ "tags": [
+ "Healthcheck Api"
],
+ "summary": "Get Health Status",
+ "description": "",
+ "operationId": "musicHealthCheck",
+ "produces": [
+ "application/json"
+ ],
+ "parameters": [],
"responses": {
"200": {
"description": "successful operation",
@@ -908,18 +925,26 @@
}
}
},
- "/v{version}/service/pingZookeeper": {
+ "/v{version}/service/pingCassandra/{consistency}": {
"get": {
"tags": [
"Healthcheck Api"
],
"summary": "Get Health Status",
"description": "",
- "operationId": "ZKStatus",
+ "operationId": "cassandraStatus",
"produces": [
"application/json"
],
- "parameters": [],
+ "parameters": [
+ {
+ "name": "consistency",
+ "in": "path",
+ "description": "Consistency level",
+ "required": true,
+ "type": "string"
+ }
+ ],
"responses": {
"200": {
"description": "successful operation",
@@ -939,7 +964,7 @@
"Lock Api"
],
"summary": "Create Lock",
- "description": "Puts the requesting process in the q for this lock. The corresponding node will be created in zookeeper if it did not already exist. Lock Name is the \"key\" of the form keyspaceName.tableName.rowId",
+ "description": "Puts the requesting process in the q for this lock. The corresponding lock will be created if it did not already exist. Lock Name is the \"key\" of the form keyspaceName.tableName.rowId",
"operationId": "createLockReference",
"produces": [
"application/json"
@@ -1269,20 +1294,6 @@
"description": "Application namespace",
"required": true,
"type": "string"
- },
- {
- "name": "userId",
- "in": "header",
- "description": "userId",
- "required": true,
- "type": "string"
- },
- {
- "name": "password",
- "in": "header",
- "description": "Password",
- "required": true,
- "type": "string"
}
],
"responses": {
diff --git a/docs/tox.ini b/docs/tox.ini
new file mode 100644
index 00000000..edac8c35
--- /dev/null
+++ b/docs/tox.ini
@@ -0,0 +1,22 @@
+[tox]
+minversion = 1.6
+envlist = docs,
+skipsdist = true
+
+[testenv:docs]
+basepython = python3
+deps = -r{toxinidir}/requirements-docs.txt
+commands =
+ sphinx-build -b html -n -d {envtmpdir}/doctrees ./ {toxinidir}/_build/html
+ echo "Generated docs available in {toxinidir}/_build/html"
+whitelist_externals =
+ echo
+ git
+ sh
+
+[testenv:docs-linkcheck]
+basepython = python3
+#deps = -r{toxinidir}/requirements-docs.txt
+commands = echo "Link Checking not enforced"
+#commands = sphinx-build -b linkcheck -d {envtmpdir}/doctrees ./ {toxinidir}/_build/linkcheck
+whitelist_externals = echo
diff --git a/examples/VotingApp/README.md b/examples/VotingApp/README.md
index bcd37b9b..94dcc80a 100644
--- a/examples/VotingApp/README.md
+++ b/examples/VotingApp/README.md
@@ -1,3 +1,4 @@
+Compatible with MUSIC 2.5.3
The voting app for MUSIC illustrates the features of MUSIC as a
multi-site state management
diff --git a/examples/VotingApp/pom.xml b/examples/VotingApp/pom.xml
index 0c85e60b..cfe085e1 100644
--- a/examples/VotingApp/pom.xml
+++ b/examples/VotingApp/pom.xml
@@ -28,23 +28,23 @@ stated inside of the file.
<version>0.0.1-SNAPSHOT</version>
- <repositories>
- <repository>
- <id>maven2-repository.java.net</id>
- <name>Java.net Repository for Maven</name>
- <url>http://download.java.net/maven/2/</url>
- <layout>default</layout>
- </repository>
- </repositories>
+ <repositories>
+ <repository>
+ <id>maven2-repository.java.net</id>
+ <name>Java.net Repository for Maven</name>
+ <url>http://download.java.net/maven/2/</url>
+ <layout>default</layout>
+ </repository>
+ </repositories>
- <dependencies>
+ <dependencies>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-server</artifactId>
- <version>1.9</version>
- </dependency>
- <dependency>
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-server</artifactId>
+ <version>1.9</version>
+ </dependency>
+ <dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-json</artifactId>
<version>1.18.1</version>
@@ -54,46 +54,46 @@ stated inside of the file.
<artifactId>genson</artifactId>
<version>0.99</version>
</dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-client</artifactId>
- <version>1.9</version>
- </dependency>
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-client</artifactId>
+ <version>1.9</version>
+ </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-json</artifactId>
- <version>1.9</version>
- </dependency>
-
- <!-- <dependency>
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-json</artifactId>
+ <version>1.9</version>
+ </dependency>
+
+ <!-- <dependency>
<groupId>com.sun.jersey</groupId>
<artifactId>jersey-bundle</artifactId>
<version>1.18</version>
- </dependency> -->
+ </dependency> -->
- <dependency>
- <groupId>com.googlecode.json-simple</groupId>
- <artifactId>json-simple</artifactId>
- <version>1.1</version>
+ <dependency>
+ <groupId>com.googlecode.json-simple</groupId>
+ <artifactId>json-simple</artifactId>
+ <version>1.1</version>
</dependency>
- <dependency>
- <groupId>com.datastax.cassandra</groupId>
- <artifactId>cassandra-driver-core</artifactId>
- <version>3.0.0</version>
- </dependency>
- <dependency>
- <groupId>org.apache.zookeeper</groupId>
- <artifactId>zookeeper</artifactId>
- <version>3.4.6</version>
- </dependency>
+ <dependency>
+ <groupId>com.datastax.cassandra</groupId>
+ <artifactId>cassandra-driver-core</artifactId>
+ <version>3.0.0</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.zookeeper</groupId>
+ <artifactId>zookeeper</artifactId>
+ <version>3.4.6</version>
+ </dependency>
- <dependency>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-shade-plugin</artifactId>
- <version>3.1.1</version>
- </dependency>
- </dependencies>
+ <dependency>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-shade-plugin</artifactId>
+ <version>3.1.1</version>
+ </dependency>
+ </dependencies>
<build>
<plugins>
<plugin>
@@ -119,4 +119,3 @@ stated inside of the file.
</plugins>
</build>
</project>
-
diff --git a/examples/VotingApp/src/main/java/main/JsonDelete.java b/examples/VotingApp/src/main/java/main/JsonDelete.java
index 9b75f875..ef44e00a 100644
--- a/examples/VotingApp/src/main/java/main/JsonDelete.java
+++ b/examples/VotingApp/src/main/java/main/JsonDelete.java
@@ -20,42 +20,43 @@ stated inside of the file.
---------------------------------------------------------------------------
*/
+
package main;
import java.util.ArrayList;
import java.util.Map;
public class JsonDelete {
-
+
private ArrayList<String> columns = null;
private Map<String,String> consistencyInfo;
- public Map<String, String> getConsistencyInfo() {
- return consistencyInfo;
- }
+ public Map<String, String> getConsistencyInfo() {
+ return consistencyInfo;
+ }
- public void setConsistencyInfo(Map<String, String> consistencyInfo) {
- this.consistencyInfo = consistencyInfo;
- }
+ public void setConsistencyInfo(Map<String, String> consistencyInfo) {
+ this.consistencyInfo = consistencyInfo;
+ }
public ArrayList<String> getColumns() {
- return columns;
- }
- public void setColumns(ArrayList<String> columns) {
- this.columns = columns;
- }
- String ttl, timestamp;
-
- public String getTtl() {
- return ttl;
- }
- public void setTtl(String ttl) {
- this.ttl = ttl;
- }
- public String getTimestamp() {
- return timestamp;
- }
- public void setTimestamp(String timestamp) {
- this.timestamp = timestamp;
- }
+ return columns;
+ }
+ public void setColumns(ArrayList<String> columns) {
+ this.columns = columns;
+ }
+ String ttl, timestamp;
+
+ public String getTtl() {
+ return ttl;
+ }
+ public void setTtl(String ttl) {
+ this.ttl = ttl;
+ }
+ public String getTimestamp() {
+ return timestamp;
+ }
+ public void setTimestamp(String timestamp) {
+ this.timestamp = timestamp;
+ }
}
diff --git a/examples/VotingApp/src/main/java/main/JsonInsert.java b/examples/VotingApp/src/main/java/main/JsonInsert.java
index a2099c16..a19a564c 100644
--- a/examples/VotingApp/src/main/java/main/JsonInsert.java
+++ b/examples/VotingApp/src/main/java/main/JsonInsert.java
@@ -20,48 +20,49 @@ stated inside of the file.
---------------------------------------------------------------------------
*/
+
package main;
import java.util.Map;
import org.codehaus.jackson.annotate.JsonIgnoreProperties;
public class JsonInsert {
-
+
private Map<String,Object> values;
String ttl, timestamp;
- private Map<String,Object> row_specification;
+ private Map<String,Object> row_specification;
private Map<String,String> consistencyInfo;
- public Map<String, String> getConsistencyInfo() {
- return consistencyInfo;
- }
+ public Map<String, String> getConsistencyInfo() {
+ return consistencyInfo;
+ }
- public void setConsistencyInfo(Map<String, String> consistencyInfo) {
- this.consistencyInfo = consistencyInfo;
- }
+ public void setConsistencyInfo(Map<String, String> consistencyInfo) {
+ this.consistencyInfo = consistencyInfo;
+ }
- public String getTtl() {
- return ttl;
- }
- public void setTtl(String ttl) {
- this.ttl = ttl;
- }
- public String getTimestamp() {
- return timestamp;
- }
- public void setTimestamp(String timestamp) {
- this.timestamp = timestamp;
- }
- public Map<String, Object> getValues() {
- return values;
- }
- public void setValues(Map<String, Object> values) {
- this.values = values;
- }
+ public String getTtl() {
+ return ttl;
+ }
+ public void setTtl(String ttl) {
+ this.ttl = ttl;
+ }
+ public String getTimestamp() {
+ return timestamp;
+ }
+ public void setTimestamp(String timestamp) {
+ this.timestamp = timestamp;
+ }
+ public Map<String, Object> getValues() {
+ return values;
+ }
+ public void setValues(Map<String, Object> values) {
+ this.values = values;
+ }
public Map<String, Object> getRow_specification() {
- return row_specification;
- }
- public void setRow_specification(Map<String, Object> row_specification) {
- this.row_specification = row_specification;
- }
+ return row_specification;
+ }
+ public void setRow_specification(Map<String, Object> row_specification) {
+ this.row_specification = row_specification;
+ }
}
diff --git a/examples/VotingApp/src/main/java/main/JsonKeySpace.java b/examples/VotingApp/src/main/java/main/JsonKeySpace.java
index ff7b6c67..240d18a3 100644
--- a/examples/VotingApp/src/main/java/main/JsonKeySpace.java
+++ b/examples/VotingApp/src/main/java/main/JsonKeySpace.java
@@ -20,6 +20,7 @@ stated inside of the file.
---------------------------------------------------------------------------
*/
+
package main;
import java.util.Map;
@@ -27,32 +28,32 @@ import java.util.Map;
public class JsonKeySpace {
private Map<String,Object> replicationInfo;
- private String durabilityOfWrites;
+ private String durabilityOfWrites;
private Map<String,String> consistencyInfo;
- public Map<String, String> getConsistencyInfo() {
- return consistencyInfo;
- }
-
- public void setConsistencyInfo(Map<String, String> consistencyInfo) {
- this.consistencyInfo = consistencyInfo;
- }
-
- public Map<String, Object> getReplicationInfo() {
- return replicationInfo;
- }
-
- public void setReplicationInfo(Map<String, Object> replicationInfo) {
- this.replicationInfo = replicationInfo;
- }
-
- public String getDurabilityOfWrites() {
- return durabilityOfWrites;
- }
- public void setDurabilityOfWrites(String durabilityOfWrites) {
- this.durabilityOfWrites = durabilityOfWrites;
- }
-
-
+ public Map<String, String> getConsistencyInfo() {
+ return consistencyInfo;
+ }
+
+ public void setConsistencyInfo(Map<String, String> consistencyInfo) {
+ this.consistencyInfo = consistencyInfo;
+ }
+
+ public Map<String, Object> getReplicationInfo() {
+ return replicationInfo;
+ }
+
+ public void setReplicationInfo(Map<String, Object> replicationInfo) {
+ this.replicationInfo = replicationInfo;
+ }
+
+ public String getDurabilityOfWrites() {
+ return durabilityOfWrites;
+ }
+ public void setDurabilityOfWrites(String durabilityOfWrites) {
+ this.durabilityOfWrites = durabilityOfWrites;
+ }
+
+
}
diff --git a/examples/VotingApp/src/main/java/main/JsonTable.java b/examples/VotingApp/src/main/java/main/JsonTable.java
index 66171af2..f1124b07 100644
--- a/examples/VotingApp/src/main/java/main/JsonTable.java
+++ b/examples/VotingApp/src/main/java/main/JsonTable.java
@@ -20,36 +20,37 @@ stated inside of the file.
---------------------------------------------------------------------------
*/
+
package main;
import java.util.Map;
public class JsonTable {
private Map<String,String> fields;
- private Map<String, Object> properties;
+ private Map<String, Object> properties;
private Map<String,String> consistencyInfo;
- public Map<String, String> getConsistencyInfo() {
- return consistencyInfo;
- }
+ public Map<String, String> getConsistencyInfo() {
+ return consistencyInfo;
+ }
- public void setConsistencyInfo(Map<String, String> consistencyInfo) {
- this.consistencyInfo = consistencyInfo;
- }
+ public void setConsistencyInfo(Map<String, String> consistencyInfo) {
+ this.consistencyInfo = consistencyInfo;
+ }
public Map<String, Object> getProperties() {
- return properties;
- }
+ return properties;
+ }
- public void setProperties(Map<String, Object> properties) {
- this.properties = properties;
- }
+ public void setProperties(Map<String, Object> properties) {
+ this.properties = properties;
+ }
- public Map<String, String> getFields() {
- return fields;
- }
+ public Map<String, String> getFields() {
+ return fields;
+ }
- public void setFields(Map<String, String> fields) {
- this.fields = fields;
- }
+ public void setFields(Map<String, String> fields) {
+ this.fields = fields;
+ }
}
diff --git a/examples/VotingApp/src/main/java/main/MusicConnector.java b/examples/VotingApp/src/main/java/main/MusicConnector.java
index d6ed20ba..7772c9f2 100644
--- a/examples/VotingApp/src/main/java/main/MusicConnector.java
+++ b/examples/VotingApp/src/main/java/main/MusicConnector.java
@@ -20,57 +20,57 @@ stated inside of the file.
---------------------------------------------------------------------------
*/
+
package main;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
-import java.util.Random;
-
+import java.security.SecureRandom;
public class MusicConnector {
-
- //change this to point to relevant cluster
- public String[] musicNodes;
+
+ //change this to point to relevant cluster
+ public String[] musicNodes;
- public MusicConnector(String[] musicNodes){
- this.musicNodes = musicNodes;
- }
-
- private String getMusicNodeIp(){
- Random r = new Random();
- int index = r.nextInt(musicNodes.length);
- return musicNodes[index];
- }
-
- public String getMusicNodeURL(){
- String musicurl = "http://"+getMusicNodeIp()+":8080/MUSIC/rest/v2";
- return musicurl;
- }
-
- public boolean isHostUp(String serverAddress) {
- Boolean isUp = false;
- try {
- InetAddress inet = InetAddress.getByName(serverAddress);
- isUp = inet.isReachable(1000);
- } catch (UnknownHostException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- } catch (IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- return isUp;
- }
-
- /*
- private static String getMusicNodeIp(){
-
- //return "54.224.168.13";
- return bigSiteMusicNode;
- String serverAddress;
- serverAddress = agaveMusicNode;
- while(isHostUp(serverAddress) != true)
- serverAddress = toggle(serverAddress);
- return serverAddress;
- }*/
+ public MusicConnector(String[] musicNodes){
+ this.musicNodes = musicNodes;
+ }
+
+ private String getMusicNodeIp(){
+ SecureRandom r = new SecureRandom();
+ int index = r.nextInt(musicNodes.length);
+ return musicNodes[index];
+ }
+
+ public String getMusicNodeURL(){
+ String musicurl = "http://"+getMusicNodeIp()+":8080/MUSIC/rest/v2";
+ return musicurl;
+ }
+
+ public boolean isHostUp(String serverAddress) {
+ Boolean isUp = false;
+ try {
+ InetAddress inet = InetAddress.getByName(serverAddress);
+ isUp = inet.isReachable(1000);
+ } catch (UnknownHostException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ return isUp;
+ }
+
+ /*
+ private static String getMusicNodeIp(){
+
+ //return "54.224.168.13";
+ return bigSiteMusicNode;
+ String serverAddress;
+ serverAddress = agaveMusicNode;
+ while(isHostUp(serverAddress) != true)
+ serverAddress = toggle(serverAddress);
+ return serverAddress;
+ }*/
}
diff --git a/examples/VotingApp/src/main/java/main/Util.java b/examples/VotingApp/src/main/java/main/Util.java
index aefa9a36..0add7a70 100644
--- a/examples/VotingApp/src/main/java/main/Util.java
+++ b/examples/VotingApp/src/main/java/main/Util.java
@@ -1,6 +1,6 @@
package main;
public class Util {
- public static final String version="1.0.0";
+ public static final String version="1.0.0";
}
diff --git a/examples/VotingApp/src/main/java/main/VotingApp.java b/examples/VotingApp/src/main/java/main/VotingApp.java
index e58c324d..653cef2e 100644
--- a/examples/VotingApp/src/main/java/main/VotingApp.java
+++ b/examples/VotingApp/src/main/java/main/VotingApp.java
@@ -20,6 +20,7 @@ stated inside of the file.
---------------------------------------------------------------------------
*/
+
package main;
import java.io.BufferedReader;
import java.io.IOException;
@@ -28,6 +29,7 @@ import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
+import java.util.Base64;
import javax.ws.rs.core.MediaType;
@@ -40,474 +42,472 @@ import com.sun.jersey.api.client.config.DefaultClientConfig;
import com.sun.jersey.api.json.JSONConfiguration;
public class VotingApp {
- String keyspaceName;
- ArrayList<String> lockNames;
- MusicConnector musicHandle;
- private final String version="1.0.0";
-
- //UPDATE your onboarding information here
- String namespace = "votingapp";
- String userId = "abc123d";
- String password = "password";
-
- public VotingApp(String[] musicIps){
- lockNames = new ArrayList<String>();
- musicHandle = new MusicConnector(musicIps);
- bootStrap();
- }
-
- /**
- * Adds MUSIC's authentication headers into the webresource
- * @param webResource
- */
- private Builder addMusicHeaders(WebResource webResource) {
- Builder builder = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON);
- if (!namespace.equals("")) {
- builder.header("ns", namespace);
- }
- if (!userId.equals("")) {
- builder.header("userId", userId);
- }
- if (!password.equals("")) {
- builder.header("password", password);
- }
-
- return builder;
- }
-
- public void createVotingKeyspace(){
- keyspaceName = "VotingAppForMusic";
- System.out.println("Voting app version "+ version+" .....");
- Map<String,Object> replicationInfo = new HashMap<String, Object>();
- replicationInfo.put("class", "SimpleStrategy");
- replicationInfo.put("replication_factor", 1);
- String durabilityOfWrites="false";
- Map<String,String> consistencyInfo= new HashMap<String, String>();
- consistencyInfo.put("type", "eventual");
- JsonKeySpace jsonKp = new JsonKeySpace();
- jsonKp.setConsistencyInfo(consistencyInfo);
- jsonKp.setDurabilityOfWrites(durabilityOfWrites);
- jsonKp.setReplicationInfo(replicationInfo);
-
- ClientConfig clientConfig = new DefaultClientConfig();
-
- clientConfig.getFeatures().put(
- JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
-
- Client client = Client.create(clientConfig);
-
- WebResource webResource = client
- .resource(musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName);
-
- ClientResponse response = addMusicHeaders(webResource).accept("application/json")
- .type("application/json").post(ClientResponse.class, jsonKp);
- if (response.getStatus() < 200 || (response.getStatus() > 299 && response.getStatus()!=400)) { //supress keyspace already exists
- Map<String, String> map = response.getEntity(Map.class);
- throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus() + "- " + map);
- }
-
- }
-
- public void createVotingTable(){
- Map<String,String> fields = new HashMap<String,String>();
- fields.put("name", "text");
- fields.put("count", "varint");
- fields.put("PRIMARY KEY", "(name)");
-
-
- Map<String,String> consistencyInfo= new HashMap<String, String>();
- consistencyInfo.put("type", "eventual");
-
- JsonTable jtab = new JsonTable();
- jtab.setFields(fields);
- jtab.setConsistencyInfo(consistencyInfo);
-
- ClientConfig clientConfig = new DefaultClientConfig();
-
- clientConfig.getFeatures().put(
- JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
-
- Client client = Client.create(clientConfig);
- String url = musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/votecount";
- System.out.println("create url:"+url);
- WebResource webResource = client
- .resource(url);
-
- ClientResponse response = addMusicHeaders(webResource).accept("application/json")
- .type("application/json").post(ClientResponse.class, jtab);
-
- System.out.println(response.getEntity(Map.class));
- if (response.getStatus() < 200 || (response.getStatus() > 299 && response.getStatus()!=400))
- throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
-
- }
- private void checkMusicVersion(){
- Client client = Client.create();
- System.out.println(musicHandle.getMusicNodeURL()+"/version");
-
-
-// System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
- WebResource webResource = client
- .resource(musicHandle.getMusicNodeURL()+"/version");
-
-
- ClientResponse response = addMusicHeaders(webResource)
- .accept(MediaType.APPLICATION_JSON).header("Connection", "close").get(ClientResponse.class);
-
- if (response.getStatus() != 200) {
- throw new RuntimeException("Failed : HTTP error code : "
- + response.getStatus());
- }
-
- String output = response.getEntity(Map.class).toString();
-
- System.out.println(output);
-
- }
-
- private void createEntryForCandidate(String candidateName){
- Map<String,Object> values = new HashMap<String,Object>();
- values.put("name",candidateName );
- values.put("count",0);
-
- Map<String,String> consistencyInfo= new HashMap<String, String>();
- consistencyInfo.put("type", "eventual");
+ String keyspaceName;
+ ArrayList<String> lockNames;
+ MusicConnector musicHandle;
+ private final String version="1.0.0";
+
+ //UPDATE your onboarding information here
+ String namespace = "votingapp";
+ String userId = "abc123d";
+ String password = "password";
+
+ public VotingApp(String[] musicIps){
+ lockNames = new ArrayList<String>();
+ musicHandle = new MusicConnector(musicIps);
+ bootStrap();
+ }
+
+ /**
+ * Adds MUSIC's authentication headers into the webresource
+ * @param webResource
+ */
+ private Builder addMusicHeaders(WebResource webResource) {
+ Builder builder = webResource.accept(MediaType.APPLICATION_JSON).type(MediaType.APPLICATION_JSON);
+ if (!namespace.equals("")) {
+ builder.header("ns", namespace);
+ }
+ if (!userId.equals("") && !password.equals("")) {
+ String authString = Base64.getEncoder().encodeToString((userId + ":" + password).getBytes());
+ builder.header("Authorization", "Basic " + authString);
+ }
+
+ return builder;
+ }
+
+ public void createVotingKeyspace(){
+ keyspaceName = "VotingAppForMusic";
+ System.out.println("Voting app version "+ version+" .....");
+ Map<String,Object> replicationInfo = new HashMap<String, Object>();
+ replicationInfo.put("class", "SimpleStrategy");
+ replicationInfo.put("replication_factor", 1);
+ String durabilityOfWrites="false";
+ Map<String,String> consistencyInfo= new HashMap<String, String>();
+ consistencyInfo.put("type", "eventual");
+ JsonKeySpace jsonKp = new JsonKeySpace();
+ jsonKp.setConsistencyInfo(consistencyInfo);
+ jsonKp.setDurabilityOfWrites(durabilityOfWrites);
+ jsonKp.setReplicationInfo(replicationInfo);
+
+ ClientConfig clientConfig = new DefaultClientConfig();
+
+ clientConfig.getFeatures().put(
+ JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
+
+ Client client = Client.create(clientConfig);
+
+ WebResource webResource = client
+ .resource(musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName);
+
+ ClientResponse response = addMusicHeaders(webResource).accept("application/json")
+ .type("application/json").post(ClientResponse.class, jsonKp);
+ if (response.getStatus() < 200 || (response.getStatus() > 299 && response.getStatus()!=400)) { //supress keyspace already exists
+ Map<String, String> map = response.getEntity(Map.class);
+ throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus() + "- " + map);
+ }
+
+ }
+
+ public void createVotingTable(){
+ Map<String,String> fields = new HashMap<String,String>();
+ fields.put("name", "text");
+ fields.put("count", "varint");
+ fields.put("PRIMARY KEY", "(name)");
+
+
+ Map<String,String> consistencyInfo= new HashMap<String, String>();
+ consistencyInfo.put("type", "eventual");
+
+ JsonTable jtab = new JsonTable();
+ jtab.setFields(fields);
+ jtab.setConsistencyInfo(consistencyInfo);
+
+ ClientConfig clientConfig = new DefaultClientConfig();
+
+ clientConfig.getFeatures().put(
+ JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
+
+ Client client = Client.create(clientConfig);
+ String url = musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/votecount";
+ System.out.println("create url:"+url);
+ WebResource webResource = client
+ .resource(url);
+
+ ClientResponse response = addMusicHeaders(webResource).accept("application/json")
+ .type("application/json").post(ClientResponse.class, jtab);
+
+ System.out.println(response.getEntity(Map.class));
+ if (response.getStatus() < 200 || (response.getStatus() > 299 && response.getStatus()!=400))
+ throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
+
+ }
+ private void checkMusicVersion(){
+ Client client = Client.create();
+ System.out.println(musicHandle.getMusicNodeURL()+"/version");
+
+
+// System.setProperty("sun.net.http.allowRestrictedHeaders", "true");
+ WebResource webResource = client
+ .resource(musicHandle.getMusicNodeURL()+"/version");
+
+
+ ClientResponse response = addMusicHeaders(webResource)
+ .accept(MediaType.APPLICATION_JSON).header("Connection", "close").get(ClientResponse.class);
+
+ if (response.getStatus() != 200) {
+ throw new RuntimeException("Failed : HTTP error code : "
+ + response.getStatus());
+ }
+
+ String output = response.getEntity(Map.class).toString();
+
+ System.out.println(output);
+
+ }
+
+ private void createEntryForCandidate(String candidateName){
+ Map<String,Object> values = new HashMap<String,Object>();
+ values.put("name",candidateName );
+ values.put("count",0);
+
+ Map<String,String> consistencyInfo= new HashMap<String, String>();
+ consistencyInfo.put("type", "eventual");
- JsonInsert jIns = new JsonInsert();
- jIns.setValues(values);
- jIns.setConsistencyInfo(consistencyInfo);
- ClientConfig clientConfig = new DefaultClientConfig();
+ JsonInsert jIns = new JsonInsert();
+ jIns.setValues(values);
+ jIns.setConsistencyInfo(consistencyInfo);
+ ClientConfig clientConfig = new DefaultClientConfig();
- clientConfig.getFeatures().put(
- JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
+ clientConfig.getFeatures().put(
+ JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
- Client client = Client.create(clientConfig);
+ Client client = Client.create(clientConfig);
- String url = musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/votecount/rows";
- WebResource webResource = client
- .resource(url);
+ String url = musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/votecount/rows";
+ WebResource webResource = client
+ .resource(url);
- ClientResponse response = addMusicHeaders(webResource).accept("application/json")
- .type("application/json").post(ClientResponse.class, jIns);
+ ClientResponse response = addMusicHeaders(webResource).accept("application/json")
+ .type("application/json").post(ClientResponse.class, jIns);
- if (response.getStatus() < 200 || response.getStatus() > 299)
- throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus()+"url:"+url+" candidate name:"+ candidateName);
+ if (response.getStatus() < 200 || response.getStatus() > 299)
+ throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus()+"url:"+url+" candidate name:"+ candidateName);
- }
+ }
- private String createLock(String lockName){
- Client client = Client.create();
- String msg = musicHandle.getMusicNodeURL()+"/locks/create/"+lockName;
- WebResource webResource = client.resource(msg);
- System.out.println(msg);
- WebResource.Builder wb = addMusicHeaders(webResource).accept(MediaType.APPLICATION_JSON);
+ private String createLock(String lockName){
+ Client client = Client.create();
+ String msg = musicHandle.getMusicNodeURL()+"/locks/create/"+lockName;
+ WebResource webResource = client.resource(msg);
+ System.out.println(msg);
+ WebResource.Builder wb = addMusicHeaders(webResource).accept(MediaType.APPLICATION_JSON);
- ClientResponse response = wb.post(ClientResponse.class);
+ ClientResponse response = wb.post(ClientResponse.class);
- if (response.getStatus() != 200) {
- throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus()+"url:"+msg);
- }
+ if (response.getStatus() != 200) {
+ throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus()+"url:"+msg);
+ }
- Map<String,Object> responseMap = response.getEntity(Map.class);
+ Map<String,Object> responseMap = response.getEntity(Map.class);
- String lockid = ((Map<String,String>) responseMap.get("lock")).get("lock");
-// System.out.println("Server response .... \n");
-// System.out.println(output);
- return lockid;
- }
+ String lockid = ((Map<String,String>) responseMap.get("lock")).get("lock");
+// System.out.println("Server response .... \n");
+// System.out.println(output);
+ return lockid;
+ }
- private boolean acquireLock(String lockId){
- Client client = Client.create();
- String msg = musicHandle.getMusicNodeURL()+"/locks/acquire/"+lockId;
- System.out.println(msg);
- WebResource webResource = client.resource(msg);
+ private boolean acquireLock(String lockId){
+ Client client = Client.create();
+ String msg = musicHandle.getMusicNodeURL()+"/locks/acquire/"+lockId;
+ System.out.println(msg);
+ WebResource webResource = client.resource(msg);
- WebResource.Builder wb = addMusicHeaders(webResource).accept(MediaType.APPLICATION_JSON);
+ WebResource.Builder wb = addMusicHeaders(webResource).accept(MediaType.APPLICATION_JSON);
- ClientResponse response = wb.get(ClientResponse.class);
+ ClientResponse response = wb.get(ClientResponse.class);
- Map<String, Object> responseMap = response.getEntity(Map.class);
-
- if (response.getStatus() != 200) {
- throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus()+ ":" + responseMap);
- }
+ Map<String, Object> responseMap = response.getEntity(Map.class);
+
+ if (response.getStatus() != 200) {
+ throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus()+ ":" + responseMap);
+ }
- System.out.println(responseMap);
- Boolean status = responseMap.get("status").equals("SUCCESS");
- System.out.println("Server response .... " + status);
- return status;
- }
+ System.out.println(responseMap);
+ Boolean status = responseMap.get("status").equals("SUCCESS");
+ System.out.println("Server response .... " + status);
+ return status;
+ }
- private void unlock(String lockId){
- Client client = Client.create();
- WebResource webResource = client.resource(musicHandle.getMusicNodeURL()+"/locks/release/"+lockId);
+ private void unlock(String lockId){
+ Client client = Client.create();
+ WebResource webResource = client.resource(musicHandle.getMusicNodeURL()+"/locks/release/"+lockId);
- ClientResponse response = addMusicHeaders(webResource).delete(ClientResponse.class);
+ ClientResponse response = addMusicHeaders(webResource).delete(ClientResponse.class);
- if (response.getStatus() < 200 || response.getStatus()>299) {
- throw new RuntimeException("Failed : HTTP error code : "
- + response.getStatus());
- }
- }
+ if (response.getStatus() < 200 || response.getStatus()>299) {
+ throw new RuntimeException("Failed : HTTP error code : "
+ + response.getStatus());
+ }
+ }
- private void updateVoteCountAtomically(String candidateName,int count){
- /*create lock for the candidate. The music API dictates that
- * the lock name must be of the form keyspacename.tableName.primaryKeyName
- * */
- System.out.println("trying to acquire lock!");
+ private void updateVoteCountAtomically(String candidateName,int count){
+ /*create lock for the candidate. The music API dictates that
+ * the lock name must be of the form keyspacename.tableName.primaryKeyName
+ * */
+ System.out.println("trying to acquire lock!");
- String lockName = keyspaceName+".votecount."+candidateName;
- lockNames.add(lockName);
- String lockId = createLock(lockName);
- while(acquireLock(lockId) != true);
-
- System.out.println("acquired lock!");
- //update candidate entry if you have the lock
- Map<String,Object> values = new HashMap<String,Object>();
- values.put("count",count);
+ String lockName = keyspaceName+".votecount."+candidateName;
+ lockNames.add(lockName);
+ String lockId = createLock(lockName);
+ while(acquireLock(lockId) != true);
+
+ System.out.println("acquired lock!");
+ //update candidate entry if you have the lock
+ Map<String,Object> values = new HashMap<String,Object>();
+ values.put("count",count);
- Map<String,String> consistencyInfo= new HashMap<String, String>();
- consistencyInfo.put("type", "critical");
- consistencyInfo.put("lockId", lockId);
+ Map<String,String> consistencyInfo= new HashMap<String, String>();
+ consistencyInfo.put("type", "critical");
+ consistencyInfo.put("lockId", lockId);
- JsonInsert jIns = new JsonInsert();
- jIns.setValues(values);
- jIns.setConsistencyInfo(consistencyInfo);
- ClientConfig clientConfig = new DefaultClientConfig();
+ JsonInsert jIns = new JsonInsert();
+ jIns.setValues(values);
+ jIns.setConsistencyInfo(consistencyInfo);
+ ClientConfig clientConfig = new DefaultClientConfig();
- clientConfig.getFeatures().put(
- JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
+ clientConfig.getFeatures().put(
+ JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
- Client client = Client.create(clientConfig);
- String url = musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/votecount/rows?name="+candidateName;
- System.out.println(url);
- WebResource webResource = client
- .resource(url);
+ Client client = Client.create(clientConfig);
+ String url = musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/votecount/rows?name="+candidateName;
+ System.out.println(url);
+ WebResource webResource = client
+ .resource(url);
- ClientResponse response = addMusicHeaders(webResource).accept("application/json")
- .type("application/json").put(ClientResponse.class, jIns);
+ ClientResponse response = addMusicHeaders(webResource).accept("application/json")
+ .type("application/json").put(ClientResponse.class, jIns);
- Map<String,String> map = response.getEntity(Map.class);
-
- if (response.getStatus() < 200 || response.getStatus() > 299)
- throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus()+":"+map);
-
- //release lock now that the operation is done
- unlock(lockId);
-
- }
-
- private void deleteCandidateEntryEventually(String candidateName){
- Map<String,String> consistencyInfo= new HashMap<String, String>();
- consistencyInfo.put("type", "eventual");
+ Map<String,String> map = response.getEntity(Map.class);
+
+ if (response.getStatus() < 200 || response.getStatus() > 299)
+ throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus()+":"+map);
+
+ //release lock now that the operation is done
+ unlock(lockId);
+
+ }
+
+ private void deleteCandidateEntryEventually(String candidateName){
+ Map<String,String> consistencyInfo= new HashMap<String, String>();
+ consistencyInfo.put("type", "eventual");
- JsonDelete jDel = new JsonDelete();
- jDel.setConsistencyInfo(consistencyInfo);
- ClientConfig clientConfig = new DefaultClientConfig();
+ JsonDelete jDel = new JsonDelete();
+ jDel.setConsistencyInfo(consistencyInfo);
+ ClientConfig clientConfig = new DefaultClientConfig();
- clientConfig.getFeatures().put(
- JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
-
- Client client = Client.create(clientConfig);
- String url = musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/votecount/rows?name="+candidateName;
- System.out.println(url);
- WebResource webResource = client
- .resource(url);
+ clientConfig.getFeatures().put(
+ JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
+
+ Client client = Client.create(clientConfig);
+ String url = musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/votecount/rows?name="+candidateName;
+ System.out.println(url);
+ WebResource webResource = client
+ .resource(url);
- ClientResponse response = addMusicHeaders(webResource).accept("application/json")
- .type("application/json").delete(ClientResponse.class, jDel);
+ ClientResponse response = addMusicHeaders(webResource).accept("application/json")
+ .type("application/json").delete(ClientResponse.class, jDel);
- if (response.getStatus() < 200 || response.getStatus() > 299)
- throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus()+"url:"+url);
+ if (response.getStatus() < 200 || response.getStatus() > 299)
+ throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus()+"url:"+url);
- }
-
- public Map<String,Object> readVoteCountForCandidate(String candidateName){
- ClientConfig clientConfig = new DefaultClientConfig();
-
- clientConfig.getFeatures().put(
- JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
-
- Client client = Client.create(clientConfig);
- String url = musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/votecount/rows?name="+candidateName;
- WebResource webResource = client
- .resource(url);
-
- ClientResponse response = addMusicHeaders(webResource).accept("application/json").get(ClientResponse.class);
-
- if (response.getStatus() < 200 || response.getStatus() > 299)
- throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
-
- Map<String,Object> output = response.getEntity(Map.class);
- return output;
- }
+ }
+
+ public Map<String,Object> readVoteCountForCandidate(String candidateName){
+ ClientConfig clientConfig = new DefaultClientConfig();
+
+ clientConfig.getFeatures().put(
+ JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
+
+ Client client = Client.create(clientConfig);
+ String url = musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/votecount/rows?name="+candidateName;
+ WebResource webResource = client
+ .resource(url);
+
+ ClientResponse response = addMusicHeaders(webResource).accept("application/json").get(ClientResponse.class);
+
+ if (response.getStatus() < 200 || response.getStatus() > 299)
+ throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
+
+ Map<String,Object> output = response.getEntity(Map.class);
+ return output;
+ }
- public Map<String,Object> readAllVotes(){
- ClientConfig clientConfig = new DefaultClientConfig();
-
- clientConfig.getFeatures().put(
- JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
-
- Client client = Client.create(clientConfig);
- String url = musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/votecount/rows";
- WebResource webResource = client
- .resource(url);
-
- ClientResponse response = addMusicHeaders(webResource).accept("application/json").get(ClientResponse.class);
+ public Map<String,Object> readAllVotes(){
+ ClientConfig clientConfig = new DefaultClientConfig();
+
+ clientConfig.getFeatures().put(
+ JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
+
+ Client client = Client.create(clientConfig);
+ String url = musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName+"/tables/votecount/rows";
+ WebResource webResource = client
+ .resource(url);
+
+ ClientResponse response = addMusicHeaders(webResource).accept("application/json").get(ClientResponse.class);
- if (response.getStatus() < 200 || response.getStatus() > 299)
- throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
-
- Map<String,Object> output = response.getEntity(Map.class);
- return output;
- }
-
-
- /*
- * Unable to use this because of the error:
- * Exception in thread "main" com.sun.jersey.api.client.ClientHandlerException: java.net.ProtocolException:
- * HTTP method DELETE doesn't support output. Seems to be a error in the rest java combination according to the interwebs
- */
- private void dropKeySpace(){
- Map<String,String> consistencyInfo= new HashMap<String, String>();
- consistencyInfo.put("type", "eventual");
+ if (response.getStatus() < 200 || response.getStatus() > 299)
+ throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
+
+ Map<String,Object> output = response.getEntity(Map.class);
+ return output;
+ }
+
+
+ /*
+ * Unable to use this because of the error:
+ * Exception in thread "main" com.sun.jersey.api.client.ClientHandlerException: java.net.ProtocolException:
+ * HTTP method DELETE doesn't support output. Seems to be a error in the rest java combination according to the interwebs
+ */
+ private void dropKeySpace(){
+ Map<String,String> consistencyInfo= new HashMap<String, String>();
+ consistencyInfo.put("type", "eventual");
- JsonKeySpace jsonKp = new JsonKeySpace();
- jsonKp.setConsistencyInfo(consistencyInfo);
+ JsonKeySpace jsonKp = new JsonKeySpace();
+ jsonKp.setConsistencyInfo(consistencyInfo);
- ClientConfig clientConfig = new DefaultClientConfig();
+ ClientConfig clientConfig = new DefaultClientConfig();
- clientConfig.getFeatures().put(
- JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
-
- Client client = Client.create(clientConfig);
-
- WebResource webResource = client
- .resource(musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName);
-
- ClientResponse response = addMusicHeaders(webResource).type("application/json")
- .delete(ClientResponse.class, jsonKp);
-
- if (response.getStatus() < 200 || response.getStatus() > 299)
- throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
- }
-
- private void deleteLock(String lockName){
- Client client = Client.create();
- WebResource webResource = client.resource(musicHandle.getMusicNodeURL()+"/locks/delete/"+lockName);
-
- ClientResponse response = addMusicHeaders(webResource).delete(ClientResponse.class);
-
-
- if (response.getStatus() <200 || response.getStatus()>299) {
- throw new RuntimeException("Failed : HTTP error code : "
- + response.getStatus());
- }
- }
-
- private void resetMusic(){
- Client client = Client.create();
- WebResource webResource = client.resource(musicHandle.getMusicNodeURL()+"/reset");
-
- ClientResponse response = addMusicHeaders(webResource).delete(ClientResponse.class);
-
-
- if (response.getStatus() != 204) {
- throw new RuntimeException("Failed : HTTP error code : "
- + response.getStatus());
- }
-
- }
- public void deleteAllLocks(){
- for (String lockName : lockNames) {
- deleteLock(lockName);
- }
- }
-
-
- public void bootStrap(){
- checkMusicVersion();
- createVotingKeyspace();
-
-
- createVotingTable();
-
-
- //the next few lines just create an entry in the voting table for all these candidates with vote count as 0
- createEntryForCandidate("Popeye");
-
- createEntryForCandidate("Judy");
-
- createEntryForCandidate("Flash");
-
- createEntryForCandidate("Mickey");
-
- }
-
- public void overAllTests(){
- //update the count atomically
- updateVoteCountAtomically("Popeye",5);
-
- updateVoteCountAtomically("Judy",7);
-
- updateVoteCountAtomically("Mickey",8);
-
- updateVoteCountAtomically("Flash",2);
-
-
- //read votecount
- System.out.println(readAllVotes());
-
- System.out.println(readVoteCountForCandidate("Popeye"));
-
- System.out.println(readVoteCountForCandidate("Flash"));
-
- deleteCandidateEntryEventually("Mickey");
-
- System.out.println(readAllVotes());
-
-// dropKeySpace();
-
- deleteAllLocks();
- }
-
- public void flipTest(){
- checkMusicVersion();
- }
-
- public static String executeBashScript(String pathToScript, String arg1, String arg2){
- try {
- ProcessBuilder pb = new ProcessBuilder(pathToScript,arg1, arg2);
- final Process process = pb.start();
- InputStream is = process.getInputStream();
- InputStreamReader isr = new InputStreamReader(is);
- BufferedReader br = new BufferedReader(isr);
- return br.readLine();
- } catch (IOException e) {
- e.printStackTrace();
- }
- return null;
- }
-
- public static void main(String[] args) {
- long start = System.currentTimeMillis();
-
- if (args.length==0) {
- args = new String[]{"localhost"};
- }
- for(int i =0; i < 2;++i){
- VotingApp vHandle = new VotingApp(args);
- vHandle.overAllTests();
-
- System.out.println("=====================================");
- System.out.println("Test no."+i+" completed:");
- }
- long diff = System.currentTimeMillis() - start;
- System.out.println(diff);
- }
-
-
-} \ No newline at end of file
+ clientConfig.getFeatures().put(
+ JSONConfiguration.FEATURE_POJO_MAPPING, Boolean.TRUE);
+
+ Client client = Client.create(clientConfig);
+
+ WebResource webResource = client
+ .resource(musicHandle.getMusicNodeURL()+"/keyspaces/"+keyspaceName);
+
+ ClientResponse response = addMusicHeaders(webResource).type("application/json")
+ .delete(ClientResponse.class, jsonKp);
+
+ if (response.getStatus() < 200 || response.getStatus() > 299)
+ throw new RuntimeException("Failed : HTTP error code : "+ response.getStatus());
+ }
+
+ private void deleteLock(String lockName){
+ Client client = Client.create();
+ WebResource webResource = client.resource(musicHandle.getMusicNodeURL()+"/locks/delete/"+lockName);
+
+ ClientResponse response = addMusicHeaders(webResource).delete(ClientResponse.class);
+
+
+ if (response.getStatus() <200 || response.getStatus()>299) {
+ throw new RuntimeException("Failed : HTTP error code : "
+ + response.getStatus());
+ }
+ }
+
+ private void resetMusic(){
+ Client client = Client.create();
+ WebResource webResource = client.resource(musicHandle.getMusicNodeURL()+"/reset");
+
+ ClientResponse response = addMusicHeaders(webResource).delete(ClientResponse.class);
+
+
+ if (response.getStatus() != 204) {
+ throw new RuntimeException("Failed : HTTP error code : "
+ + response.getStatus());
+ }
+
+ }
+ public void deleteAllLocks(){
+ for (String lockName : lockNames) {
+ deleteLock(lockName);
+ }
+ }
+
+
+ public void bootStrap(){
+ checkMusicVersion();
+ createVotingKeyspace();
+
+
+ createVotingTable();
+
+
+ //the next few lines just create an entry in the voting table for all these candidates with vote count as 0
+ createEntryForCandidate("Popeye");
+
+ createEntryForCandidate("Judy");
+
+ createEntryForCandidate("Flash");
+
+ createEntryForCandidate("Mickey");
+
+ }
+
+ public void overAllTests(){
+ //update the count atomically
+ updateVoteCountAtomically("Popeye",5);
+
+ updateVoteCountAtomically("Judy",7);
+
+ updateVoteCountAtomically("Mickey",8);
+
+ updateVoteCountAtomically("Flash",2);
+
+
+ //read votecount
+ System.out.println(readAllVotes());
+
+ System.out.println(readVoteCountForCandidate("Popeye"));
+
+ System.out.println(readVoteCountForCandidate("Flash"));
+
+ deleteCandidateEntryEventually("Mickey");
+
+ System.out.println(readAllVotes());
+
+// dropKeySpace();
+
+ deleteAllLocks();
+ }
+
+ public void flipTest(){
+ checkMusicVersion();
+ }
+
+ public static String executeBashScript(String pathToScript, String arg1, String arg2){
+ try {
+ ProcessBuilder pb = new ProcessBuilder(pathToScript,arg1, arg2);
+ final Process process = pb.start();
+ InputStream is = process.getInputStream();
+ InputStreamReader isr = new InputStreamReader(is);
+ BufferedReader br = new BufferedReader(isr);
+ return br.readLine();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ return null;
+ }
+
+ public static void main(String[] args) {
+ long start = System.currentTimeMillis();
+
+ if (args.length==0) {
+ args = new String[]{"localhost"};
+ }
+ for(int i =0; i < 2;++i){
+ VotingApp vHandle = new VotingApp(args);
+ vHandle.overAllTests();
+
+ System.out.println("=====================================");
+ System.out.println("Test no."+i+" completed:");
+ }
+ long diff = System.currentTimeMillis() - start;
+ System.out.println(diff);
+ }
+
+
+}
diff --git a/jar/pom.xml b/jar/pom.xml
index b068aee6..af4bdb6d 100644..100755
--- a/jar/pom.xml
+++ b/jar/pom.xml
@@ -1,5 +1,4 @@
-<?xml version="1.0"?>
-<!--
+<!--
============LICENSE_START==========================================
org.onap.music
===================================================================
@@ -20,12 +19,13 @@
============LICENSE_END=============================================
====================================================================
-->
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
+ xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.onap.music</groupId>
<artifactId>MUSIC</artifactId>
<packaging>jar</packaging>
- <version>2.5.6</version>
+ <version>2.5.10-SNAPSHOT</version>
<description>
This is the MUSIC REST interface, packaged as a war file.
</description>
@@ -33,8 +33,8 @@
<parent>
<groupId>org.onap.oparent</groupId>
<artifactId>oparent</artifactId>
- <version>1.2.0</version>
- <relativePath/>
+ <version>2.0.0</version>
+ <relativePath />
</parent>
<properties>
@@ -44,6 +44,7 @@
<jaxrs.version>2.0.1</jaxrs.version>
<cassandra.version>3.4.0</cassandra.version>
<zookeeper.version>3.4.11</zookeeper.version>
+ <onap.nexus.url>https://nexus.onap.org</onap.nexus.url>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
@@ -115,8 +116,8 @@
<source>1.7</source>
<target>1.7</target>
<excludes>
- <exclude>jar/**</exclude>
- </excludes>
+ <exclude>jar/**</exclude>
+ </excludes>
</configuration>
</plugin>
<plugin>
@@ -185,7 +186,6 @@
<scope>provided</scope>
</dependency>
<!-- /Development -->
-
<!-- Logging -->
<dependency>
<groupId>ch.qos.logback</groupId>
@@ -216,13 +216,13 @@
</dependency>
<!-- End Logging -->
- <!-- Cassandra -->
+ <!-- Cassandra -->
<dependency>
<groupId>com.datastax.cassandra</groupId>
<artifactId>cassandra-driver-core</artifactId>
<version>${cassandra.version}</version>
</dependency>
- <!-- /Cassandra -->
+ <!-- /Cassandra -->
<!-- Zookeeper -->
<dependency>
@@ -254,10 +254,10 @@
<artifactId>jersey-json</artifactId>
<version>${jersey1.version}</version>
</dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-servlet</artifactId>
- <version>${jersey1.version}</version>
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-servlet</artifactId>
+ <version>${jersey1.version}</version>
</dependency>
<!-- /Jersey -->
@@ -311,7 +311,32 @@
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-handler</artifactId>
- <version>4.0.56.Final</version>
+ <version>4.1.33.Final</version>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-buffer</artifactId>
+ <version>4.1.33.Final</version>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-codec</artifactId>
+ <version>4.1.33.Final</version>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-common</artifactId>
+ <version>4.1.33.Final</version>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-resolver</artifactId>
+ <version>4.1.33.Final</version>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-transport</artifactId>
+ <version>4.1.33.Final</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
@@ -331,13 +356,31 @@
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
-
+ <version>19.0</version>
</dependency>
<dependency>
+ <groupId>de.svenkubiak</groupId>
+ <artifactId>jBCrypt</artifactId>
+ <version>0.4.1</version>
+ </dependency>
+ <!-- <dependency>
<groupId>org.mindrot</groupId>
<artifactId>jbcrypt</artifactId>
<version>0.4</version>
+ </dependency>-->
+ <!-- https://mvnrepository.com/artifact/commons-codec/commons-codec -->
+ <dependency>
+ <groupId>commons-codec</groupId>
+ <artifactId>commons-codec</artifactId>
+ <version>1.9</version>
</dependency>
+ <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-lang3 -->
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <version>3.0</version>
+ </dependency>
+
</dependencies>
<reporting>
@@ -404,14 +447,14 @@
</build>
</image>
<!-- Zookeeper -->
- <!-- <image> <name>onap/music/zookeeper_music</name>
- <alias>docker_zookeeper</alias> <build> <cleanup>true</cleanup> <tags> <tag>3.4-${timestamp}</tag>
- <tag>3.4-latest</tag> </tags> <dockerFileDir>${project.basedir}/distribution/zookeeper</dockerFileDir>
+ <!-- <image> <name>onap/music/zookeeper_music</name>
+ <alias>docker_zookeeper</alias> <build> <cleanup>true</cleanup> <tags> <tag>3.4-${timestamp}</tag>
+ <tag>3.4-latest</tag> </tags> <dockerFileDir>${project.basedir}/distribution/zookeeper</dockerFileDir>
</build> </image> -->
<!-- tomcat 8.5 -->
- <!-- <image> <name>onap/music/tomcat_music</name>
- <alias>docker_tomcat</alias> <build> <cleanup>true</cleanup> <tags> <tag>8.5-${timestamp}</tag>
- <tag>8.5-latest</tag> </tags> <dockerFileDir>${project.basedir}/distribution/tomcat</dockerFileDir>
+ <!-- <image> <name>onap/music/tomcat_music</name>
+ <alias>docker_tomcat</alias> <build> <cleanup>true</cleanup> <tags> <tag>8.5-${timestamp}</tag>
+ <tag>8.5-latest</tag> </tags> <dockerFileDir>${project.basedir}/distribution/tomcat</dockerFileDir>
</build> </image>\ -->
</images>
</configuration>
diff --git a/jar/src/main/java/org/onap/music/datastore/MusicDataStore.java b/jar/src/main/java/org/onap/music/datastore/MusicDataStore.java
index 71006f73..3cd8baeb 100644
--- a/jar/src/main/java/org/onap/music/datastore/MusicDataStore.java
+++ b/jar/src/main/java/org/onap/music/datastore/MusicDataStore.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.datastore;
import java.net.InetAddress;
@@ -54,6 +55,7 @@ import com.datastax.driver.core.exceptions.NoHostAvailableException;
import com.datastax.driver.core.policies.RoundRobinPolicy;
import com.datastax.driver.core.HostDistance;
import com.datastax.driver.core.PoolingOptions;
+import org.onap.music.main.MusicUtil;
/**
@@ -141,7 +143,7 @@ public class MusicDataStore {
} catch (SocketException e) {
logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.CONNCECTIVITYERROR, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
}catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
}
return allPossibleIps;
}
@@ -155,8 +157,8 @@ public class MusicDataStore {
String address = "localhost";
String[] addresses = null;
address = MusicUtil.getMyCassaHost();
- addresses = address.split(",");
-
+ addresses = address.split(",");
+
logger.info(EELFLoggerDelegate.applicationLogger,
"Connecting to cassa cluster: Iterating through possible ips:"
+ getAllPossibleLocalIps());
@@ -166,19 +168,18 @@ public class MusicDataStore {
.setConnectionsPerHost(HostDistance.REMOTE, 2, 4);
while (it.hasNext()) {
try {
- if(MusicUtil.getCassName() != null && MusicUtil.getCassPwd() != null) {
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Building with credentials "+MusicUtil.getCassName()+" & "+MusicUtil.getCassPwd());
- cluster = Cluster.builder().withPort(9042)
- .withCredentials(MusicUtil.getCassName(), MusicUtil.getCassPwd())
- //.withLoadBalancingPolicy(new RoundRobinPolicy())
- .withPoolingOptions(poolingOptions)
- .addContactPoints(addresses).build();
- }
- else
- cluster = Cluster.builder().withPort(9042)
- //.withLoadBalancingPolicy(new RoundRobinPolicy())
- .addContactPoints(addresses).build();
+ if(MusicUtil.getCassName() != null && MusicUtil.getCassPwd() != null) {
+ cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort())
+ .withCredentials(MusicUtil.getCassName(), MusicUtil.getCassPwd())
+ //.withLoadBalancingPolicy(new RoundRobinPolicy())
+ .withoutJMXReporting()
+ .withPoolingOptions(poolingOptions)
+ .addContactPoints(addresses).build();
+ }
+ else
+ cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort())
+ //.withLoadBalancingPolicy(new RoundRobinPolicy())
+ .addContactPoints(addresses).build();
Metadata metadata = cluster.getMetadata();
logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster "
@@ -206,26 +207,24 @@ public class MusicDataStore {
* @param address
*/
private void connectToCassaCluster(String address) throws MusicServiceException {
- String[] addresses = null;
- addresses = address.split(",");
- PoolingOptions poolingOptions = new PoolingOptions();
+ String[] addresses = null;
+ addresses = address.split(",");
+ PoolingOptions poolingOptions = new PoolingOptions();
poolingOptions
- .setConnectionsPerHost(HostDistance.LOCAL, 4, 10)
- .setConnectionsPerHost(HostDistance.REMOTE, 2, 4);
+ .setConnectionsPerHost(HostDistance.LOCAL, 4, 10)
+ .setConnectionsPerHost(HostDistance.REMOTE, 2, 4);
if(MusicUtil.getCassName() != null && MusicUtil.getCassPwd() != null) {
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Building with credentials "+MusicUtil.getCassName()+" & "+MusicUtil.getCassPwd());
- cluster = Cluster.builder().withPort(9042)
- .withCredentials(MusicUtil.getCassName(), MusicUtil.getCassPwd())
- //.withLoadBalancingPolicy(new RoundRobinPolicy())
- .withPoolingOptions(poolingOptions)
- .addContactPoints(addresses).build();
- }
- else {
- cluster = Cluster.builder().withPort(9042)
- //.withLoadBalancingPolicy(new RoundRobinPolicy())
- .withPoolingOptions(poolingOptions)
- .addContactPoints(addresses).build();
+ cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort())
+ .withCredentials(MusicUtil.getCassName(), MusicUtil.getCassPwd())
+ .withoutJMXReporting()
+ .withPoolingOptions(poolingOptions)
+ .addContactPoints(addresses).build();
+ } else {
+ cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort())
+ //.withLoadBalancingPolicy(new RoundRobinPolicy())
+ .withoutJMXReporting()
+ .withPoolingOptions(poolingOptions)
+ .addContactPoints(addresses).build();
}
Metadata metadata = cluster.getMetadata();
logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster "
@@ -233,7 +232,9 @@ public class MusicDataStore {
try {
session = cluster.connect();
} catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.CASSANDRACONNECTIVITY, ErrorSeverity.ERROR, ErrorTypes.SERVICEUNAVAILABLE);
+ logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),
+ AppMessages.CASSANDRACONNECTIVITY,
+ ErrorSeverity.ERROR, ErrorTypes.SERVICEUNAVAILABLE);
throw new MusicServiceException(
"Error while connecting to Cassandra cluster.. " + ex.getMessage());
}
@@ -355,7 +356,7 @@ public class MusicDataStore {
boolean result = false;
if (!MusicUtil.isValidQueryObject(!queryObject.getValues().isEmpty(), queryObject)) {
- logger.error(EELFLoggerDelegate.errorLogger, queryObject.getQuery(),AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, queryObject.getQuery(),AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
throw new MusicQueryException("Ill formed queryObject for the request = " + "["
+ queryObject.getQuery() + "]");
}
@@ -365,15 +366,15 @@ public class MusicDataStore {
+ queryObject.getValues());
PreparedStatement preparedInsert = null;
try {
-
- preparedInsert = session.prepare(queryObject.getQuery());
-
+
+ preparedInsert = session.prepare(queryObject.getQuery());
+
} catch(InvalidQueryException iqe) {
- logger.error(EELFLoggerDelegate.errorLogger, iqe.getMessage(),AppMessages.QUERYERROR, ErrorSeverity.CRITICAL, ErrorTypes.QUERYERROR);
- throw new MusicQueryException(iqe.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger, iqe.getMessage(),AppMessages.QUERYERROR, ErrorSeverity.CRITICAL, ErrorTypes.QUERYERROR);
+ throw new MusicQueryException(iqe.getMessage());
}catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.QUERYERROR, ErrorSeverity.CRITICAL, ErrorTypes.QUERYERROR);
- throw new MusicQueryException(e.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.QUERYERROR, ErrorSeverity.CRITICAL, ErrorTypes.QUERYERROR);
+ throw new MusicQueryException(e.getMessage());
}
try {
@@ -391,11 +392,11 @@ public class MusicDataStore {
}
catch (AlreadyExistsException ae) {
logger.error(EELFLoggerDelegate.errorLogger, ae.getMessage(),AppMessages.SESSIONFAILED+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicServiceException(ae.getMessage());
+ throw new MusicServiceException(ae.getMessage());
}
catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.SESSIONFAILED+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicQueryException("Executing Session Failure for Request = " + "["
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.SESSIONFAILED+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
+ throw new MusicQueryException("Executing Session Failure for Request = " + "["
+ queryObject.getQuery() + "]" + " Reason = " + e.getMessage());
}
@@ -415,8 +416,8 @@ public class MusicDataStore {
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("Ill formed queryObject for the request = " + "["
+ 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,
@@ -424,13 +425,13 @@ public class MusicDataStore {
ResultSet results = null;
try {
- PreparedStatement preparedEventualGet = session.prepare(queryObject.getQuery());
+ PreparedStatement preparedEventualGet = session.prepare(queryObject.getQuery());
preparedEventualGet.setConsistencyLevel(ConsistencyLevel.ONE);
results = session.execute(preparedEventualGet.bind(queryObject.getValues().toArray()));
} catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicServiceException(ex.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
+ throw new MusicServiceException(ex.getMessage());
}
return results;
}
@@ -447,7 +448,7 @@ public class MusicDataStore {
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);
+ 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() + "]");
}
@@ -459,8 +460,8 @@ public class MusicDataStore {
try {
results = session.execute(preparedEventualGet.bind(queryObject.getValues().toArray()));
} catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicServiceException(ex.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
+ throw new MusicServiceException(ex.getMessage());
}
return results;
diff --git a/jar/src/main/java/org/onap/music/datastore/PreparedQueryObject.java b/jar/src/main/java/org/onap/music/datastore/PreparedQueryObject.java
index 694d9acd..28920cbb 100644
--- a/jar/src/main/java/org/onap/music/datastore/PreparedQueryObject.java
+++ b/jar/src/main/java/org/onap/music/datastore/PreparedQueryObject.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.datastore;
import java.util.ArrayList;
diff --git a/jar/src/main/java/org/onap/music/datastore/jsonobjects/AAFResponse.java b/jar/src/main/java/org/onap/music/datastore/jsonobjects/AAFResponse.java
index df6089ee..6be6796c 100644
--- a/jar/src/main/java/org/onap/music/datastore/jsonobjects/AAFResponse.java
+++ b/jar/src/main/java/org/onap/music/datastore/jsonobjects/AAFResponse.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.datastore.jsonobjects;
import java.util.ArrayList;
diff --git a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java
index 8de0a2cd..2fc4215b 100644
--- a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java
+++ b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java
@@ -24,14 +24,14 @@ package org.onap.music.datastore.jsonobjects;
public class JSONObject {
- private String data;
+ private String data;
- public String getData() {
- return data;
- }
-
- public void setData(String data) {
- this.data = data;
- }
-
+ public String getData() {
+ return data;
+ }
+
+ public void setData(String data) {
+ this.data = data;
+ }
+
}
diff --git a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java
index a5db4be5..c90dd005 100644
--- a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java
+++ b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.datastore.jsonobjects;
import java.util.ArrayList;
diff --git a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java
index a58552c6..8e1d7ee8 100644
--- a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java
+++ b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.datastore.jsonobjects;
import java.io.ByteArrayOutputStream;
diff --git a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java
index 54de02fd..f2232ffd 100644
--- a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java
+++ b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.datastore.jsonobjects;
import java.util.Map;
diff --git a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java
index 497e17d1..06a76f57 100644
--- a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java
+++ b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.datastore.jsonobjects;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
diff --git a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java
index 0bac1e31..f7c3f8a7 100755
--- a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java
+++ b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.datastore.jsonobjects;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
diff --git a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java
index 64bc3887..831a9c61 100644
--- a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java
+++ b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.datastore.jsonobjects;
import java.io.ByteArrayOutputStream;
diff --git a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java
index 5d508adb..368e4fac 100644
--- a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java
+++ b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.datastore.jsonobjects;
import java.util.Map;
diff --git a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java
index 3ab5ea0d..47e1a12b 100644
--- a/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java
+++ b/jar/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.datastore.jsonobjects;
import java.io.ByteArrayOutputStream;
diff --git a/jar/src/main/java/org/onap/music/datastore/jsonobjects/NameSpace.java b/jar/src/main/java/org/onap/music/datastore/jsonobjects/NameSpace.java
index 232353c1..3c18c791 100644
--- a/jar/src/main/java/org/onap/music/datastore/jsonobjects/NameSpace.java
+++ b/jar/src/main/java/org/onap/music/datastore/jsonobjects/NameSpace.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.datastore.jsonobjects;
import java.util.List;
diff --git a/jar/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java b/jar/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java
index 1f4abea1..fdd706b2 100644
--- a/jar/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java
+++ b/jar/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.eelf.healthcheck;
import java.io.BufferedReader;
@@ -57,119 +58,119 @@ import com.datastax.driver.core.ResultSet;
*
*/
public class MusicHealthCheck {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
-
- private String cassandrHost;
- private String zookeeperHost;
-
-
-
-
-
-
-
-
- public String getCassandraStatus() {
- logger.info(EELFLoggerDelegate.applicationLogger,"Getting Status for Cassandra");
- if(this.getAdminKeySpace()) {
- return "ACTIVE";
+
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
+
+ private String cassandrHost;
+ private String zookeeperHost;
+
+
+
+
+
+
+
+
+ public String getCassandraStatus() {
+ logger.info(EELFLoggerDelegate.applicationLogger,"Getting Status for Cassandra");
+ if(this.getAdminKeySpace()) {
+ return "ACTIVE";
}else {
- logger.info(EELFLoggerDelegate.applicationLogger,"Cassandra Service is not responding");
+ logger.info(EELFLoggerDelegate.applicationLogger,"Cassandra Service is not responding");
return "INACTIVE";
}
}
-
-
- private Boolean getAdminKeySpace() {
-
- String appName = "";
-
- PreparedQueryObject pQuery = new PreparedQueryObject();
+
+
+ private Boolean getAdminKeySpace() {
+
+ String appName = "";
+
+ PreparedQueryObject pQuery = new PreparedQueryObject();
pQuery.appendQueryString(
"select * from admin.keyspace_master");
//pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
try {
- ResultSet rs = MusicCore.get(pQuery);
-
- if(rs != null) {
- return Boolean.TRUE;
- }else {
- return Boolean.FALSE;
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(),AppMessages.CASSANDRACONNECTIVITY, ErrorTypes.CONNECTIONERROR, ErrorSeverity.CRITICAL);
- }
+ ResultSet rs = MusicCore.get(pQuery);
+
+ if(rs != null) {
+ return Boolean.TRUE;
+ }else {
+ return Boolean.FALSE;
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(),AppMessages.CASSANDRACONNECTIVITY, ErrorTypes.CONNECTIONERROR, ErrorSeverity.CRITICAL);
+ }
return Boolean.FALSE;
- }
-
- public String getZookeeperStatus() {
-
-
- String host = MusicUtil.getMyZkHost();
- logger.info(EELFLoggerDelegate.applicationLogger,"Getting Status for Zookeeper Host: "+host);
- try {
- MusicLockingService lockingService = MusicCore.getLockingServiceHandle();
- //additionally need to call the ZK to create,aquire and delete lock
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(),AppMessages.LOCKINGERROR, ErrorTypes.CONNECTIONERROR, ErrorSeverity.CRITICAL);
- return "INACTIVE";
- }
-
- logger.info(EELFLoggerDelegate.applicationLogger,"Zookeeper is Active and Running");
+ }
+
+ public String getZookeeperStatus() {
+
+
+ String host = MusicUtil.getMyZkHost();
+ logger.info(EELFLoggerDelegate.applicationLogger,"Getting Status for Zookeeper Host: "+host);
+ try {
+ MusicLockingService lockingService = MusicCore.getLockingServiceHandle();
+ //additionally need to call the ZK to create,aquire and delete lock
+ } catch (MusicLockingException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(),AppMessages.LOCKINGERROR, ErrorTypes.CONNECTIONERROR, ErrorSeverity.CRITICAL);
+ return "INACTIVE";
+ }
+
+ logger.info(EELFLoggerDelegate.applicationLogger,"Zookeeper is Active and Running");
return "ACTIVE";
- //return "Zookeeper is not responding";
+ //return "Zookeeper is not responding";
- }
+ }
- public String getCassandrHost() {
- return cassandrHost;
- }
+ public String getCassandrHost() {
+ return cassandrHost;
+ }
- public void setCassandrHost(String cassandrHost) {
- this.cassandrHost = cassandrHost;
- }
+ public void setCassandrHost(String cassandrHost) {
+ this.cassandrHost = cassandrHost;
+ }
- public String getZookeeperHost() {
- return zookeeperHost;
- }
+ public String getZookeeperHost() {
+ return zookeeperHost;
+ }
- public void setZookeeperHost(String zookeeperHost) {
- this.zookeeperHost = zookeeperHost;
- }
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
+ public void setZookeeperHost(String zookeeperHost) {
+ this.zookeeperHost = zookeeperHost;
+ }
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
+
}
diff --git a/jar/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java b/jar/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java
index 0c290b6f..0d1eb641 100644
--- a/jar/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java
+++ b/jar/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.eelf.logging;
import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
diff --git a/jar/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java b/jar/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java
index 2c7952b2..545740dd 100644
--- a/jar/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java
+++ b/jar/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java
@@ -27,157 +27,157 @@ package org.onap.music.eelf.logging.format;
*
*/
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 - 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 ZK 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
- *
- */
-
-
-
-
- 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"),
- KEEPERERROR("[ERR502E]"," Zookeeper error has occured","","Please check zookeeper details"),
- 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");
-
-
-
- ErrorTypes eType;
- ErrorSeverity alarmSeverity;
- ErrorSeverity errorSeverity;
- String errorCode;
- String errorDescription;
- String details;
- String resolution;
+
+
+
+ /*
+ * 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 - 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 ZK 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
+ *
+ */
+
+
+
+
+ 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"),
+ KEEPERERROR("[ERR502E]"," Zookeeper error has occured","","Please check zookeeper details"),
+ 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");
+
+
+
+ ErrorTypes eType;
+ ErrorSeverity alarmSeverity;
+ ErrorSeverity errorSeverity;
+ String errorCode;
+ String errorDescription;
+ String details;
+ String resolution;
- AppMessages(String errorCode, String errorDescription, String details,String resolution) {
-
- this.errorCode = errorCode;
- this.errorDescription = errorDescription;
- this.details = details;
- this.resolution = resolution;
- }
+ AppMessages(String errorCode, String errorDescription, String details,String resolution) {
+
+ this.errorCode = errorCode;
+ this.errorDescription = errorDescription;
+ this.details = details;
+ this.resolution = resolution;
+ }
-
-
-
- AppMessages(ErrorTypes eType, ErrorSeverity alarmSeverity,
- ErrorSeverity errorSeverity, String errorCode, String errorDescription, String details,
- String resolution) {
-
- this.eType = eType;
- this.alarmSeverity = alarmSeverity;
- this.errorSeverity = errorSeverity;
- this.errorCode = errorCode;
- this.errorDescription = errorDescription;
- this.details = details;
- this.resolution = resolution;
- }
+
+
+
+ AppMessages(ErrorTypes eType, ErrorSeverity alarmSeverity,
+ ErrorSeverity errorSeverity, String errorCode, String errorDescription, String details,
+ String resolution) {
+
+ this.eType = eType;
+ this.alarmSeverity = alarmSeverity;
+ this.errorSeverity = errorSeverity;
+ this.errorCode = errorCode;
+ this.errorDescription = errorDescription;
+ this.details = details;
+ this.resolution = resolution;
+ }
- public String getDetails() {
- return this.details;
- }
+ public String getDetails() {
+ return this.details;
+ }
- public String getResolution() {
- return this.resolution;
- }
+ public String getResolution() {
+ return this.resolution;
+ }
- public String getErrorCode() {
- return this.errorCode;
- }
+ public String getErrorCode() {
+ return this.errorCode;
+ }
- public String getErrorDescription() {
- return this.errorDescription;
- }
+ public String getErrorDescription() {
+ return this.errorDescription;
+ }
-
+
-
-
-
+
+
+
}
diff --git a/jar/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java b/jar/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java
index b18c1771..0afd9eea 100644
--- a/jar/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java
+++ b/jar/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.eelf.logging.format;
@@ -28,67 +29,67 @@ package org.onap.music.eelf.logging.format;
*
*/
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 ZK 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");
+
+
+ /*
+ * 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 ZK 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;
@@ -100,7 +101,7 @@ public enum ErrorCodes {
return result;
}
*/
-
-
+
+
}
diff --git a/jar/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java b/jar/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java
index cda5dd31..4e798239 100644
--- a/jar/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java
+++ b/jar/src/main/java/org/onap/music/eelf/logging/format/ErrorSeverity.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.eelf.logging.format;
/**
diff --git a/jar/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java b/jar/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java
index 2536f4a4..d263eef5 100644
--- a/jar/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java
+++ b/jar/src/main/java/org/onap/music/eelf/logging/format/ErrorTypes.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.eelf.logging.format;
import com.att.eelf.i18n.EELFResolvableErrorEnum;
@@ -28,17 +29,17 @@ import com.att.eelf.i18n.EELFResolvableErrorEnum;
*
*/
public enum ErrorTypes implements EELFResolvableErrorEnum {
-
-
- CONNECTIONERROR,
- SESSIONEXPIRED,
- AUTHENTICATIONERROR,
- SERVICEUNAVAILABLE,
- QUERYERROR,
- DATAERROR,
- GENERALSERVICEERROR,
- MUSICSERVICEERROR,
- LOCKINGERROR,
- UNKNOWN,
-
+
+
+ CONNECTIONERROR,
+ SESSIONEXPIRED,
+ AUTHENTICATIONERROR,
+ SERVICEUNAVAILABLE,
+ QUERYERROR,
+ DATAERROR,
+ GENERALSERVICEERROR,
+ MUSICSERVICEERROR,
+ LOCKINGERROR,
+ UNKNOWN,
+
}
diff --git a/jar/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java b/jar/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java
index 14a23d1f..83bb1b8a 100644
--- a/jar/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java
+++ b/jar/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.exceptions;
import java.io.EOFException;
diff --git a/jar/src/main/java/org/onap/music/exceptions/MusicLockingException.java b/jar/src/main/java/org/onap/music/exceptions/MusicLockingException.java
index 1a9e45d9..ab70c54c 100644
--- a/jar/src/main/java/org/onap/music/exceptions/MusicLockingException.java
+++ b/jar/src/main/java/org/onap/music/exceptions/MusicLockingException.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.exceptions;
/**
diff --git a/jar/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java b/jar/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java
index bade21a4..dbd5ae5c 100644
--- a/jar/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java
+++ b/jar/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.exceptions;
/**
diff --git a/jar/src/main/java/org/onap/music/exceptions/MusicQueryException.java b/jar/src/main/java/org/onap/music/exceptions/MusicQueryException.java
index 24b8568b..803f993f 100644
--- a/jar/src/main/java/org/onap/music/exceptions/MusicQueryException.java
+++ b/jar/src/main/java/org/onap/music/exceptions/MusicQueryException.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.exceptions;
diff --git a/jar/src/main/java/org/onap/music/lockingservice/LockListener.java b/jar/src/main/java/org/onap/music/lockingservice/LockListener.java
index 33188e60..1089a3af 100644
--- a/jar/src/main/java/org/onap/music/lockingservice/LockListener.java
+++ b/jar/src/main/java/org/onap/music/lockingservice/LockListener.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.lockingservice;
/**
diff --git a/jar/src/main/java/org/onap/music/lockingservice/MusicLockState.java b/jar/src/main/java/org/onap/music/lockingservice/MusicLockState.java
index 6c31410f..b33c8326 100644
--- a/jar/src/main/java/org/onap/music/lockingservice/MusicLockState.java
+++ b/jar/src/main/java/org/onap/music/lockingservice/MusicLockState.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.lockingservice;
import java.io.ByteArrayInputStream;
@@ -107,8 +108,8 @@ public class MusicLockState implements Serializable {
}
public String getErrorMessage() {
- return errorMessage;
- }
+ return errorMessage;
+ }
public byte[] serialize() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
@@ -117,7 +118,7 @@ public class MusicLockState implements Serializable {
out = new ObjectOutputStream(bos);
out.writeObject(this);
} catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
}
return bos.toByteArray();
}
@@ -130,7 +131,7 @@ public class MusicLockState implements Serializable {
in = new ObjectInputStream(bis);
o = in.readObject();
} catch (ClassNotFoundException | IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.UNKNOWN);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.UNKNOWN);
}
return (MusicLockState) o;
}
diff --git a/jar/src/main/java/org/onap/music/lockingservice/MusicLockingService.java b/jar/src/main/java/org/onap/music/lockingservice/MusicLockingService.java
index 4070238a..aab50dc5 100644
--- a/jar/src/main/java/org/onap/music/lockingservice/MusicLockingService.java
+++ b/jar/src/main/java/org/onap/music/lockingservice/MusicLockingService.java
@@ -15,6 +15,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.lockingservice;
@@ -55,24 +56,24 @@ public class MusicLockingService implements Watcher {
logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
throw new MusicServiceException("IO Error has occured" + e.getMessage());
} catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
throw new MusicServiceException("Exception Occured " + e.getMessage());
}
}
public MusicLockingService(int timeout) throws MusicServiceException {
- CountDownLatch connectedSignal1 = new CountDownLatch(1);
- try {
+ CountDownLatch connectedSignal1 = new CountDownLatch(1);
+ try {
ZooKeeper zk1 = new ZooKeeper(MusicUtil.getMyZkHost(), SESSION_TIMEOUT, this);
connectedSignal1.await(timeout, TimeUnit.SECONDS);
if(!zk1.getState().isConnected()) {
- throw new MusicServiceException("Unable to Connect. Some nodes are down.");
+ throw new MusicServiceException("Unable to Connect. Some nodes are down.");
}
} catch (IOException e ) {
logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
throw new MusicServiceException("IO Error has occured" + e.getMessage());
} catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
throw new MusicServiceException("Exception Occured " + e.getMessage());
}
}
@@ -87,12 +88,12 @@ public class MusicLockingService implements Watcher {
connectedSignal.await();
zkLockHandle = new ZkStatelessLockService(zk);
} catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
}catch( InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ }catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ }
}
public void createLockaIfItDoesNotExist(String lockName) {
@@ -111,17 +112,17 @@ public class MusicLockingService implements Watcher {
public MusicLockState getLockState(String lockName) throws MusicLockingException {
- byte[] data = null;
+ byte[] data = null;
try{
- data = zkLockHandle.getNodeData(lockName);
+ data = zkLockHandle.getNodeData(lockName);
}catch (Exception ex){
- logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
}
if(data !=null)
return MusicLockState.deSerialize(data);
else {
- logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.INVALIDLOCK, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- throw new MusicLockingException("Invalid lock or acquire failed");
+ logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.INVALIDLOCK, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ throw new MusicLockingException("Invalid lock or acquire failed");
}
}
@@ -137,12 +138,12 @@ public class MusicLockingService implements Watcher {
try {
return zkLockHandle.lock(lockName, lockId);
} catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.LOCKINGERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.LOCKINGERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
}catch( InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ }catch(Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ }
return false;
}
@@ -152,11 +153,11 @@ public class MusicLockingService implements Watcher {
}
public void deleteLock(String lockName) throws MusicLockingException {
- if(lockIdExists(lockName))
- zkLockHandle.deleteLock(lockName);
- else{
- throw new MusicLockingException("Lock does not exist.Please check the lock: " + lockName + " and try again");
- }
+ if(lockIdExists(lockName))
+ zkLockHandle.deleteLock(lockName);
+ else{
+ throw new MusicLockingException("Lock does not exist.Please check the lock: " + lockName + " and try again");
+ }
}
public String whoseTurnIsIt(String lockName) {
@@ -176,9 +177,9 @@ public class MusicLockingService implements Watcher {
zkLockHandle.close();
}
- public boolean lockIdExists(String lockIdWithDollar) {
- String lockId = lockIdWithDollar.replace('$', '/');
- return zkLockHandle.checkIfLockExists(lockId);
- }
+ public boolean lockIdExists(String lockIdWithDollar) {
+ String lockId = lockIdWithDollar.replace('$', '/');
+ return zkLockHandle.checkIfLockExists(lockId);
+ }
}
diff --git a/jar/src/main/java/org/onap/music/lockingservice/ProtocolSupport.java b/jar/src/main/java/org/onap/music/lockingservice/ProtocolSupport.java
index 4082b3b8..b8be0c46 100644
--- a/jar/src/main/java/org/onap/music/lockingservice/ProtocolSupport.java
+++ b/jar/src/main/java/org/onap/music/lockingservice/ProtocolSupport.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.lockingservice;
import org.apache.zookeeper.CreateMode;
@@ -128,7 +129,7 @@ class ProtocolSupport {
try {
return operation.execute();
} catch (KeeperException.SessionExpiredException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.SESSIONEXPIRED+" for: " + zookeeper + " so reconnecting due to: " + e, ErrorSeverity.ERROR, ErrorTypes.SESSIONEXPIRED);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.SESSIONEXPIRED+" for: " + zookeeper + " so reconnecting due to: " + e, ErrorSeverity.ERROR, ErrorTypes.SESSIONEXPIRED);
throw e;
} catch (KeeperException.ConnectionLossException e) {
if (exception == null) {
@@ -174,9 +175,9 @@ class ProtocolSupport {
}
});
} catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
} catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
}
}
@@ -199,8 +200,8 @@ class ProtocolSupport {
try {
Thread.sleep(attemptCount * retryDelay);
} catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Thread failed to sleep: " + e);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Thread failed to sleep: " + e);
Thread.currentThread().interrupt();
}
}
diff --git a/jar/src/main/java/org/onap/music/lockingservice/ZNodeName.java b/jar/src/main/java/org/onap/music/lockingservice/ZNodeName.java
index 0c190f14..308e133f 100644
--- a/jar/src/main/java/org/onap/music/lockingservice/ZNodeName.java
+++ b/jar/src/main/java/org/onap/music/lockingservice/ZNodeName.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.lockingservice;
import org.onap.music.eelf.logging.EELFLoggerDelegate;
@@ -50,9 +51,9 @@ class ZNodeName implements Comparable<ZNodeName> {
// If an exception occurred we misdetected a sequence suffix,
// so return -1.
} catch (NumberFormatException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Number format exception "+idx, ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Number format exception "+idx, ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
} catch (ArrayIndexOutOfBoundsException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Array out of bounds for "+idx, ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Array out of bounds for "+idx, ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
}
}
}
diff --git a/jar/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java b/jar/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java
index e99df255..1c56238c 100644
--- a/jar/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java
+++ b/jar/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java
@@ -15,6 +15,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.lockingservice;
@@ -61,9 +62,9 @@ public class ZkStatelessLockService extends ProtocolSupport {
}
});
}catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
}catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
}
}
@@ -71,7 +72,7 @@ public class ZkStatelessLockService extends ProtocolSupport {
try {
zookeeper.close();
}catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
}
}
@@ -85,9 +86,9 @@ public class ZkStatelessLockService extends ProtocolSupport {
}
});
}catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
}catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
}
}
@@ -100,9 +101,9 @@ public class ZkStatelessLockService extends ProtocolSupport {
return null;
}catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
}catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
}
return null;
}
@@ -115,9 +116,9 @@ public class ZkStatelessLockService extends ProtocolSupport {
result = true;
}
}catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
}catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
}
return result;
}
@@ -132,9 +133,9 @@ public class ZkStatelessLockService extends ProtocolSupport {
try {
retryOperation(zop);
}catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
}catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
}
return zop.getId();
}
@@ -172,14 +173,14 @@ public class ZkStatelessLockService extends ProtocolSupport {
};
zopdel.execute();
} catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
// set that we have been interrupted.
Thread.currentThread().interrupt();
} catch (KeeperException.NoNodeException e) {
// do nothing
- throw new KeeperException.NoNodeException("Lock doesn't exists. Release lock operation failed.");
+ throw new KeeperException.NoNodeException("Lock doesn't exists. Release lock operation failed.");
} catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
throw (RuntimeException) new RuntimeException(e.getMessage()).initCause(e);
}
}
@@ -199,13 +200,13 @@ public class ZkStatelessLockService extends ProtocolSupport {
}
return sortedNames.first().getName();
} catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
// set that we have been interrupted.
Thread.currentThread().interrupt();
} catch (KeeperException.NoNodeException e) {
// do nothing
} catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
throw (RuntimeException) new RuntimeException(e.getMessage()).initCause(e);
}
}
@@ -228,14 +229,14 @@ public class ZkStatelessLockService extends ProtocolSupport {
};
zopdel.execute();
} catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
// set that we have been interrupted.
Thread.currentThread().interrupt();
} catch (KeeperException.NoNodeException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
// do nothing
} catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
throw (RuntimeException) new RuntimeException(e.getMessage()).initCause(e);
}
}
@@ -286,7 +287,7 @@ public class ZkStatelessLockService extends ProtocolSupport {
CreateMode.PERSISTENT_SEQUENTIAL);
if (logger.isDebugEnabled()) {
- logger.debug(EELFLoggerDelegate.debugLogger, "Created id: " + id);
+ logger.debug(EELFLoggerDelegate.debugLogger, "Created id: " + id);
}
if (id != null)
break;
@@ -316,7 +317,7 @@ public class ZkStatelessLockService extends ProtocolSupport {
ZNodeName lastChildName = lessThanMe.last();
String lastChildId = lastChildName.getName();
if (logger.isDebugEnabled()) {
- logger.debug(EELFLoggerDelegate.debugLogger, "watching less than me node: " + lastChildId);
+ logger.debug(EELFLoggerDelegate.debugLogger, "watching less than me node: " + lastChildId);
}
Stat stat = zookeeper.exists(lastChildId, false);
if (stat != null) {
diff --git a/jar/src/main/java/org/onap/music/lockingservice/ZooKeeperOperation.java b/jar/src/main/java/org/onap/music/lockingservice/ZooKeeperOperation.java
index 7020d14d..d5ee5615 100644
--- a/jar/src/main/java/org/onap/music/lockingservice/ZooKeeperOperation.java
+++ b/jar/src/main/java/org/onap/music/lockingservice/ZooKeeperOperation.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.lockingservice;
import org.apache.zookeeper.KeeperException;
diff --git a/jar/src/main/java/org/onap/music/main/CachingUtil.java b/jar/src/main/java/org/onap/music/main/CachingUtil.java
index aa06aae2..4b293bbb 100755
--- a/jar/src/main/java/org/onap/music/main/CachingUtil.java
+++ b/jar/src/main/java/org/onap/music/main/CachingUtil.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.main;
import java.util.Arrays;
@@ -122,12 +123,12 @@ public class CachingUtil implements Runnable {
@Override
public void run() {
- logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
+ logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
try {
- initializeAafCache();
- } catch (MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
- }
+ initializeAafCache();
+ } catch (MusicServiceException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
+ }
}
public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
@@ -135,9 +136,9 @@ public class CachingUtil implements Runnable {
if (aafCache.get(nameSpace) != null) {
if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
+ logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
} else if (aafCache.get(nameSpace).get(userId).equals(password)) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
+ logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
// reset invalid attempts to 0
userAttempts.put(nameSpace, 0);
return true;
@@ -155,7 +156,7 @@ public class CachingUtil implements Runnable {
logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
userAttempts.put(nameSpace, 0);
} else {
- logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
+ logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
}
}
@@ -167,10 +168,10 @@ public class CachingUtil implements Runnable {
AAFResponse responseObj = triggerAAF(nameSpace, userId, password);
if (responseObj.getNs().size() > 0) {
if (responseObj.getNs().get(0).getAdmin().contains(userId)) {
- //Map<String, String> map = new HashMap<>();
+ //Map<String, String> map = new HashMap<>();
//map.put(userId, password);
//aafCache.put(nameSpace, map);
- return true;
+ return true;
}
}
logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
@@ -180,7 +181,7 @@ public class CachingUtil implements Runnable {
private static AAFResponse triggerAAF(String nameSpace, String userId, String password)
throws Exception {
if (MusicUtil.getAafEndpointUrl() == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
}
Client client = Client.create();
@@ -255,8 +256,8 @@ public class CachingUtil implements Runnable {
if(isAAF != null)
appNameCache.put(namespace, isAAF);
} catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- e.printStackTrace();
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
+ e.printStackTrace();
}
}
return isAAF;
@@ -290,7 +291,7 @@ public class CachingUtil implements Runnable {
try {
appName = rs.getString("application_name");
} catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
e.printStackTrace();
}
return appName;
@@ -317,8 +318,8 @@ public class CachingUtil implements Runnable {
public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
Map<String, Object> resultMap = new HashMap<>();
if (ns == null || userId == null || password == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
+ logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing.");
resultMap.put("Exception",
"One or more required headers appName(ns), userId, password is missing. Please check.");
return resultMap;
@@ -327,20 +328,20 @@ public class CachingUtil implements Runnable {
queryObject.appendQueryString(
"select * from admin.keyspace_master where application_name = ? allow filtering");
try {
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
+ queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
} catch(Exception e) {
- resultMap.put("Exception",
+ resultMap.put("Exception",
"Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
- return resultMap;
+ return resultMap;
}
Row rs = null;
- try {
- rs = MusicCore.get(queryObject).one();
- } catch (MusicServiceException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
- return resultMap;
+ try {
+ rs = MusicCore.get(queryObject).one();
+ } catch (MusicServiceException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
+ return resultMap;
} catch (InvalidQueryException e) {
logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
@@ -350,7 +351,7 @@ public class CachingUtil implements Runnable {
logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
} else {
- if(!(rs.getString("username").equals(userId)) || !(BCrypt.checkpw(password, rs.getString("password")))) {
+ if(!(rs.getString("username").equals(userId)) || !(BCrypt.checkpw(password, rs.getString("password")))) {
logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
diff --git a/jar/src/main/java/org/onap/music/main/CipherUtil.java b/jar/src/main/java/org/onap/music/main/CipherUtil.java
new file mode 100644
index 00000000..8b1149c9
--- /dev/null
+++ b/jar/src/main/java/org/onap/music/main/CipherUtil.java
@@ -0,0 +1,270 @@
+/*
+ * ============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.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.UnsupportedEncodingException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.util.Scanner;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang3.ArrayUtils;
+import org.onap.music.eelf.logging.EELFLoggerDelegate;
+
+public class CipherUtil {
+
+
+ /**
+ * Default key.
+ */
+ private static String keyString = null;
+
+ private static final String ALGORITHM = "AES";
+ private static final String ALGORYTHM_DETAILS = ALGORITHM + "/CBC/PKCS5PADDING";
+ private static final int BLOCK_SIZE = 128;
+ @SuppressWarnings("unused")
+ private static SecretKeySpec secretKeySpec;
+ private static IvParameterSpec ivspec;
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CipherUtil.class);
+ /**
+ * @deprecated Please use {@link #encryptPKC(String)} to encrypt the text.
+ *
+ * Encrypts the text using the specified secret key.
+ *
+ * @param plainText
+ * Text to encrypt
+ * @param secretKey
+ * Key to use for encryption
+ * @return encrypted version of plain text.
+ * @
+ * if any encryption step fails
+ *
+ */
+ @Deprecated
+ public static String encrypt(String plainText, String secretKey) {
+ String encryptedString = null;
+ try {
+ byte[] encryptText = plainText.getBytes("UTF-8");
+ byte[] rawKey = Base64.decodeBase64(secretKey);
+ SecretKeySpec sKeySpec = new SecretKeySpec(rawKey, "AES");
+ Cipher cipher = Cipher.getInstance("AES");
+ cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
+ encryptedString = Base64.encodeBase64String(cipher.doFinal(encryptText));
+ } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException
+ | NoSuchPaddingException | UnsupportedEncodingException ex) {
+ }
+ return encryptedString;
+ }
+
+ /**
+ * @deprecated Please use {@link #encryptPKC(String)} to encrypt the text.
+ * Encrypts the text using the secret key in key.properties file.
+ *
+ * @param plainText
+ * Text to encrypt
+ * @return Encrypted Text
+ * @
+ * if any decryption step fails
+ */
+ @Deprecated
+ public static String encrypt(String plainText) {
+ return CipherUtil.encrypt(plainText, keyString);
+ }
+
+ /**
+ * Encrypts the text using a secret key.
+ *
+ * @param plainText
+ * Text to encrypt
+ * @return Encrypted Text
+ * @
+ * if any decryption step fails
+ */
+ public static String encryptPKC(String plainText) {
+ return CipherUtil.encryptPKC(plainText, keyString);
+ }
+
+ /**
+ *
+ * @deprecated Please use {@link #decryptPKC(String)} to Decryption the text.
+ *
+ * Decrypts the text using the specified secret key.
+ *
+ * @param encryptedText
+ * Text to decrypt
+ * @param secretKey
+ * Key to use for decryption
+ * @return plain text version of encrypted text
+ * @
+ * if any decryption step fails
+ *
+ */
+ @Deprecated
+ public static String decrypt(String encryptedText, String secretKey) {
+ String encryptedString = null;
+ try {
+ byte[] rawKey = Base64.decodeBase64(secretKey);
+ SecretKeySpec sKeySpec = new SecretKeySpec(rawKey, "AES");
+ byte[] encryptText = Base64.decodeBase64(encryptedText.getBytes("UTF-8"));
+ Cipher cipher = Cipher.getInstance("AES");
+ cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
+ encryptedString = new String(cipher.doFinal(encryptText));
+ } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException
+ | NoSuchPaddingException | UnsupportedEncodingException ex) {
+ }
+ return encryptedString;
+ }
+
+ private static SecretKeySpec getSecretKeySpec() {
+ byte[] key = Base64.decodeBase64(keyString);
+ return new SecretKeySpec(key, ALGORITHM);
+ }
+
+ private static SecretKeySpec getSecretKeySpec(String keyString) {
+ byte[] key = Base64.decodeBase64(keyString);
+ return new SecretKeySpec(key, ALGORITHM);
+ }
+
+ /**
+ * Encrypt the text using the secret key in key.properties file
+ *
+ * @param value
+ * @return The encrypted string
+ * @throws BadPaddingException
+ * @
+ * In case of issue with the encryption
+ */
+ public static String encryptPKC(String value, String skey) {
+ Cipher cipher = null;
+ byte[] iv = null, finalByte = null;
+
+ try {
+ cipher = Cipher.getInstance(ALGORYTHM_DETAILS, "SunJCE");
+
+ SecureRandom r = SecureRandom.getInstance("SHA1PRNG");
+ iv = new byte[BLOCK_SIZE / 8];
+ r.nextBytes(iv);
+ ivspec = new IvParameterSpec(iv);
+ cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(skey), ivspec);
+ finalByte = cipher.doFinal(value.getBytes());
+
+ } catch (Exception ex) {
+
+ }
+ return Base64.encodeBase64String(ArrayUtils.addAll(iv, finalByte));
+ }
+
+ /**
+ * Decrypts the text using the secret key in key.properties file.
+ *
+ * @param message
+ * The encrypted string that must be decrypted using the ecomp
+ * Encryption Key
+ * @return The String decrypted
+ * @
+ * if any decryption step fails
+ */
+ public static String decryptPKC(String message, String skey) {
+ byte[] encryptedMessage = Base64.decodeBase64(message);
+ Cipher cipher;
+ byte[] decrypted = null;
+ try {
+ cipher = Cipher.getInstance(ALGORYTHM_DETAILS, "SunJCE");
+ ivspec = new IvParameterSpec(ArrayUtils.subarray(encryptedMessage, 0, BLOCK_SIZE / 8));
+ byte[] realData = ArrayUtils.subarray(encryptedMessage, BLOCK_SIZE / 8, encryptedMessage.length);
+ cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(skey), ivspec);
+ decrypted = cipher.doFinal(realData);
+
+ } catch (Exception ex) {
+
+
+ }
+
+ return new String(decrypted);
+ }
+
+ /**
+ * @deprecated Please use {@link #decryptPKC(String)} to Decrypt the text.
+ *
+ * Decrypts the text using the secret key in key.properties file.
+ *
+ * @param encryptedText
+ * Text to decrypt
+ * @return Decrypted text
+ * @
+ * if any decryption step fails
+ */
+ @Deprecated
+ public static String decrypt(String encryptedText) {
+ return CipherUtil.decrypt(encryptedText, keyString);
+ }
+
+ /**
+ *
+ * Decrypts the text using the secret key in key.properties file.
+ *
+ * @param encryptedText
+ * Text to decrypt
+ * @return Decrypted text
+ * @
+ * if any decryption step fails
+ */
+ public static String decryptPKC(String encryptedText) {
+ return CipherUtil.decryptPKC(encryptedText, keyString);
+ }
+
+
+ public static void readAndSetKeyString() {
+ try {
+ Scanner in = new Scanner(new FileReader("/opt/app/music/etc/properties.txt"));
+ StringBuilder sb = new StringBuilder();
+ while(in.hasNext()) {
+ sb.append(in.next());
+ }
+ in.close();
+ keyString = sb.toString();
+ } catch (FileNotFoundException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
+ }
+ }
+
+ /*public static void main(String[] args) {
+
+ System.out.println("Encrypted password: "+encryptPKC("cassandra"));
+
+ System.out.println("Decrypted password: "+decryptPKC("dDhqAp5/RwZbl9yRSZg15fN7Qul9eiE/JFkKemtTib0="));
+ System.out.println("Decrypted password: "+decryptPKC("I/dOtD/YYzBStbtOYhKuUUyPHSW2G9ZzdSyB8bJp4vk="));
+ System.out.println("Decrypted password: "+decryptPKC("g7zJqg74dLsH/fyL7I75b4eySy3pbMS2xVqkrB5lDl8="));
+ }*/
+
+}
diff --git a/jar/src/main/java/org/onap/music/main/CronJobManager.java b/jar/src/main/java/org/onap/music/main/CronJobManager.java
index fb4a2ac3..85769451 100644
--- a/jar/src/main/java/org/onap/music/main/CronJobManager.java
+++ b/jar/src/main/java/org/onap/music/main/CronJobManager.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.main;
import java.util.concurrent.Executors;
diff --git a/jar/src/main/java/org/onap/music/main/MusicCore.java b/jar/src/main/java/org/onap/music/main/MusicCore.java
index cad384a3..21509fa4 100644
--- a/jar/src/main/java/org/onap/music/main/MusicCore.java
+++ b/jar/src/main/java/org/onap/music/main/MusicCore.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.main;
@@ -87,7 +88,7 @@ public class MusicCore {
try {
mLockHandle = new MusicLockingService();
} catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKHANDLE,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKHANDLE,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
throw new MusicLockingException("Failed to aquire Locl store handle " + e);
}
}
@@ -105,11 +106,11 @@ public class MusicCore {
logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring data store handle");
long start = System.currentTimeMillis();
if (mDstoreHandle == null) {
- try {
- MusicUtil.loadProperties();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "No properties file defined. Falling back to default.");
- }
+ try {
+ MusicUtil.loadProperties();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "No properties file defined. Falling back to default.");
+ }
mDstoreHandle = new MusicDataStore(remoteIp);
}
long end = System.currentTimeMillis();
@@ -126,11 +127,11 @@ public class MusicCore {
logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring data store handle");
long start = System.currentTimeMillis();
if (mDstoreHandle == null) {
- try {
- MusicUtil.loadProperties();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "No properties file defined. Falling back to default.");
- }
+ try {
+ MusicUtil.loadProperties();
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, "No properties file defined. Falling back to default.");
+ }
// Quick Fix - Best to put this into every call to getDSHandle?
if (! MusicUtil.getMyCassaHost().equals("localhost") ) {
mDstoreHandle = new MusicDataStore(MusicUtil.getMyCassaHost());
@@ -139,9 +140,9 @@ public class MusicCore {
}
}
if(mDstoreHandle.getSession() == null) {
- String message = "Connection to Cassandra has not been enstablished."
- + " Please check connection properites and reboot.";
- logger.info(EELFLoggerDelegate.applicationLogger, message);
+ 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();
@@ -156,8 +157,8 @@ public class MusicCore {
try {
lockId = getLockingServiceHandle().createLockId("/" + lockName);
} catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.CREATELOCK+lockName,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
-
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.CREATELOCK+lockName,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+
}
long end = System.currentTimeMillis();
logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to create lock reference:" + (end - start) + " ms");
@@ -196,7 +197,7 @@ public class MusicCore {
logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to get lock state:" + (end - start) + " ms");
return mls;
} catch (NullPointerException | MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.INVALIDLOCK,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.INVALIDLOCK,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
}
return null;
}
@@ -221,7 +222,7 @@ public class MusicCore {
}
}
} else
- logger.error(EELFLoggerDelegate.errorLogger,key, AppMessages.INVALIDLOCK,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,key, AppMessages.INVALIDLOCK,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
/*
* call the traditional acquire lock now and if the result returned is true, set the
@@ -248,7 +249,7 @@ public class MusicCore {
}
} catch (Exception e) {
StringWriter sw = new StringWriter();
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR506E] Failed to aquire lock ",ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR506E] Failed to aquire lock ",ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
String exceptionAsString = sw.toString();
return new ReturnType(ResultType.FAILURE,
@@ -272,14 +273,14 @@ public class MusicCore {
if (!result) {
logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Not your turn, someone else has the lock");
try {
- if (!getLockingServiceHandle().lockIdExists(lockId)) {
- logger.info(EELFLoggerDelegate.applicationLogger, "In acquire lock: this lockId doesn't exist");
- return new ReturnType(ResultType.FAILURE, "Lockid doesn't exist");
- }
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.INVALIDLOCK+lockId,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- throw new MusicLockingException();
- }
+ if (!getLockingServiceHandle().lockIdExists(lockId)) {
+ logger.info(EELFLoggerDelegate.applicationLogger, "In acquire lock: this lockId doesn't exist");
+ return new ReturnType(ResultType.FAILURE, "Lockid doesn't exist");
+ }
+ } catch (MusicLockingException e) {
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.INVALIDLOCK+lockId,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ throw new MusicLockingException();
+ }
logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: returning failure");
return new ReturnType(ResultType.FAILURE, "Not your turn, someone else has the lock");
}
@@ -304,7 +305,7 @@ public class MusicCore {
return new ReturnType(ResultType.SUCCESS, "You already have the lock!");
}
} catch (NullPointerException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.INVALIDLOCK+lockId,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.INVALIDLOCK+lockId,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
}
// change status to "being locked". This state transition is necessary to ensure syncing
@@ -320,7 +321,7 @@ public class MusicCore {
try {
getLockingServiceHandle().setLockState(key, newMls);
} catch (MusicLockingException e1) {
- logger.error(EELFLoggerDelegate.errorLogger,e1.getMessage(), AppMessages.LOCKSTATE+key,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e1.getMessage(), AppMessages.LOCKSTATE+key,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
}
logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Set lock state to being_locked");
@@ -341,7 +342,7 @@ public class MusicCore {
try {
getLockingServiceHandle().setLockState(key, newMls);
} catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKSTATE+key,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKSTATE+key,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
}
logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Set lock state to locked and assigned current lock ref "
+ lockId + " as holder");
@@ -412,7 +413,7 @@ public class MusicCore {
getDSHandle().executePut(updateQuery, "critical");
} catch (MusicServiceException | MusicQueryException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery ,ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery ,ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR);
}
}
@@ -429,7 +430,7 @@ public class MusicCore {
try {
results = getDSHandle().executeCriticalGet(query);
} catch (MusicServiceException | MusicQueryException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.MAJOR, ErrorTypes.GENERALSERVICEERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.MAJOR, ErrorTypes.GENERALSERVICEERROR);
}
return results;
@@ -456,7 +457,7 @@ public class MusicCore {
try {
return getLockingServiceHandle().whoseTurnIsIt("/" + lockName) + "";
} catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKINGERROR+lockName ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKINGERROR+lockName ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
}
return null;
@@ -478,7 +479,7 @@ public class MusicCore {
try {
getLockingServiceHandle().unlockAndDeleteId(lockId);
} catch (MusicLockingException | NoNodeException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK+lockId ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK+lockId ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
}
long end = System.currentTimeMillis();
logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms");
@@ -489,11 +490,11 @@ public class MusicCore {
try {
getLockingServiceHandle().unlockAndDeleteId(lockId);
} catch (MusicLockingException e1) {
- logger.error(EELFLoggerDelegate.errorLogger,e1.getMessage(), AppMessages.RELEASELOCK+lockId ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e1.getMessage(), AppMessages.RELEASELOCK+lockId ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
} catch (KeeperException.NoNodeException nne) {
- logger.error(EELFLoggerDelegate.errorLogger,"Failed to release Lock " + lockId + " " + nne);
- MusicLockState mls = new MusicLockState("Lock doesn't exists. Release lock operation failed.");
- return mls;
+ logger.error(EELFLoggerDelegate.errorLogger,"Failed to release Lock " + lockId + " " + nne);
+ MusicLockState mls = new MusicLockState("Lock doesn't exists. Release lock operation failed.");
+ return mls;
}
String lockName = getLockNameFromId(lockId);
MusicLockState mls;
@@ -510,7 +511,7 @@ public class MusicCore {
try {
getLockingServiceHandle().setLockState(lockName, mls);
} catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.RELEASELOCK+lockId ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.RELEASELOCK+lockId ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
}
long end = System.currentTimeMillis();
logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to release lock:" + (end - start) + " ms");
@@ -518,12 +519,12 @@ public class MusicCore {
}
public static void voluntaryReleaseLock(String lockId) throws MusicLockingException{
- try {
- getLockingServiceHandle().unlockAndDeleteId(lockId);
- } catch (KeeperException.NoNodeException e) {
- // ??? No way
- }
- }
+ try {
+ getLockingServiceHandle().unlockAndDeleteId(lockId);
+ } catch (KeeperException.NoNodeException e) {
+ // ??? No way
+ }
+ }
/**
*
@@ -536,8 +537,8 @@ public class MusicCore {
try {
getLockingServiceHandle().deleteLock("/" + lockName);
} catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DELTELOCK+lockName ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- throw new MusicLockingException(e.getMessage());
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DELTELOCK+lockName ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ throw new MusicLockingException(e.getMessage());
}
long end = System.currentTimeMillis();
logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to delete lock:" + (end - start) + " ms");
@@ -565,7 +566,7 @@ public class MusicCore {
try {
getLockingServiceHandle().getzkLockHandle().createNode(nodeName);
} catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
}
}
@@ -580,7 +581,7 @@ public class MusicCore {
try {
getLockingServiceHandle().getzkLockHandle().setNodeData(nodeName, data);
} catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
}
logger.info(EELFLoggerDelegate.applicationLogger,"Performed zookeeper write to " + nodeName);
long end = System.currentTimeMillis();
@@ -598,7 +599,7 @@ public class MusicCore {
try {
data = getLockingServiceHandle().getzkLockHandle().getNodeData(nodeName);
} catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
}
long end = System.currentTimeMillis();
logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the actual zk put:" + (end - start) + " ms");
@@ -623,7 +624,7 @@ public class MusicCore {
try {
result = getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL);
} catch (MusicServiceException | MusicQueryException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage() + " " + ex.getCause() + " " + ex);
return new ReturnType(ResultType.FAILURE, ex.getMessage());
}
@@ -695,7 +696,7 @@ public class MusicCore {
try {
result = getDSHandle().executePut(queryObject, consistency);
} catch (MusicQueryException | MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
throw new MusicServiceException(ex.getMessage());
}
return result?ResultType.SUCCESS:ResultType.FAILURE;
@@ -711,7 +712,7 @@ public class MusicCore {
public static ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException {
ResultSet results = null;
try {
- results = getDSHandle().executeEventualGet(queryObject);
+ results = getDSHandle().executeEventualGet(queryObject);
} catch (MusicQueryException | MusicServiceException e) {
logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
throw new MusicServiceException(e.getMessage());
@@ -741,7 +742,7 @@ public class MusicCore {
} else
throw new MusicServiceException("YOU DO NOT HAVE THE LOCK");
} catch (MusicQueryException | MusicServiceException | MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
}
return results;
}
@@ -853,31 +854,31 @@ public class MusicCore {
voluntaryReleaseLock(lockId);
return result;
} else {
- destroyLockRef(lockId);
+ destroyLockRef(lockId);
logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId);
return null;
}
}
- public static ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException {
- String key = keyspaceName + "." + tableName + "." + primaryKey;
- String lockId = createLockReference(key);
- long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
-
- ReturnType lockAcqResult = acquireLock(key, lockId);
-
- if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
- logger.info(EELFLoggerDelegate.applicationLogger, "acquired lock with id " + lockId);
- ResultSet result = criticalGet(keyspaceName, tableName, primaryKey, queryObject, lockId);
- deleteLock(key);
- return result;
- } else {
- deleteLock(key);
- logger.info(EELFLoggerDelegate.applicationLogger, "unable to acquire lock, id " + lockId);
- return null;
- }
- }
+ public static ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey,
+ PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException {
+ String key = keyspaceName + "." + tableName + "." + primaryKey;
+ String lockId = createLockReference(key);
+ long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
+
+ ReturnType lockAcqResult = acquireLock(key, lockId);
+
+ if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
+ logger.info(EELFLoggerDelegate.applicationLogger, "acquired lock with id " + lockId);
+ ResultSet result = criticalGet(keyspaceName, tableName, primaryKey, queryObject, lockId);
+ deleteLock(key);
+ return result;
+ } else {
+ deleteLock(key);
+ logger.info(EELFLoggerDelegate.applicationLogger, "unable to acquire lock, id " + lockId);
+ return null;
+ }
+ }
@@ -916,7 +917,7 @@ public class MusicCore {
}
boolean isAAF = Boolean.valueOf(isAAFApp);
if (userId == null || password == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: " + userId
+ " :: password: " + password);
resultMap.put("Exception",
@@ -932,14 +933,14 @@ public class MusicCore {
if (isAAF && nameSpace != null && userId != null && password != null) {
boolean isValid = true;
try {
- isValid = CachingUtil.authenticateAAFUser(nameSpace, userId, password, keyspace);
+ isValid = CachingUtil.authenticateAAFUser(nameSpace, userId, password, keyspace);
} catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
logger.error(EELFLoggerDelegate.errorLogger,"Got exception while AAF authentication for namespace " + nameSpace);
resultMap.put("Exception", e.getMessage());
}
if (!isValid) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
resultMap.put("Exception", "User not authenticated...");
}
if (!resultMap.isEmpty())
diff --git a/jar/src/main/java/org/onap/music/main/MusicDigest.java b/jar/src/main/java/org/onap/music/main/MusicDigest.java
index 893cb51f..d05969e3 100644
--- a/jar/src/main/java/org/onap/music/main/MusicDigest.java
+++ b/jar/src/main/java/org/onap/music/main/MusicDigest.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.main;
/**
diff --git a/jar/src/main/java/org/onap/music/main/MusicUtil.java b/jar/src/main/java/org/onap/music/main/MusicUtil.java
index f18570db..4acc3c5a 100755
--- a/jar/src/main/java/org/onap/music/main/MusicUtil.java
+++ b/jar/src/main/java/org/onap/music/main/MusicUtil.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.main;
import java.io.File;
@@ -81,8 +82,9 @@ public class MusicUtil {
"all.pubic.ips", "cassandra.user", "cassandra.password", "aaf.endpoint.url" };
private static String cassName = "cassandra";
- private static String cassPwd = "cassandra";
+ private static String cassPwd = "";
private static String aafEndpointUrl = null;
+ private static int cassandraPort = 9042;
private MusicUtil() {
throw new IllegalStateException("Utility Class");
@@ -341,6 +343,21 @@ public class MusicUtil {
}
/**
+ *
+ * @return cassandra port
+ */
+ public static int getCassandraPort() {
+ return cassandraPort;
+ }
+
+ /**
+ * set cassandra port
+ * @param cassandraPort
+ */
+ public static void setCassandraPort(int cassandraPort) {
+ MusicUtil.cassandraPort = cassandraPort;
+ }
+ /**
*
* @return
*/
@@ -531,30 +548,43 @@ public class MusicUtil {
public static void loadProperties() throws Exception {
- Properties prop = new Properties();
- InputStream input = null;
- try {
- // load the properties file
- input = MusicUtil.class.getClassLoader().getResourceAsStream("music.properties");
- prop.load(input);
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file.");
- throw new Exception();
- } finally {
- if (input != null) {
- try {
- input.close();
- } catch (IOException e) {
- e.printStackTrace();
- }
- }
- }
- // get the property value and return it
- MusicUtil.setMyCassaHost(prop.getProperty("cassandra.host"));
- String zkHosts = prop.getProperty("zookeeper.host");
- MusicUtil.setMyZkHost(zkHosts);
- MusicUtil.setCassName(prop.getProperty("cassandra.user"));
- MusicUtil.setCassPwd(prop.getProperty("cassandra.password"));
- }
+ CipherUtil.readAndSetKeyString();
+ Properties prop = new Properties();
+ InputStream input = null;
+ try {
+ // load the properties file
+ input = MusicUtil.class.getClassLoader().getResourceAsStream("music.properties");
+ prop.load(input);
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file.");
+ throw new Exception();
+ } finally {
+ if (input != null) {
+ try {
+ input.close();
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+ }
+ String cassPwd = prop.getProperty("cassandra.password");
+ String isEncrypted = prop.getProperty("cassandra.password.isencrypted");
+ if("true".equals(isEncrypted)) {
+ logger.debug(EELFLoggerDelegate.applicationLogger,"Decrypting....");
+ cassPwd = CipherUtil.decryptPKC(cassPwd);
+ logger.debug(EELFLoggerDelegate.applicationLogger,"Password Decrypted");
+ MusicUtil.setCassPwd(cassPwd);
+ } else
+ MusicUtil.setCassPwd(cassPwd);
+ // get the property value and return it
+ MusicUtil.setMyCassaHost(prop.getProperty("cassandra.host"));
+ String zkHosts = prop.getProperty("zookeeper.host");
+ MusicUtil.setMyZkHost(zkHosts);
+ MusicUtil.setCassName(prop.getProperty("cassandra.user"));
+ String cassPort = prop.getProperty("cassandra.port");
+ if(cassPort != null)
+ MusicUtil.setCassandraPort(Integer.parseInt(cassPort));
+ }
+
}
diff --git a/jar/src/main/java/org/onap/music/main/PropertiesListener.java b/jar/src/main/java/org/onap/music/main/PropertiesListener.java
index afd35387..724d3d45 100755
--- a/jar/src/main/java/org/onap/music/main/PropertiesListener.java
+++ b/jar/src/main/java/org/onap/music/main/PropertiesListener.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.main;
import java.io.FileInputStream;
@@ -80,7 +81,7 @@ public class PropertiesListener implements ServletContextListener {
break;
case "debug":
MusicUtil.setDebug(Boolean
- .getBoolean(prop.getProperty(key).toLowerCase()));
+ .parseBoolean(prop.getProperty(key).toLowerCase()));
break;
case "version":
MusicUtil.setVersion(prop.getProperty(key));
@@ -130,7 +131,7 @@ public class PropertiesListener implements ServletContextListener {
}
}
} catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.IOERROR ,ErrorSeverity.CRITICAL, ErrorTypes.CONNECTIONERROR);
+ logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.IOERROR ,ErrorSeverity.CRITICAL, ErrorTypes.CONNECTIONERROR);
logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
}
diff --git a/jar/src/main/java/org/onap/music/main/ResultType.java b/jar/src/main/java/org/onap/music/main/ResultType.java
index 61ba0295..f5ef2070 100644
--- a/jar/src/main/java/org/onap/music/main/ResultType.java
+++ b/jar/src/main/java/org/onap/music/main/ResultType.java
@@ -19,13 +19,14 @@
* ============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.");
-
+ SYNTAXERROR("SyntaxError"), EXCEPTION("Exception"),
+ BODYMISSING("Incomplete Request body. Please correct your input request and retry.");
+
private String result;
ResultType(String result) {
diff --git a/jar/src/main/java/org/onap/music/main/ReturnType.java b/jar/src/main/java/org/onap/music/main/ReturnType.java
index 1453a1bf..e3905fd8 100644
--- a/jar/src/main/java/org/onap/music/main/ReturnType.java
+++ b/jar/src/main/java/org/onap/music/main/ReturnType.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.main;
import java.util.HashMap;
diff --git a/jar/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java b/jar/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java
index a406afce..9d4f5ed9 100644
--- a/jar/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java
+++ b/jar/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.response.jsonobjects;
import java.util.HashMap;
@@ -39,7 +40,7 @@ import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "JsonResponse", description = "General Response JSON")
public class JsonResponse {
- /* Status is required */
+ /* Status is required */
private ResultType status;
/* Standard informational fields */
@@ -69,7 +70,7 @@ public class JsonResponse {
this.status = status;
}
- /**
+ /**
*
* @return
*/
@@ -130,7 +131,7 @@ public class JsonResponse {
* @return the music version
*/
public String getMusicVersion() {
- return this.musicVersion;
+ return this.musicVersion;
}
/**
@@ -139,20 +140,20 @@ public class JsonResponse {
* @return
*/
public JsonResponse setMusicVersion(String version) {
- this.musicVersion = version;
- return this;
+ this.musicVersion = version;
+ return this;
}
public Map<String, HashMap<String, Object>> getDataResult() {
- return this.dataResult;
+ return this.dataResult;
}
public JsonResponse setDataResult(Map<String, HashMap<String, Object>> map) {
- this.dataResult = map;
- return this;
+ this.dataResult = map;
+ return this;
}
- /**
+ /**
*
* @return
*/
@@ -237,16 +238,16 @@ public class JsonResponse {
if (musicVersion!=null) {fullMap.put("version", musicVersion);}
if (dataResult!=null) {
- fullMap.put("result", dataResult);
+ fullMap.put("result", dataResult);
}
if (lock!=null) {
- Map<String, Object> lockMap = new HashMap<>();
- if (lock!=null) {lockMap.put("lock", lock);}
- if (lockStatus!=null) {lockMap.put("lock-status", lockStatus);}
- if (lockHolder!=null) {lockMap.put("lock-holder", lockHolder);}
- if (lockLease!=null) {lockMap.put("lock-lease", lockLease);}
- fullMap.put("lock", lockMap);
+ Map<String, Object> lockMap = new HashMap<>();
+ if (lock!=null) {lockMap.put("lock", lock);}
+ if (lockStatus!=null) {lockMap.put("lock-status", lockStatus);}
+ if (lockHolder!=null) {lockMap.put("lock-holder", lockHolder);}
+ if (lockLease!=null) {lockMap.put("lock-lease", lockLease);}
+ fullMap.put("lock", lockMap);
}
return fullMap;
diff --git a/jar/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java b/jar/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java
index e7c7fb6c..cc7c01c7 100755
--- a/jar/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java
+++ b/jar/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.rest;
diff --git a/jar/src/main/java/org/onap/music/rest/RestMusicBmAPI.java b/jar/src/main/java/org/onap/music/rest/RestMusicBmAPI.java
index 55eb47f2..097c7b40 100644
--- a/jar/src/main/java/org/onap/music/rest/RestMusicBmAPI.java
+++ b/jar/src/main/java/org/onap/music/rest/RestMusicBmAPI.java
@@ -15,6 +15,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.rest;
import java.util.List;
diff --git a/jar/src/main/java/org/onap/music/rest/RestMusicDataAPI.java b/jar/src/main/java/org/onap/music/rest/RestMusicDataAPI.java
index 47d1eae7..4b29f9a1 100755
--- a/jar/src/main/java/org/onap/music/rest/RestMusicDataAPI.java
+++ b/jar/src/main/java/org/onap/music/rest/RestMusicDataAPI.java
@@ -7,18 +7,19 @@
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
- *
+ *
* http://www.apache.org/licenses/LICENSE-2.0
- *
+ *
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS 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.ArrayList;
@@ -85,7 +86,7 @@ public class RestMusicDataAPI {
* (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
@@ -107,7 +108,7 @@ public class RestMusicDataAPI {
private static final String USERID = "userId";
private static final String PASSWORD = "password";
private static final String VERSION = "v2";
-
+
private class RowIdentifier {
public String primarKeyValue;
public StringBuilder rowIdString;
@@ -126,7 +127,7 @@ public class RestMusicDataAPI {
/**
* Create Keyspace REST
- *
+ *
* @param kspObject
* @param keyspaceName
* @return
@@ -149,7 +150,7 @@ public class RestMusicDataAPI {
JsonKeySpace kspObject,
@ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) {
ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
+
Map<String, Object> authMap = CachingUtil.verifyOnboarding(ns, userId, password);
if (!authMap.isEmpty()) {
logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
@@ -192,7 +193,7 @@ public class RestMusicDataAPI {
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);
@@ -214,28 +215,32 @@ public class RestMusicDataAPI {
logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("err:" + ex.getMessage()).toMap()).build();
}
-
+
try {
queryObject = new PreparedQueryObject();
- queryObject.appendQueryString("CREATE ROLE IF NOT EXISTS '" + userId
- + "' WITH PASSWORD = '" + password + "' AND LOGIN = true;");
+// queryObject.appendQueryString("CREATE ROLE IF NOT EXISTS '" + userId
+// + "' WITH PASSWORD = '" + password + "' AND LOGIN = true;");
+ queryObject.appendQueryString("CREATE ROLE IF NOT EXISTS ? "
+ + " WITH PASSWORD = ? AND LOGIN = true;");
+ queryObject.addValue(userId);
+ queryObject.addValue(password);
MusicCore.nonKeyRelatedPut(queryObject, consistency);
queryObject = new PreparedQueryObject();
queryObject.appendQueryString("GRANT ALL PERMISSIONS on KEYSPACE " + keyspaceName
- + " to '" + userId + "'");
+ + " to '" + userId + "'");
queryObject.appendQueryString(";");
MusicCore.nonKeyRelatedPut(queryObject, consistency);
} catch (Exception e) {
logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
}
-
+
try {
boolean isAAF = Boolean.valueOf(CachingUtil.isAAFApplication(ns));
String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt());
queryObject = new PreparedQueryObject();
queryObject.appendQueryString(
- "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
- + "password, username, is_aaf) values (?,?,?,?,?,?,?)");
+ "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
+ + "password, username, is_aaf) values (?,?,?,?,?,?,?)");
queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), newAid));
queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName));
queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
@@ -250,12 +255,12 @@ public class RestMusicDataAPI {
logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
}
-
+
return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Created").toMap()).build();
}
/**
- *
+ *
* @param kspObject
* @param keyspaceName
* @return
@@ -325,7 +330,7 @@ public class RestMusicDataAPI {
}
/**
- *
+ *
* @param tableObj
* @param version
* @param keyspace
@@ -369,7 +374,7 @@ public class RestMusicDataAPI {
int counter = 0;
String primaryKey;
for (Map.Entry<String, String> entry : fields.entrySet()) {
-
+
if (entry.getKey().equals("PRIMARY KEY")) {
if(! entry.getValue().contains("("))
primaryKey = entry.getValue();
@@ -433,7 +438,7 @@ public class RestMusicDataAPI {
}
/**
- *
+ *
* @param keyspace
* @param tablename
* @param fieldName
@@ -473,7 +478,7 @@ public class RestMusicDataAPI {
PreparedQueryObject query = new PreparedQueryObject();
query.appendQueryString("Create index " + indexName + " if not exists on " + keyspace + "."
+ tablename + " (" + fieldName + ");");
-
+
ResultType result = ResultType.FAILURE;
try {
result = MusicCore.nonKeyRelatedPut(query, "eventual");
@@ -490,7 +495,7 @@ public class RestMusicDataAPI {
}
/**
- *
+ *
* @param insObj
* @param keyspace
* @param tablename
@@ -518,7 +523,7 @@ public class RestMusicDataAPI {
ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
Map<String, Object> authMap = null;
-
+
try {
authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
aid, "insertIntoTable");
@@ -587,7 +592,7 @@ public class RestMusicDataAPI {
}
counter = counter + 1;
}
-
+
if(primaryKey == null || primaryKey.length() <= 0) {
logger.error(EELFLoggerDelegate.errorLogger, "Some required partition key parts are missing: "+primaryKeyName );
return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Some required partition key parts are missing: "+primaryKeyName).toMap()).build();
@@ -646,7 +651,7 @@ public class RestMusicDataAPI {
logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
}
-
+
if (result==null) {
logger.error(EELFLoggerDelegate.errorLogger,"", 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();
@@ -655,7 +660,7 @@ public class RestMusicDataAPI {
}
/**
- *
+ *
* @param insObj
* @param keyspace
* @param tablename
@@ -853,7 +858,7 @@ public class RestMusicDataAPI {
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();
@@ -864,11 +869,11 @@ public class RestMusicDataAPI {
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();
}
-
+
}
/**
- *
+ *
* @param delObj
* @param keyspace
* @param tablename
@@ -1014,7 +1019,7 @@ public class RestMusicDataAPI {
}
/**
- *
+ *
* @param tabObj
* @param keyspace
* @param tablename
@@ -1066,7 +1071,7 @@ public class RestMusicDataAPI {
}
/**
- *
+ *
* @param selObj
* @param keyspace
* @param tablename
@@ -1137,7 +1142,7 @@ public class RestMusicDataAPI {
} else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
results = MusicCore.atomicGet(keyspace, tablename, rowId.primarKeyValue, queryObject);
}
-
+
else if (consistency.equalsIgnoreCase(MusicUtil.ATOMICDELETELOCK)) {
results = MusicCore.atomicGetWithDeleteLock(keyspace, tablename, rowId.primarKeyValue, queryObject);
}
@@ -1146,7 +1151,7 @@ public class RestMusicDataAPI {
}
/**
- *
+ *
* @param keyspace
* @param tablename
* @param info
@@ -1212,7 +1217,7 @@ public class RestMusicDataAPI {
}
/**
- *
+ *
* @param keyspace
* @param tablename
* @param info
@@ -1242,7 +1247,7 @@ public class RestMusicDataAPI {
}
/**
- *
+ *
* @param keyspace
* @param tablename
* @param rowParams
diff --git a/jar/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java b/jar/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java
index 752a538b..c1071e5b 100644
--- a/jar/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java
+++ b/jar/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.rest;
import java.util.HashMap;
@@ -58,56 +59,56 @@ import io.swagger.annotations.ApiOperation;
@Path("/v{version: [0-9]+}/service")
@Api(value="Healthcheck Api")
public class RestMusicHealthCheckAPI {
-
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
-
-
- @GET
- @Path("/cs")
- @ApiOperation(value = "Get Health Status", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response cassandraStatus(@Context HttpServletResponse response) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for MUSIC Health Check status for Cassandra");
-
- Map<String, Object> resultMap = new HashMap<>();
-
- MusicHealthCheck cassHealthCheck = new MusicHealthCheck();
- String status = cassHealthCheck.getCassandraStatus();
- if(status.equals("ACTIVE")) {
- resultMap.put("ACTIVE", "Cassandra Running and Listening to requests");
- return Response.status(Status.OK).entity(resultMap).build();
- }else {
- resultMap.put("INACTIVE", "Cassandra Service is not responding");
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
-
-
-
- }
-
- @GET
- @Path("/zk")
- @ApiOperation(value = "Get Health Status", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response ZKStatus(@Context HttpServletResponse response) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for MUSIC Health Check status for Zookeeper");
- Map<String, Object> resultMap = new HashMap<>();
- MusicHealthCheck ZKHealthCheck = new MusicHealthCheck();
- String status = ZKHealthCheck.getZookeeperStatus();
- if(status.equals("ACTIVE")) {
- resultMap.put("ACTIVE", "Zookeeper is Active and Running");
- return Response.status(Status.OK).entity(resultMap).build();
- }else {
- resultMap.put("INACTIVE", "Zookeeper is not responding");
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- }
-
-
-
-
-
-
+
+
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
+
+
+ @GET
+ @Path("/cs")
+ @ApiOperation(value = "Get Health Status", response = Map.class)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response cassandraStatus(@Context HttpServletResponse response) {
+ logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for MUSIC Health Check status for Cassandra");
+
+ Map<String, Object> resultMap = new HashMap<>();
+
+ MusicHealthCheck cassHealthCheck = new MusicHealthCheck();
+ String status = cassHealthCheck.getCassandraStatus();
+ if(status.equals("ACTIVE")) {
+ resultMap.put("ACTIVE", "Cassandra Running and Listening to requests");
+ return Response.status(Status.OK).entity(resultMap).build();
+ }else {
+ resultMap.put("INACTIVE", "Cassandra Service is not responding");
+ return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
+ }
+
+
+
+ }
+
+ @GET
+ @Path("/zk")
+ @ApiOperation(value = "Get Health Status", response = Map.class)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Response ZKStatus(@Context HttpServletResponse response) {
+ logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for MUSIC Health Check status for Zookeeper");
+ Map<String, Object> resultMap = new HashMap<>();
+ MusicHealthCheck ZKHealthCheck = new MusicHealthCheck();
+ String status = ZKHealthCheck.getZookeeperStatus();
+ if(status.equals("ACTIVE")) {
+ resultMap.put("ACTIVE", "Zookeeper is Active and Running");
+ return Response.status(Status.OK).entity(resultMap).build();
+ }else {
+ resultMap.put("INACTIVE", "Zookeeper is not responding");
+ return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
+ }
+ }
+
+
+
+
+
+
}
diff --git a/jar/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java b/jar/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java
index 22112ddf..5b587511 100644
--- a/jar/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java
+++ b/jar/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.rest;
import java.util.Map;
@@ -413,10 +414,10 @@ public class RestMusicLocksAPI {
return response.status(Status.BAD_REQUEST).entity(resultMap).build();
}
try{
- MusicCore.deleteLock(lockName);
+ MusicCore.deleteLock(lockName);
}catch (Exception 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();
}
diff --git a/jar/src/main/java/org/onap/music/rest/RestMusicQAPI.java b/jar/src/main/java/org/onap/music/rest/RestMusicQAPI.java
index e08adaf7..1c964074 100755
--- a/jar/src/main/java/org/onap/music/rest/RestMusicQAPI.java
+++ b/jar/src/main/java/org/onap/music/rest/RestMusicQAPI.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.rest;
diff --git a/jar/src/main/java/org/onap/music/rest/RestMusicTestAPI.java b/jar/src/main/java/org/onap/music/rest/RestMusicTestAPI.java
index 287fa176..539f43f3 100644
--- a/jar/src/main/java/org/onap/music/rest/RestMusicTestAPI.java
+++ b/jar/src/main/java/org/onap/music/rest/RestMusicTestAPI.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.rest;
import java.util.HashMap;
@@ -41,27 +42,27 @@ import io.swagger.annotations.ApiOperation;
@Path("/v{version: [0-9]+}/test")
@Api(value="Test Api")
public class RestMusicTestAPI {
-
- @SuppressWarnings("unused")
+
+ @SuppressWarnings("unused")
private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicTestAPI.class);
- /**
- * Returns a test JSON. This will confirm that REST is working.
- * @return
- */
- @GET
- @ApiOperation(value = "Get Test", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Map<String, HashMap<String, String>> simpleTests(
- @Context HttpServletResponse response) {
- response.addHeader("X-latestVersion",MusicUtil.getVersion());
- Map<String, HashMap<String, String>> testMap = new HashMap<>();
- for(int i=0; i < 3; i++){
- HashMap<String, String> innerMap = new HashMap<>();
- innerMap.put(i+"", i+1+"");
- innerMap.put(i+1+"", i+2+"");
- testMap.put(i+"", innerMap);
- }
- return testMap;
- }
+ /**
+ * Returns a test JSON. This will confirm that REST is working.
+ * @return
+ */
+ @GET
+ @ApiOperation(value = "Get Test", response = Map.class)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Map<String, HashMap<String, String>> simpleTests(
+ @Context HttpServletResponse response) {
+ response.addHeader("X-latestVersion",MusicUtil.getVersion());
+ Map<String, HashMap<String, String>> testMap = new HashMap<>();
+ for(int i=0; i < 3; i++){
+ HashMap<String, String> innerMap = new HashMap<>();
+ innerMap.put(i+"", i+1+"");
+ innerMap.put(i+1+"", i+2+"");
+ testMap.put(i+"", innerMap);
+ }
+ return testMap;
+ }
}
diff --git a/jar/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java b/jar/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java
index a5f2ac49..74b8e5dd 100644
--- a/jar/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java
+++ b/jar/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.rest;
import java.util.Map;
@@ -46,18 +47,18 @@ import io.swagger.annotations.ApiOperation;
@Api(value="Version Api")
public class RestMusicVersionAPI {
- private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicVersionAPI.class);
-
- /**
- * Get the version of MUSIC
- * @return
- */
- @GET
- @ApiOperation(value = "Get Version", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Map<String,Object> 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:" + MusicUtil.getVersion()).toMap();
- }
+ private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicVersionAPI.class);
+
+ /**
+ * Get the version of MUSIC
+ * @return
+ */
+ @GET
+ @ApiOperation(value = "Get Version", response = Map.class)
+ @Produces(MediaType.APPLICATION_JSON)
+ public Map<String,Object> 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:" + MusicUtil.getVersion()).toMap();
+ }
} \ No newline at end of file
diff --git a/jar/src/main/resources/logback.xml b/jar/src/main/resources/logback.xml
index fe7f54ae..ecf99b15 100644
--- a/jar/src/main/resources/logback.xml
+++ b/jar/src/main/resources/logback.xml
@@ -42,7 +42,7 @@
<property name="applicationLoggerPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %msg%n" />
<property name="auditLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
<property name="metricsLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
- <property name="errorLoggerPattern" value= "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %msg%n " />
+ <property name="errorLoggerPattern" value= "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %msg%n " />
<property name="debugLoggerPattern" value="%date{ISO8601,UTC}|%X{RequestId}| %msg%n" ></property>
<property name="logDirectory" value="${logDir}/${componentName}" />
<property name="debugLogDirectory" value="${debugDir}/${componentName}" />
@@ -53,7 +53,7 @@
</encoder> -->
<layout class="">
<pattern>
- %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
+ %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</layout>
</appender>
@@ -106,7 +106,7 @@
<maxFileSize>5MB</maxFileSize>
</triggeringPolicy>
<encoder>
- <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n </pattern>
+ <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n </pattern>
</encoder>
</appender>
diff --git a/jar/src/main/resources/project.properties b/jar/src/main/resources/project.properties
index 199afa33..a6814430 100644
--- a/jar/src/main/resources/project.properties
+++ b/jar/src/main/resources/project.properties
@@ -1,4 +1,3 @@
version=${project.version}
artifactId=${project.artifactId}
-music.properties=/opt/app/music/etc/music.properties
-
+music.properties=/opt/app/music/etc/music.properties \ No newline at end of file
diff --git a/jar/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java b/jar/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java
index 16d2af02..5a6838b0 100644
--- a/jar/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java
+++ b/jar/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.unittests;
import static org.junit.Assert.assertEquals;
diff --git a/jar/src/test/java/org/onap/music/unittests/TestLockStore.java b/jar/src/test/java/org/onap/music/unittests/TestLockStore.java
index 4dbc7b4f..70ba88c4 100644
--- a/jar/src/test/java/org/onap/music/unittests/TestLockStore.java
+++ b/jar/src/test/java/org/onap/music/unittests/TestLockStore.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.unittests;
import org.apache.log4j.Logger;
diff --git a/jar/src/test/java/org/onap/music/unittests/TestMusicCore.java b/jar/src/test/java/org/onap/music/unittests/TestMusicCore.java
index e798aaf1..4cc801b4 100644
--- a/jar/src/test/java/org/onap/music/unittests/TestMusicCore.java
+++ b/jar/src/test/java/org/onap/music/unittests/TestMusicCore.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.unittests;
import static org.junit.Assert.*;
diff --git a/jar/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java b/jar/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java
index d327d0f0..9ea104a9 100644
--- a/jar/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java
+++ b/jar/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java
@@ -15,6 +15,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.unittests;
import static org.junit.Assert.assertEquals;
diff --git a/jar/src/test/java/org/onap/music/unittests/TestRestMusicData.java b/jar/src/test/java/org/onap/music/unittests/TestRestMusicData.java
index febf6c76..908e2a11 100644
--- a/jar/src/test/java/org/onap/music/unittests/TestRestMusicData.java
+++ b/jar/src/test/java/org/onap/music/unittests/TestRestMusicData.java
@@ -15,6 +15,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.unittests;
import static org.junit.Assert.assertEquals;
diff --git a/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java b/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java
index 885694bd..4c5af38f 100644
--- a/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java
+++ b/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.unittests.jsonobjects;
import static org.junit.Assert.*;
diff --git a/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java b/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java
index 882d5d5e..0f4abd7c 100644
--- a/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java
+++ b/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.unittests.jsonobjects;
import static org.junit.Assert.*;
diff --git a/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java b/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java
index 63f901c6..0014093d 100644
--- a/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java
+++ b/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.unittests.jsonobjects;
import static org.junit.Assert.*;
diff --git a/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonOnboardTest.java b/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonOnboardTest.java
index 82f1748a..1e66ed58 100644
--- a/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonOnboardTest.java
+++ b/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonOnboardTest.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.unittests.jsonobjects;
import static org.junit.Assert.*;
diff --git a/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java b/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java
index 0243232f..c56e9b44 100644
--- a/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java
+++ b/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.unittests.jsonobjects;
import static org.junit.Assert.*;
diff --git a/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java b/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java
index 54db0540..6196a3ad 100644
--- a/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java
+++ b/jar/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*******************************************************************************/
+
package org.onap.music.unittests.jsonobjects;
import static org.junit.Assert.*;
diff --git a/jar/version.properties b/jar/version.properties
index 2ffa6347..fbd855ff 100644
--- a/jar/version.properties
+++ b/jar/version.properties
@@ -4,7 +4,7 @@
major=2
minor=5
-patch=6
+patch=9
base_version=${major}.${minor}.${patch}
diff --git a/music-core/pom.xml b/music-core/pom.xml
new file mode 100755
index 00000000..cf7f59e9
--- /dev/null
+++ b/music-core/pom.xml
@@ -0,0 +1,459 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ============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=============================================
+ ====================================================================
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.onap.music</groupId>
+ <artifactId>MUSIC-core</artifactId>
+ <packaging>jar</packaging>
+ <version>3.2.40-SNAPSHOT</version>
+ <description>
+ This is the MUSIC core interface, packaged as a jar file.
+ </description>
+ <name>music-core</name>
+
+ <parent>
+ <groupId>org.onap.music</groupId>
+ <artifactId>MUSIC</artifactId>
+ <version>3.2.40-SNAPSHOT</version>
+ </parent>
+
+ <properties>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <java.version>1.8</java.version>
+ <jaxrs.version>2.0.1</jaxrs.version>
+ <cassandra.version>3.6.0</cassandra.version>
+ </properties>
+
+ <repositories>
+ <repository>
+ <id>onap-releases</id>
+ <name>ONAP - Release Repository</name>
+ <url>${nexusproxy}/${releaseNexusPath}</url>
+ </repository>
+ <repository>
+ <id>onap-staging</id>
+ <name>ONAP - Staging Repository</name>
+ <url>${nexusproxy}/${stagingNexusPath}</url>
+ </repository>
+ <repository>
+ <id>onap-snapshots</id>
+ <name>ONAP - Snapshot Repository</name>
+ <url>${nexusproxy}/${snapshotNexusPath}</url>
+ </repository>
+ <repository>
+ <id>onap-public</id>
+ <name>ONAP public Repository</name>
+ <url>${nexusproxy}/content/groups/public</url>
+ </repository>
+ </repositories>
+
+ <build>
+ <finalName>${project.artifactId}</finalName>
+ <sourceDirectory>src/main/java</sourceDirectory>
+ <outputDirectory>src/main/webapp/WEB-INF/classes</outputDirectory>
+ <testSourceDirectory>src/test/java</testSourceDirectory>
+ <testOutputDirectory>target/test-classes</testOutputDirectory>
+ <defaultGoal>validate</defaultGoal>
+ <resources>
+ <resource>
+ <directory>src/main/resources</directory>
+ <filtering>true</filtering>
+ <includes>
+ <include>**/*.properties</include>
+ <include>**/*.xml</include>
+ <include>**/*.ccf</include>
+ </includes>
+ </resource>
+ </resources>
+ <testResources>
+ <testResource>
+ <directory>${project.basedir}/src/test/resources</directory>
+ </testResource>
+ </testResources>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-checkstyle-plugin</artifactId>
+ <configuration>
+ <skip>${maven.check.skip}</skip>
+ </configuration>
+ </plugin>
+
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-jar-plugin</artifactId>
+ <version>2.4</version>
+ <executions>
+ <execution>
+ <id>make-a-jar</id>
+ <phase>compile</phase>
+ <goals>
+ <goal>jar</goal>
+ </goals>
+ <configuration>
+ <excludes>
+ <exclude>**/Sample*</exclude>
+ </excludes>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-install-plugin</artifactId>
+ <version>2.4</version>
+ <executions>
+ <execution>
+ <id>core</id>
+ <phase>install</phase>
+ <goals>
+ <goal>install-file</goal>
+ </goals>
+ <configuration>
+ <packaging>jar</packaging>
+ <artifactId>${project.artifactId}</artifactId>
+ <groupId>${project.groupId}</groupId>
+ <version>${project.version}</version>
+ <file>${project.build.directory}/${project.artifactId}.jar</file>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+
+ <dependencies>
+ <!-- Logging -->
+ <dependency>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-core</artifactId>
+ <version>1.2.3</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
+ <version>1.2.3</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>com.att.eelf</groupId>
+ <artifactId>eelf-core</artifactId>
+ <version>1.0.1-oss</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-api-mockito</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.powermock</groupId>
+ <artifactId>powermock-module-junit4</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <!-- End Logging -->
+ <!-- Cassandra -->
+ <dependency>
+ <groupId>io.dropwizard.metrics</groupId>
+ <artifactId>metrics-core</artifactId>
+ <version>4.1.0-rc3</version>
+ </dependency>
+ <dependency>
+ <groupId>com.datastax.cassandra</groupId>
+ <artifactId>cassandra-driver-core</artifactId>
+ <version>${cassandra.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>com.datastax.cassandra</groupId>
+ <artifactId>cassandra-driver-extras</artifactId>
+ <version>${cassandra.version}</version>
+ </dependency>
+ <!-- /Cassandra -->
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-jcs-core</artifactId>
+ <version>2.2</version>
+ </dependency>
+ <dependency>
+ <groupId>commons-codec</groupId>
+ <artifactId>commons-codec</artifactId>
+ <version>1.11</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.commons</groupId>
+ <artifactId>commons-lang3</artifactId>
+ <version>3.8</version>
+ </dependency>
+
+ <!-- Testing -->
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.12</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.cassandraunit</groupId>
+ <artifactId>cassandra-unit-spring</artifactId>
+ <version>3.5.0.1</version>
+ <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.cassandraunit</groupId>
+ <artifactId>cassandra-unit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>io.dropwizard.metrics</groupId>
+ <artifactId>metrics-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.addthis.metrics</groupId>
+ <artifactId>reporter-config-base</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.cassandraunit</groupId>
+ <artifactId>cassandra-unit-shaded</artifactId>
+ <version>3.5.0.1</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>2.23.4</version>
+ <scope>test</scope>
+ </dependency>
+ <!-- /Testing -->
+ <!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.datatype/jackson-datatype-jsr310 -->
+ <dependency>
+ <groupId>com.fasterxml.jackson.datatype</groupId>
+ <artifactId>jackson-datatype-jsr310</artifactId>
+ <version>2.9.9</version>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-databind</artifactId>
+ <version>2.9.9.2</version>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-core</artifactId>
+ <version>2.9.9</version>
+ </dependency>
+ <dependency>
+ <groupId>com.fasterxml.jackson.core</groupId>
+ <artifactId>jackson-annotations</artifactId>
+ <version>2.9.9</version>
+ </dependency>
+ <dependency>
+ <groupId>org.apache.httpcomponents</groupId>
+ <artifactId>httpclient</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>io.swagger</groupId>
+ <artifactId>swagger-jersey-jaxrs</artifactId>
+ <version>1.5.22</version>
+ <exclusions>
+ <exclusion>
+ <groupId>com.sun.jersey.contribs</groupId>
+ <artifactId>jersey-multipart</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>javax.ws.rs</groupId>
+ <artifactId>jsr311-api</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>com.sun.jersey.contribs</groupId>
+ <artifactId>jersey-multipart</artifactId>
+ <version>1.19</version>
+ <exclusions>
+ <exclusion>
+ <groupId>javax.ws.rs</groupId>
+ <artifactId>jsr311-api</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>javax.ws.rs</groupId>
+ <artifactId>javax.ws.rs-api</artifactId>
+ <version>2.0.1</version>
+ <scope>provided</scope>
+ </dependency>
+ <dependency>
+ <groupId>com.google.guava</groupId>
+ <artifactId>guava</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>de.svenkubiak</groupId>
+ <artifactId>jBCrypt</artifactId>
+ <version>0.4.1</version>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-handler</artifactId>
+ <version>4.1.33.Final</version>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-buffer</artifactId>
+ <version>4.1.33.Final</version>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-codec</artifactId>
+ <version>4.1.33.Final</version>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-common</artifactId>
+ <version>4.1.33.Final</version>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-resolver</artifactId>
+ <version>4.1.33.Final</version>
+ </dependency>
+ <dependency>
+ <groupId>io.netty</groupId>
+ <artifactId>netty-transport</artifactId>
+ <version>4.1.33.Final</version>
+ </dependency>
+ <dependency>
+ <groupId>org.onap.aaf.authz</groupId>
+ <artifactId>aaf-cadi-aaf</artifactId>
+ <version>2.1.7</version>
+ <exclusions>
+ <exclusion>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.onap.aaf.authz</groupId>
+ <artifactId>aaf-cadi-client</artifactId>
+ <version>2.1.7</version>
+ <exclusions>
+ <exclusion>
+ <groupId>javax.servlet</groupId>
+ <artifactId>javax.servlet-api</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.onap.aaf.authz</groupId>
+ <artifactId>aaf-cadi-core</artifactId>
+ <version>2.1.7</version>
+ <exclusions>
+ <exclusion>
+ <groupId>log4j</groupId>
+ <artifactId>log4j</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>com.google.code.gson</groupId>
+ <artifactId>gson</artifactId>
+ <version>2.8.5</version>
+ </dependency>
+ </dependencies>
+
+ <reporting>
+ <plugins>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-javadoc-plugin</artifactId>
+ <version>2.10.3</version>
+ <configuration>
+ <author>true</author>
+ <breakiterator>true</breakiterator>
+ <version>true</version>
+ <links>
+ <link>https://docs.oracle.com/javase/7/docs/api/</link>
+ <link>https://tomcat.apache.org/tomcat-7.0-doc/jspapi/</link>
+ <link>http://docs.oracle.com/javaee/7/api/</link>
+ </links>
+ </configuration>
+ </plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.8</source>
+ <target>1.8</target>
+ </configuration>
+ </plugin>
+ </plugins>
+ </reporting>
+
+ <distributionManagement>
+ <repository>
+ <id>ecomp-releases</id>
+ <name>Release Repository</name>
+ <url>${nexusproxy}/${releaseNexusPath}</url>
+ </repository>
+ <snapshotRepository>
+ <id>ecomp-snapshots</id>
+ <name>Snapshot Repository</name>
+ <url>${nexusproxy}/${snapshotNexusPath}</url>
+ </snapshotRepository>
+ <!-- added for javadoc -->
+ <site>
+ <id>ecomp-site</id>
+ <url>dav:${nexusproxy}${sitePath}</url>
+ </site>
+ </distributionManagement>
+</project>
diff --git a/src/main/java/LICENSE.txt b/music-core/src/main/java/LICENSE.txt
index cc6cdea5..cc6cdea5 100644
--- a/src/main/java/LICENSE.txt
+++ b/music-core/src/main/java/LICENSE.txt
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..c17d9c07
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/datastore/Condition.java
@@ -0,0 +1,63 @@
+/*
+ * ============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.exceptions.MusicServiceException;
+import org.onap.music.main.MusicCore;
+
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+
+public class Condition {
+ private Map<String, Object> conditions;
+ private PreparedQueryObject selectQueryForTheRow;
+
+ public Condition(Map<String, Object> conditions, PreparedQueryObject selectQueryForTheRow) {
+ this.conditions = conditions;
+ this.selectQueryForTheRow = selectQueryForTheRow;
+ }
+
+ public boolean testCondition() throws Exception {
+ // first generate the row
+ ResultSet results = quorumGet(selectQueryForTheRow);
+ Row row = null;
+ if(results != null) {
+ row = results.one();
+ }
+ if(row == null) {
+ throw new Exception(" No data found to update");
+ }
+ return getDSHandle().doesRowSatisfyCondition(row, conditions);
+ }
+
+ /* For JUnit testing only */
+ public ResultSet quorumGet(PreparedQueryObject selectQueryForTheRow) {
+ return MusicCore.quorumGet(selectQueryForTheRow);
+ }
+
+ /* For JUnit testing only */
+ public MusicDataStore getDSHandle() throws MusicServiceException {
+ return MusicDataStoreHandle.getDSHandle();
+ }
+ } \ 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..9ce73cc8
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/datastore/MusicDataStore.java
@@ -0,0 +1,540 @@
+/*
+ * ============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.nio.ByteBuffer;
+import java.util.HashMap;
+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.SocketOptions;
+import com.datastax.driver.core.TableMetadata;
+import com.datastax.driver.core.exceptions.AlreadyExistsException;
+import com.datastax.driver.core.exceptions.InvalidQueryException;
+import com.datastax.driver.extras.codecs.enums.EnumNameCodec;
+
+/**
+ * @author nelson24
+ *
+ */
+public class MusicDataStore {
+
+ public static final String CONSISTENCY_LEVEL_ONE = "ONE";
+ public static final String CONSISTENCY_LEVEL_QUORUM = "QUORUM";
+ public static final String CONSISTENCY_LEVEL_LOCAL_QUORUM = "LOCAL_QUORUM";
+ private Session session;
+ private Cluster cluster;
+
+
+ /**
+ * 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;
+ setCluster(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) {
+ EnumNameCodec<LockType> lockTypeCodec = new EnumNameCodec<LockType>(LockType.class);
+ cluster.getConfiguration().getCodecRegistry().register(lockTypeCodec);
+
+ this.cluster = cluster;
+ }
+
+ public Cluster getCluster() {
+ return this.cluster;
+ }
+
+
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStore.class);
+
+
+ /**
+ *
+ * @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);
+
+ Cluster cluster;
+ if(MusicUtil.getCassName() != null && MusicUtil.getCassPwd() != null) {
+ String cassPwd;
+ if (MusicUtil.getCipherEncKey() != null && !("").equals(MusicUtil.getCipherEncKey())) {
+ cassPwd = CipherUtil.decryptPKC(MusicUtil.getCassPwd());
+ } else {
+ cassPwd = 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)
+ .withSocketOptions(
+ new SocketOptions().setConnectTimeoutMillis(MusicUtil.getCassandraConnectTimeOutMS())
+ .setReadTimeoutMillis(MusicUtil.getCassandraReadTimeOutMS()))
+ .addContactPoints(addresses).build();
+ } else {
+ cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort())
+ .withoutJMXReporting()
+ .withPoolingOptions(poolingOptions)
+ .withSocketOptions(new SocketOptions()
+ .setConnectTimeoutMillis(MusicUtil.getCassandraConnectTimeOutMS())
+ .setReadTimeoutMillis(MusicUtil.getCassandraReadTimeOutMS()))
+ .addContactPoints(addresses)
+ .build();
+ }
+
+ this.setCluster(cluster);
+ Metadata metadata = this.cluster.getMetadata();
+ logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster "
+ + metadata.getClusterName() + " at " + address);
+
+ try {
+ session = this.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<String, Object> condition) throws Exception {
+ ColumnDefinitions colInfo = row.getColumnDefinitions();
+
+ for (Map.Entry<String, Object> 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<String, HashMap<String, Object>> marshalData(ResultSet results) {
+ Map<String, HashMap<String, Object>> resultMap =
+ new HashMap<>();
+ int counter = 0;
+ for (Row row : results) {
+ ColumnDefinitions colInfo = row.getColumnDefinitions();
+ HashMap<String, Object> 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) {
+ throw new MusicServiceException("Already Exists Exception: " + ae.getMessage());
+ } catch (InvalidQueryException e) {
+ if (e.getMessage().contains("unconfigured table")) {
+ throw new MusicServiceException("Invalid Query Exception: " + e.getMessage());
+ } else {
+ logger.info(EELFLoggerDelegate.applicationLogger, "Query Exception: " + e.getMessage(),
+ AppMessages.SESSIONFAILED + " [" + queryObject.getQuery() + "]", ErrorSeverity.INFO,
+ ErrorTypes.QUERYERROR, e);
+ throw new MusicServiceException("Query Exception: " + e.getMessage());
+ }
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),
+ AppMessages.SESSIONFAILED + " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR,
+ ErrorTypes.QUERYERROR, e);
+ throw new MusicServiceException("Executing Session Failure for Request = " + "[" + queryObject.getQuery()
+ + "]" + " Reason = " + e.getMessage());
+ }
+
+ 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<String, PreparedStatement> 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)) {
+ statement.setConsistencyLevel(ConsistencyLevel.ONE);
+ } else if (consistencyLevel.equalsIgnoreCase(CONSISTENCY_LEVEL_QUORUM)) {
+ statement.setConsistencyLevel(ConsistencyLevel.QUORUM);
+ } else if (consistencyLevel.equalsIgnoreCase(CONSISTENCY_LEVEL_LOCAL_QUORUM)) {
+ statement.setConsistencyLevel(ConsistencyLevel.LOCAL_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 LOCAL_QUORUM.
+ *
+ * @param queryObject Object containing cassandra prepared query and values.
+ */
+ public ResultSet executeLocalQuorumConsistencyGet(PreparedQueryObject queryObject)
+ throws MusicServiceException, MusicQueryException {
+ return executeGet(queryObject, CONSISTENCY_LEVEL_LOCAL_QUORUM);
+ }
+
+ /**
+ *
+ * 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..09fe0d35
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/datastore/MusicDataStoreHandle.java
@@ -0,0 +1,127 @@
+/*
+ * ============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;
+ }
+
+ public static void setMDstoreHandle(MusicDataStore dsHandle) {
+ mDstoreHandle = dsHandle;
+ }
+
+ /**
+ *
+ * @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<String, HashMap<String, Object>> 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<Object> 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")<firstOpChar) {
+ firstOp = "insert";
+ firstOpChar = queryStr.indexOf("insert");
+ }
+ if (queryStr.indexOf("update")>-1 && queryStr.indexOf("update")<firstOpChar) {
+ firstOp = "update";
+ firstOpChar = queryStr.indexOf("update");
+ }
+ if (queryStr.indexOf("delete")>-1 && queryStr.indexOf("delete")<firstOpChar) {
+ firstOp = "delete";
+ firstOpChar = queryStr.indexOf("delete");
+ }
+ if (queryStr.indexOf("select")>-1 && queryStr.indexOf("select")<firstOpChar) {
+ firstOp = "select";
+ firstOpChar = queryStr.indexOf("select");
+ }
+ return firstOp;
+ }
+
+ public void setOperation(String operation) {
+ this.operation = operation;
+ }
+
+ public String getPrimaryKeyValue() {
+ return primaryKeyValue;
+ }
+
+ public void setPrimaryKeyValue(String primaryKeyValue) {
+ this.primaryKeyValue = primaryKeyValue;
+ }
+
+ public String getConsistency() {
+ return consistency;
+ }
+
+ public void setConsistency(String consistency) {
+ this.consistency = consistency;
+ }
+
+ /**
+ * @return values to be set as part of the prepared query
+ */
+ public List<Object> 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/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java
index 8de0a2cd..a1524cc6 100644
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java
+++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JSONObject.java
@@ -5,7 +5,7 @@ package org.onap.music.datastore.jsonobjects;
* ===================================================================
* Copyright (c) 2017 AT&T Intellectual Property
* ===================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
+ * Licensed under the Apache License, Version 2.0 (the "License")
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
@@ -24,14 +24,14 @@ package org.onap.music.datastore.jsonobjects;
public class JSONObject {
- private String data;
+ private String data;
- public String getData() {
- return data;
- }
-
- public void setData(String data) {
- this.data = 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<String> columns = null;
+ private Map<String, String> consistencyInfo;
+ private Map<String, Object> conditions;
+ private String ttl;
+ private String timestamp;
+ private String keyspaceName;
+ private String tableName;
+ private StringBuilder rowIdString;
+ private String primarKeyValue;
+
+
+ @ApiModelProperty(value = "Conditions")
+ public Map<String, Object> getConditions() {
+ return conditions;
+ }
+
+ public void setConditions(Map<String, Object> conditions) {
+ this.conditions = conditions;
+ }
+
+ @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic")
+ public Map<String, String> getConsistencyInfo() {
+ return consistencyInfo;
+ }
+
+ public void setConsistencyInfo(Map<String, String> consistencyInfo) {
+ this.consistencyInfo = consistencyInfo;
+ }
+
+ @ApiModelProperty(value = "Column values")
+ public List<String> getColumns() {
+ return columns;
+ }
+
+ public void setColumns(List<String> 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<String, String> 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<String> 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<String, String> 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<String, List<String>> entry : rowParams.entrySet()) {
+ String keyName = entry.getKey();
+ List<String> 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..2f685cfe
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java
@@ -0,0 +1,415 @@
+/*
+ * ============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<String, Object> values;
+ private String ttl;
+ private String timestamp;
+ private transient Map<String, Object> rowSpecification;
+ private Map<String, String> consistencyInfo;
+ private Map<String, byte[]> objectMap;
+ private String primaryKeyVal;
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonInsert.class);
+
+ @ApiModelProperty(value = "objectMap",hidden = true)
+ public Map<String, byte[]> getObjectMap() {
+ return objectMap;
+ }
+
+ public void setObjectMap(Map<String, byte[]> 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<String, String> getConsistencyInfo() {
+ return consistencyInfo;
+ }
+
+ public void setConsistencyInfo(Map<String, String> 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<String, Object> getValues() {
+ return values;
+ }
+
+ public void setValues(Map<String, Object> values) {
+ this.values = values;
+ }
+
+ @ApiModelProperty(value = "Information for selecting specific rows for insert",hidden = true)
+ public Map<String, Object> getRowSpecification() {
+ return rowSpecification;
+ }
+
+ public void setRowSpecification(Map<String, Object> 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 {
+ 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<String, Object> 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<String, Object> 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<String, byte[]> objectMap = this.getObjectMap();
+ if(objectMap != null) {
+ for (Map.Entry<String, byte[]> 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<String, String> 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<String, String> 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<String, List<String>> entry : rowParams.entrySet()) {
+ String keyName = entry.getKey();
+ List<String> 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<String, Object> replicationInfo;
+ private String durabilityOfWrites;
+ private Map<String, String> consistencyInfo;
+
+ @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic")
+ public Map<String, String> getConsistencyInfo() {
+ return consistencyInfo;
+ }
+
+ public void setConsistencyInfo(Map<String, String> consistencyInfo) {
+ this.consistencyInfo = consistencyInfo;
+ }
+
+ @ApiModelProperty(value = "Replication information")
+ public Map<String, Object> getReplicationInfo() {
+ return replicationInfo;
+ }
+
+ public void setReplicationInfo(Map<String, Object> 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<String, Object> 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/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java
index 497e17d1..86bbe3dc 100644
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java
+++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonLeasedLock.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.datastore.jsonobjects;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@@ -26,11 +27,10 @@ import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
-@ApiModel(value = "JsonTable", description = "model for leased lock")
+@ApiModel(value = "Json Leasesd Lock", description = "model for leased lock")
@JsonIgnoreProperties(ignoreUnknown = true)
public class JsonLeasedLock {
- long leasePeriod;
- String notifyUrl;
+ private long leasePeriod;
@ApiModelProperty(value = "Lease period")
public long getLeasePeriod() {
@@ -41,12 +41,4 @@ public class JsonLeasedLock {
this.leasePeriod = leasePeriod;
}
- @ApiModelProperty(value = "URL to be notified")
- public String getNotifyUrl() {
- return notifyUrl;
- }
-
- public void setNotifyUrl(String notifyUrl) {
- this.notifyUrl = notifyUrl;
- }
}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/AAFResponse.java b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonLock.java
index df6089ee..f353c018 100644
--- a/src/main/java/org/onap/music/datastore/jsonobjects/AAFResponse.java
+++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonLock.java
@@ -19,24 +19,31 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.datastore.jsonobjects;
-import java.util.ArrayList;
+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 = "JsonTable", description = "Reponse class for AAF request")
-public class AAFResponse {
+@ApiModel(value = "Json Lock Type", description = "Model for Lock Type")
+@JsonIgnoreProperties(ignoreUnknown = true)
+public class JsonLock {
+ private LockType locktype;
- private ArrayList<NameSpace> ns = null;
-
- @ApiModelProperty(value = "Namespace value")
- public ArrayList<NameSpace> getNs() {
- return ns;
+ @ApiModelProperty(
+ value = "Type of music lock",
+ name = "lockType",
+ allowEmptyValue = false,
+ allowableValues = "READ|WRITE")
+ public LockType getLocktype() {
+ return this.locktype;
}
- public void setNs(ArrayList<NameSpace> ns) {
- this.ns = ns;
+ 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<String, String> consistencyInfo;
+ private String keyspaceName;
+ private String tableName;
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonSelect.class);
+
+
+
+ public Map<String, String> getConsistencyInfo() {
+ return consistencyInfo;
+ }
+
+ public void setConsistencyInfo(Map<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, List<String>> entry : rowParams.entrySet()) {
+ String keyName = entry.getKey();
+ List<String> 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..0ba1a7ef
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java
@@ -0,0 +1,363 @@
+/*
+ * ============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<String, String> fields;
+ private Map<String, Object> properties;
+ private String primaryKey;
+ private String partitionKey;
+ private String clusteringKey;
+ private String filteringKey;
+ private String clusteringOrder;
+ private Map<String, String> consistencyInfo;
+
+ @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic")
+ public Map<String, String> getConsistencyInfo() {
+ return consistencyInfo;
+ }
+
+ public void setConsistencyInfo(Map<String, String> consistencyInfo) {
+ this.consistencyInfo = consistencyInfo;
+ }
+
+ @ApiModelProperty(value = "Properties")
+ public Map<String, Object> getProperties() {
+ return properties;
+ }
+
+ public void setProperties(Map<String, Object> properties) {
+ this.properties = properties;
+ }
+
+ @ApiModelProperty(value = "Fields")
+ public Map<String, String> getFields() {
+ return fields;
+ }
+
+ public void setFields(Map<String, String> 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 {
+ 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<String, String> 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<String, String> 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<String, Object> propertiesMap = this.getProperties();
+ StringBuilder propertiesString = new StringBuilder();
+ if (propertiesMap != null) {
+ counter = 0;
+ for (Map.Entry<String, Object> entry : propertiesMap.entrySet()) {
+ Object ot = entry.getValue();
+ String value = ot + "";
+ if (ot instanceof String) {
+ value = "'" + value + "'";
+ } else if (ot instanceof Map) {
+ @SuppressWarnings("unchecked")
+ Map<String, Object> otMap = (Map<String, Object>) 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;
+ }
+
+ /**
+ * genDropTableQuery
+ *
+ * @return PreparedQueryObject
+ */
+ public PreparedQueryObject genDropTableQuery() {
+ 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..29fdb1d4
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java
@@ -0,0 +1,436 @@
+/*
+ * ============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<String, Object> values;
+ private String ttl;
+ private String timestamp;
+ private Map<String, String> consistencyInfo;
+ private transient Map<String, Object> conditions;
+ private transient Map<String, Object> rowSpecification;
+ private String rowIdString;
+ private String primarKeyValue;
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(JsonUpdate.class);
+
+ @ApiModelProperty(value = "Conditions")
+ public Map<String, Object> getConditions() {
+ return conditions;
+ }
+
+ public void setConditions(Map<String, Object> conditions) {
+ this.conditions = conditions;
+ }
+
+ @ApiModelProperty(value = "Information for selecting sepcific rows")
+ public Map<String, Object> getRow_specification() {
+ return rowSpecification;
+ }
+
+ public void setRow_specification(Map<String, Object> 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<String, String> getConsistencyInfo() {
+ return consistencyInfo;
+ }
+
+ public void setConsistencyInfo(Map<String, String> 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<String, Object> getValues() {
+ return values;
+ }
+
+ public void setValues(Map<String, Object> values) {
+ this.values = values;
+ }
+
+ public String getRowIdString() {
+ return rowIdString;
+ }
+
+ public void setRowIdString(String 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<String, String> rowParams) throws MusicQueryException {
+ 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()+" ) ");
+ 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<String, Object> valuesMap = this.getValues();
+
+ TableMetadata tableInfo = getColumnMetadata(this.getKeyspaceName(), this.getTableName());
+
+ 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<String, Object> 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.getPrimaryKeyValue().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.getRowIdString() + ";");
+
+
+
+ // 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.getRowIdString() + ";");
+ selectQuery.addValue(rowId.primarKeyValue);
+ conditionInfo = new Condition(this.getConditions(), selectQuery);
+ }
+
+ 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;
+ }
+
+ TableMetadata getColumnMetadata(String keyspaceName, String tableName) throws MusicQueryException {
+ TableMetadata tableInfo;
+ try {
+ tableInfo = returnColumnMetadata(keyspaceName, tableName);
+ } 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());
+ }
+ return tableInfo;
+ }
+
+ /** wrapper around static method for testing */
+ TableMetadata returnColumnMetadata(String keyspace, String tableName) throws MusicServiceException {
+ return MusicDataStoreHandle.returnColumnMetadata(keyspace, tableName);
+ }
+
+ class RowIdentifier {
+ private String primarKeyValue;
+ private String rowIdString;
+ @SuppressWarnings("unused")
+ public PreparedQueryObject queryObject; // the string with all the row
+ // identifiers separated by AND
+
+ public RowIdentifier(String primaryKeyValue, String rowIdString,
+ PreparedQueryObject queryObject) {
+ this.primarKeyValue = primaryKeyValue;
+ this.rowIdString = rowIdString;
+ this.queryObject = queryObject;
+ }
+
+ public String getPrimaryKeyValue() {
+ return this.primarKeyValue;
+ }
+
+ public void setPrimaryKeyValue(String primaryKeyValue) {
+ this.primarKeyValue = primaryKeyValue;
+ }
+
+ public String getRowIdString() {
+ return this.rowIdString;
+ }
+
+ public void setRowIdString(String rowIdString) {
+ this.rowIdString = rowIdString;
+ }
+
+ public PreparedQueryObject getQueryObject() {
+ return this.queryObject;
+ }
+ }
+
+ /**
+ *
+ * @param keyspace
+ * @param tablename
+ * @param rowParams
+ * @param queryObject
+ * @return
+ * @throws MusicServiceException
+ */
+ RowIdentifier getRowIdentifier(String keyspace, String tablename,
+ MultivaluedMap<String, String> rowParams, PreparedQueryObject queryObject)
+ throws MusicServiceException {
+ StringBuilder rowSpec = new StringBuilder();
+ int counter = 0;
+ TableMetadata tableInfo = 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<String, List<String>> entry : rowParams.entrySet()) {
+ String keyName = entry.getKey();
+ List<String> 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.toString(), 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/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java b/music-core/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java
index 0c290b6f..a8012c82 100644
--- a/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java
+++ b/music-core/src/main/java/org/onap/music/eelf/logging/EELFLoggerDelegate.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.eelf.logging;
import static com.att.eelf.configuration.Configuration.MDC_SERVER_FQDN;
@@ -43,6 +44,7 @@ public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger {
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<String, EELFLoggerDelegate> classMap = new ConcurrentHashMap<>();
@@ -228,10 +230,21 @@ public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger {
*
* @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.
@@ -239,9 +252,21 @@ public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger {
* @param logger
* @param msg
* @param arguments
+ *
*/
public void error(EELFLogger logger, String msg, Object... arguments) {
- logger.warn(msg, 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);
}
/**
@@ -252,7 +277,7 @@ public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger {
* @param th
*/
public void error(EELFLogger logger, String msg, Throwable th) {
- logger.warn(msg, th);
+ logger.error(msg, th);
}
/**
@@ -279,6 +304,8 @@ public class EELFLoggerDelegate extends SLF4jWrapper implements EELFLogger {
debug(debugLogger, msg);
info(auditLogger, msg);
info(metricsLogger, msg);
+ info(securityLogger, msg);
+
}
/**
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/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
index cda5dd31..4e798239 100644
--- a/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
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.eelf.logging.format;
/**
diff --git a/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
index 2536f4a4..9bdbf20f 100644
--- a/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
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.eelf.logging.format;
import com.att.eelf.i18n.EELFResolvableErrorEnum;
@@ -28,17 +29,18 @@ import com.att.eelf.i18n.EELFResolvableErrorEnum;
*
*/
public enum ErrorTypes implements EELFResolvableErrorEnum {
-
-
- CONNECTIONERROR,
- SESSIONEXPIRED,
- AUTHENTICATIONERROR,
- SERVICEUNAVAILABLE,
- QUERYERROR,
- DATAERROR,
- GENERALSERVICEERROR,
- MUSICSERVICEERROR,
- LOCKINGERROR,
- UNKNOWN,
-
+
+
+ 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..7a40ed91
--- /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 {
+
+ private String owner = null;
+ private String keyspace = null;
+ private String table = null;
+ private 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/MusicLockingException.java b/music-core/src/main/java/org/onap/music/exceptions/MusicLockingException.java
index 1a9e45d9..ab70c54c 100644
--- a/src/main/java/org/onap/music/exceptions/MusicLockingException.java
+++ b/music-core/src/main/java/org/onap/music/exceptions/MusicLockingException.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.exceptions;
/**
diff --git a/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java b/music-core/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java
index bade21a4..f489cd45 100644
--- a/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java
+++ b/music-core/src/main/java/org/onap/music/exceptions/MusicPolicyVoilationException.java
@@ -2,7 +2,9 @@
* ============LICENSE_START==========================================
* org.onap.music
* ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
+ * 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.
@@ -19,6 +21,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.exceptions;
/**
@@ -36,7 +39,7 @@ public class MusicPolicyVoilationException extends Exception {
*
*/
public MusicPolicyVoilationException() {
- // TODO Auto-generated constructor stub
+
}
/**
@@ -44,7 +47,7 @@ public class MusicPolicyVoilationException extends Exception {
*/
public MusicPolicyVoilationException(String message) {
super(message);
- // TODO Auto-generated constructor stub
+
}
/**
@@ -52,7 +55,7 @@ public class MusicPolicyVoilationException extends Exception {
*/
public MusicPolicyVoilationException(Throwable cause) {
super(cause);
- // TODO Auto-generated constructor stub
+
}
/**
@@ -61,7 +64,7 @@ public class MusicPolicyVoilationException extends Exception {
*/
public MusicPolicyVoilationException(String message, Throwable cause) {
super(message, cause);
- // TODO Auto-generated constructor stub
+
}
/**
@@ -73,7 +76,7 @@ public class MusicPolicyVoilationException extends Exception {
public MusicPolicyVoilationException(String message, Throwable cause, boolean enableSuppression,
boolean writableStackTrace) {
super(message, cause, enableSuppression, writableStackTrace);
- // TODO Auto-generated constructor stub
+
}
}
diff --git a/src/main/java/org/onap/music/exceptions/MusicQueryException.java b/music-core/src/main/java/org/onap/music/exceptions/MusicQueryException.java
index 24b8568b..803f993f 100644
--- a/src/main/java/org/onap/music/exceptions/MusicQueryException.java
+++ b/music-core/src/main/java/org/onap/music/exceptions/MusicQueryException.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.exceptions;
diff --git a/src/main/java/org/onap/music/exceptions/MusicServiceException.java b/music-core/src/main/java/org/onap/music/exceptions/MusicServiceException.java
index a3b1fc56..76e1f948 100644
--- a/src/main/java/org/onap/music/exceptions/MusicServiceException.java
+++ b/music-core/src/main/java/org/onap/music/exceptions/MusicServiceException.java
@@ -4,6 +4,8 @@
* ===================================================================
* 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
@@ -32,26 +34,6 @@ public class MusicServiceException extends Exception {
private int errorCode;
private String errorMessage;
- public int getErrorCode() {
- return errorCode;
- }
-
-
- public void setErrorCode(int errorCode) {
- this.errorCode = errorCode;
- }
-
-
- public String getErrorMessage() {
- return errorMessage;
- }
-
-
- public void setErrorMessage(String errorMessage) {
- this.errorMessage = errorMessage;
- }
-
-
public MusicServiceException() {
super();
}
@@ -61,8 +43,18 @@ public class MusicServiceException extends Exception {
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);
@@ -76,9 +68,21 @@ public class MusicServiceException extends Exception {
public MusicServiceException(String message, Throwable cause, boolean enableSuppression,
- boolean writableStackTrace) {
+ 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..9a69a9ba
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/lockingservice/cassandra/CassaLockStore.java
@@ -0,0 +1,613 @@
+/*
+ * ============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;
+
+/*
+ * 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);
+ public static final 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, leasePeriodTime bigint, 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<Row> 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<String> 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<String> 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<String> 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<String> 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 = getDeadlockDetectionUtil();
+
+ ResultSet rs = dsHandle.executeLocalQuorumConsistencyGet(queryObject);
+ logger.debug("rs has " + rs.getAvailableWithoutFetching() + (rs.isFullyFetched()?"":" (or more!)") );
+ Iterator<Row> 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;
+ }
+
+ /**
+ * This is used for testing purpose
+ * @return new DeadlockDetectionUtil object
+ */
+ DeadlockDetectionUtil getDeadlockDetectionUtil() {
+ return new DeadlockDetectionUtil();
+ }
+
+ public List<String> getAllLocksForOwner(String ownerId, String keyspace, String table) throws MusicServiceException, MusicQueryException {
+ List<String> 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<Row> 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 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<ref) {
+ return new ReturnType(ResultType.FAILURE, "Lockref does not exist.");
+ }
+
+ if (lockType==LockType.READ || lockType==LockType.PROMOTING) {
+ if (!readBlock) {
+ readBlockStart = ref;
+ readBlock = true;
+ }
+ if (readBlock) {
+ readBlockEnd = ref;
+ }
+ if (lockType==LockType.PROMOTING) {
+ promotionOngoing = true;
+ }
+ }
+
+ if (lockType==LockType.WRITE) {
+ if (refToPromote==ref) {
+ return new ReturnType(ResultType.FAILURE, "Lockref is already write.");
+ }
+ if (readBlock) {
+ readBlock = false;
+ promotionOngoing = false;
+ if (seenLockToPromote) {
+ break;
+ }
+ //can no longer be lock holder after this
+ topOfQueue = false;
+ }
+ }
+ }
+
+ if (readBlockStart<=refToPromote && refToPromote<=readBlockEnd) {
+ if (readBlockStart==refToPromote && refToPromote==readBlockEnd) {
+ promoteLockTo(keyspace, lockqtable, key, lockRef, LockType.WRITE);
+ return new ReturnType(ResultType.SUCCESS, "Lock has successfully been upgraded.");
+ }
+ promoteLockTo(keyspace, lockqtable, key, lockRef, LockType.PROMOTING);
+ return new ReturnType(ResultType.FAILURE, "Your lock upgrade is in progress. Check again to see if successful.");
+ }
+
+ //shouldn't reach here?
+ return new ReturnType(ResultType.FAILURE,"Promotion failed.");
+ }
+
+ private void promoteLockTo(String keyspace, String table, String key, String lockRef, LockType newLockType)
+ throws MusicServiceException, MusicQueryException {
+ PreparedQueryObject queryObject =
+ new PreparedQueryObject("UPDATE " + keyspace + "." + table + " SET lockType=? WHERE key='" + key
+ + "' AND lockReference = " + lockRef + " IF EXISTS;", newLockType);
+
+ //cannot use executePut because we need to ignore music timestamp adjustments for lock store
+ dsHandle.executePut(queryObject, MusicUtil.QUORUM);
+ }
+
+
+
+}
diff --git a/music-core/src/main/java/org/onap/music/lockingservice/cassandra/LockCleanUpDaemon.java b/music-core/src/main/java/org/onap/music/lockingservice/cassandra/LockCleanUpDaemon.java
new file mode 100644
index 00000000..623a07c7
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/lockingservice/cassandra/LockCleanUpDaemon.java
@@ -0,0 +1,133 @@
+/*
+ * ============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.lockingservice.cassandra;
+
+import java.util.HashSet;
+import java.util.Set;
+import org.onap.music.datastore.MusicDataStoreHandle;
+import org.onap.music.datastore.PreparedQueryObject;
+import org.onap.music.eelf.logging.EELFLoggerDelegate;
+import org.onap.music.exceptions.MusicServiceException;
+import org.onap.music.main.MusicCore;
+import org.onap.music.main.MusicUtil;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+
+public class LockCleanUpDaemon extends Thread {
+
+ boolean terminated = false;
+ private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(LockCleanUpDaemon.class);
+
+
+ public LockCleanUpDaemon() {
+ }
+
+ @Override
+ public void run() {
+ if (MusicUtil.getLockDaemonSleepTimeMs()<0) {
+ terminate();
+ }
+ while (!terminated) {
+ try {
+ cleanupStaleLocks();
+ } catch (MusicServiceException e) {
+ logger.warn(EELFLoggerDelegate.applicationLogger, "Unable to clean up locks", e);
+ }
+ try {
+ Thread.sleep(MusicUtil.getLockDaemonSleepTimeMs());
+ } catch (InterruptedException e) {
+ logger.warn(EELFLoggerDelegate.applicationLogger, "Interrupted exception", e);
+
+ }
+ }
+ }
+
+ private void cleanupStaleLocks() throws MusicServiceException {
+ Set<String> lockQTables = getLockQTables();
+ logger.info(EELFLoggerDelegate.applicationLogger, "Lock q tables found: " + lockQTables);
+ for(String lockTable: lockQTables) {
+ try {
+ cleanUpLocksFromTable(lockTable);
+ } catch (MusicServiceException e) {
+ logger.warn(EELFLoggerDelegate.applicationLogger, "Unable to clear locks on table " + lockTable, e);
+ }
+ }
+ }
+
+
+ private Set<String> getLockQTables() throws MusicServiceException {
+ Set<String> keyspacesToCleanUp = MusicUtil.getKeyspacesToCleanLocks();
+ Set<String> lockQTables = new HashSet<>();
+
+ PreparedQueryObject query = new PreparedQueryObject();
+ query.appendQueryString("SELECT keyspace_name, table_name FROM system_schema.tables;");
+ ResultSet results = MusicCore.get(query);
+
+ for (Row row: results) {
+ if (keyspacesToCleanUp.contains(row.getString("keyspace_name"))
+ && row.getString("table_name").toLowerCase().startsWith(CassaLockStore.table_prepend_name.toLowerCase()) ) {
+ lockQTables.add(row.getString("keyspace_name") + "." + row.getString("table_name"));
+ }
+ }
+ return lockQTables;
+ }
+
+ private void cleanUpLocksFromTable(String lockTable) throws MusicServiceException {
+ PreparedQueryObject query = new PreparedQueryObject();
+ query.appendQueryString("SELECT * from " + lockTable);
+ ResultSet results = MusicCore.get(query);
+ for (Row lock: results) {
+ if (!lock.isNull("lockreference")) {
+ try {
+ deleteLockIfStale(lockTable, lock);
+ } catch (MusicServiceException e) {
+ logger.warn(EELFLoggerDelegate.applicationLogger, "Unable to delete a potentially stale lock " + lock, e);
+ }
+ }
+ }
+ }
+
+
+ private void deleteLockIfStale(String lockTable, Row lock) throws MusicServiceException {
+ final String CREATETIME="createtime";
+ final String ACQUIRETIME="acquiretime";
+ if (lock.isNull(CREATETIME) && lock.isNull("acquiretime")) {
+ return;
+ }
+
+ long createTime = lock.isNull(CREATETIME) ? 0 : Long.parseLong(lock.getString(CREATETIME));
+ long acquireTime = lock.isNull(ACQUIRETIME) ? 0 : Long.parseLong(lock.getString(ACQUIRETIME));
+ long row_access_time = Math.max(createTime, acquireTime);
+ if (System.currentTimeMillis() > row_access_time + MusicUtil.getDefaultLockLeasePeriod()) {
+ logger.info(EELFLoggerDelegate.applicationLogger, "Stale lock detected and being removed: " + lock);
+ PreparedQueryObject query = new PreparedQueryObject();
+ query.appendQueryString("DELETE FROM " + lockTable + " WHERE key='" + lock.getString("key") + "' AND " +
+ "lockreference=" + lock.getLong("lockreference") + " IF EXISTS;");
+ MusicDataStoreHandle.getDSHandle().getSession().execute(query.getQuery());
+ }
+ }
+
+ public void terminate() {
+ terminated = true;
+ }
+}
diff --git a/musictrigger/src/JSONObject.java b/music-core/src/main/java/org/onap/music/lockingservice/cassandra/LockType.java
index 38dfcbdc..432b1c51 100644
--- a/musictrigger/src/JSONObject.java
+++ b/music-core/src/main/java/org/onap/music/lockingservice/cassandra/LockType.java
@@ -2,37 +2,29 @@
* ============LICENSE_START==========================================
* org.onap.music
* ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
+ * 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=============================================
* ====================================================================
*/
-public class JSONObject {
+package org.onap.music.lockingservice.cassandra;
- private String data;
- public String getData() {
- return data;
- }
-
- public void setData(String data) {
- this.data = data;
- }
-
-
-
+public enum LockType {
+ WRITE, READ, PROMOTING;
}
+
diff --git a/src/main/java/org/onap/music/lockingservice/MusicLockState.java b/music-core/src/main/java/org/onap/music/lockingservice/cassandra/MusicLockState.java
index 04a1e6b2..14fb8135 100644
--- a/src/main/java/org/onap/music/lockingservice/MusicLockState.java
+++ b/music-core/src/main/java/org/onap/music/lockingservice/cassandra/MusicLockState.java
@@ -4,6 +4,8 @@
* ===================================================================
* 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
@@ -19,7 +21,8 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
-package org.onap.music.lockingservice;
+
+package org.onap.music.lockingservice.cassandra;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
@@ -34,19 +37,20 @@ import org.onap.music.eelf.logging.format.AppMessages;
import org.onap.music.eelf.logging.format.ErrorSeverity;
import org.onap.music.eelf.logging.format.ErrorTypes;
-// the state variable that will be stored in zookeeper, capturing the transitions of
+// the state variable that will be stored in the locking service, capturing the transitions of
public class MusicLockState implements Serializable {
+ // captures the state of the lock
public enum LockStatus {
UNLOCKED, BEING_LOCKED, LOCKED
- };// captures the state of the lock
+ }
+
private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicLockState.class);
- LockStatus lockStatus;
- boolean needToSyncQuorum = false;
- String lockHolder;
- long leasePeriod = Long.MAX_VALUE;
- long leaseStartTime = -1;
-
+ private LockStatus lockStatus;
+ private boolean needToSyncQuorum = false;
+ private String lockHolder;
+ private long leasePeriod = Long.MAX_VALUE;
+ private long leaseStartTime = -1;
private String errorMessage = null;
public MusicLockState(String errorMessage) {
@@ -108,8 +112,8 @@ public class MusicLockState implements Serializable {
}
public String getErrorMessage() {
- return errorMessage;
- }
+ return errorMessage;
+ }
public byte[] serialize() {
ByteArrayOutputStream bos = new ByteArrayOutputStream();
@@ -118,8 +122,8 @@ public class MusicLockState implements Serializable {
out = new ObjectOutputStream(bos);
out.writeObject(this);
} catch (IOException e) {
- logger.error("Error", e);
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.IOERROR, ErrorSeverity.ERROR,
+ ErrorTypes.CONNECTIONERROR, e);
}
return bos.toByteArray();
}
@@ -132,8 +136,8 @@ public class MusicLockState implements Serializable {
in = new ObjectInputStream(bis);
o = in.readObject();
} catch (ClassNotFoundException | IOException e) {
- logger.error("Error", e);
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.UNKNOWN);
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity
+ .ERROR, ErrorTypes.UNKNOWN, e);
}
return (MusicLockState) o;
}
diff --git a/music-core/src/main/java/org/onap/music/main/CipherUtil.java b/music-core/src/main/java/org/onap/music/main/CipherUtil.java
new file mode 100644
index 00000000..9a8ff69d
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/main/CipherUtil.java
@@ -0,0 +1,279 @@
+/*
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ * Copyright (c) 2017 AT&T Intellectual Property
+ * ===================================================================
+ * Modification 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.main;
+
+import java.io.FileNotFoundException;
+import java.io.FileReader;
+import java.io.UnsupportedEncodingException;
+import java.security.InvalidKeyException;
+import java.security.NoSuchAlgorithmException;
+import java.security.SecureRandom;
+import java.util.Scanner;
+
+import javax.crypto.BadPaddingException;
+import javax.crypto.Cipher;
+import javax.crypto.IllegalBlockSizeException;
+import javax.crypto.NoSuchPaddingException;
+import javax.crypto.spec.IvParameterSpec;
+import javax.crypto.spec.SecretKeySpec;
+
+import org.apache.commons.codec.binary.Base64;
+import org.apache.commons.lang3.ArrayUtils;
+import org.onap.music.eelf.logging.EELFLoggerDelegate;
+
+public class CipherUtil {
+
+
+ /**
+ * Default key.
+ */
+ private static String keyString = MusicUtil.getCipherEncKey();
+
+ private static final String ALGORITHM = "AES";
+ private static final String ALGORYTHM_DETAILS = ALGORITHM + "/CBC/PKCS5PADDING";
+ private static final int BLOCK_SIZE = 128;
+ @SuppressWarnings("unused")
+ private static SecretKeySpec secretKeySpec;
+ private static IvParameterSpec ivspec;
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CipherUtil.class);
+ /**
+ * @deprecated Please use {@link #encryptPKC(String)} to encrypt the text.
+ *
+ * Encrypts the text using the specified secret key.
+ *
+ * @param plainText
+ * Text to encrypt
+ * @param secretKey
+ * Key to use for encryption
+ * @return encrypted version of plain text.
+ * @
+ * if any encryption step fails
+ *
+ */
+ @Deprecated
+ public static String encrypt(String plainText, String secretKey) {
+ String encryptedString = null;
+ try {
+ byte[] encryptText = plainText.getBytes("UTF-8");
+ byte[] rawKey = Base64.decodeBase64(secretKey);
+ SecretKeySpec sKeySpec = new SecretKeySpec(rawKey, "AES");
+ Cipher cipher = Cipher.getInstance("AES");
+ cipher.init(Cipher.ENCRYPT_MODE, sKeySpec);
+ encryptedString = Base64.encodeBase64String(cipher.doFinal(encryptText));
+ } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException
+ | NoSuchPaddingException | UnsupportedEncodingException ex) {
+ }
+ return encryptedString;
+ }
+
+ /**
+ * @deprecated Please use {@link #encryptPKC(String)} to encrypt the text.
+ * Encrypts the text using the secret key in key.properties file.
+ *
+ * @param plainText
+ * Text to encrypt
+ * @return Encrypted Text
+ * @
+ * if any decryption step fails
+ */
+ @Deprecated
+ public static String encrypt(String plainText) {
+ return CipherUtil.encrypt(plainText, keyString);
+ }
+
+ /**
+ * Encrypts the text using a secret key.
+ *
+ * @param plainText
+ * Text to encrypt
+ * @return Encrypted Text
+ * @
+ * if any decryption step fails
+ */
+ public static String encryptPKC(String plainText) {
+ return CipherUtil.encryptPKC(plainText, keyString);
+ }
+
+ /**
+ *
+ * @deprecated Please use {@link #decryptPKC(String)} to Decryption the text.
+ *
+ * Decrypts the text using the specified secret key.
+ *
+ * @param encryptedText
+ * Text to decrypt
+ * @param secretKey
+ * Key to use for decryption
+ * @return plain text version of encrypted text
+ * @
+ * if any decryption step fails
+ *
+ */
+ @Deprecated
+ public static String decrypt(String encryptedText, String secretKey) {
+ String encryptedString = null;
+ try {
+ byte[] rawKey = Base64.decodeBase64(secretKey);
+ SecretKeySpec sKeySpec = new SecretKeySpec(rawKey, "AES");
+ byte[] encryptText = Base64.decodeBase64(encryptedText.getBytes("UTF-8"));
+ Cipher cipher = Cipher.getInstance("AES");
+ cipher.init(Cipher.DECRYPT_MODE, sKeySpec);
+ encryptedString = new String(cipher.doFinal(encryptText));
+ } catch (BadPaddingException | IllegalBlockSizeException | InvalidKeyException | NoSuchAlgorithmException
+ | NoSuchPaddingException | UnsupportedEncodingException ex) {
+ }
+ return encryptedString;
+ }
+
+ private static SecretKeySpec getSecretKeySpec() {
+ byte[] key = Base64.decodeBase64(keyString);
+ return new SecretKeySpec(key, ALGORITHM);
+ }
+
+ private static SecretKeySpec getSecretKeySpec(String keyString) {
+ byte[] key = Base64.decodeBase64(keyString);
+ return new SecretKeySpec(key, ALGORITHM);
+ }
+
+ /**
+ * Encrypt the text using the secret key in key.properties file
+ *
+ * @param value
+ * @return The encrypted string
+ * @throws BadPaddingException
+ * @
+ * In case of issue with the encryption
+ */
+ public static String encryptPKC(String value, String skey) {
+ Cipher cipher = null;
+ byte[] iv = null;
+ byte[] finalByte = null;
+
+ try {
+ cipher = Cipher.getInstance(ALGORYTHM_DETAILS, "SunJCE");
+
+ SecureRandom r = SecureRandom.getInstance("SHA1PRNG");
+ iv = new byte[BLOCK_SIZE / 8];
+ r.nextBytes(iv);
+ ivspec = new IvParameterSpec(iv);
+ cipher.init(Cipher.ENCRYPT_MODE, getSecretKeySpec(skey), ivspec);
+ finalByte = cipher.doFinal(value.getBytes());
+
+ } catch (Exception ex) {
+
+ }
+ return Base64.encodeBase64String(ArrayUtils.addAll(iv, finalByte));
+ }
+
+ /**
+ * Decrypts the text using the secret key in key.properties file.
+ *
+ * @param message
+ * The encrypted string that must be decrypted using the ecomp
+ * Encryption Key
+ * @return The String decrypted
+ * @
+ * if any decryption step fails
+ */
+ public static String decryptPKC(String message, String skey) {
+ byte[] encryptedMessage = Base64.decodeBase64(message);
+ Cipher cipher;
+ byte[] decrypted = null;
+ try {
+ cipher = Cipher.getInstance(ALGORYTHM_DETAILS, "SunJCE");
+ ivspec = new IvParameterSpec(ArrayUtils.subarray(encryptedMessage, 0, BLOCK_SIZE / 8));
+ byte[] realData = ArrayUtils.subarray(encryptedMessage, BLOCK_SIZE / 8, encryptedMessage.length);
+ cipher.init(Cipher.DECRYPT_MODE, getSecretKeySpec(skey), ivspec);
+ decrypted = cipher.doFinal(realData);
+
+ } catch (Exception ex) {
+ logger.error(EELFLoggerDelegate.errorLogger, "Error in decryptPKC", ex);
+
+ }
+
+ return new String(decrypted);
+ }
+
+ /**
+ * @deprecated Please use {@link #decryptPKC(String)} to Decrypt the text.
+ *
+ * Decrypts the text using the secret key in key.properties file.
+ *
+ * @param encryptedText
+ * Text to decrypt
+ * @return Decrypted text
+ * @
+ * if any decryption step fails
+ */
+ @Deprecated
+ public static String decrypt(String encryptedText) {
+ return CipherUtil.decrypt(encryptedText, keyString);
+ }
+
+ /**
+ *
+ * Decrypts the text using the secret key in key.properties file.
+ *
+ * @param encryptedText
+ * Text to decrypt
+ * @return Decrypted text
+ * @
+ * if any decryption step fails
+ */
+ public static String decryptPKC(String encryptedText) {
+ return CipherUtil.decryptPKC(encryptedText, keyString);
+ }
+
+
+ public static void readAndSetKeyString() {
+ try (Scanner in = new Scanner(new FileReader("/opt/app/music/etc/properties.txt"))) {
+
+ StringBuilder sb = new StringBuilder();
+ while(in.hasNext()) {
+ sb.append(in.next());
+ }
+ keyString = sb.toString();
+ } catch (FileNotFoundException e) {
+ logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
+ }
+ }
+
+ public static void main(String[] args) {
+
+ if (args.length < 2) {
+ System.out.println("Usage: java -jar CipherUtil <key> <password>");
+ return;
+ }
+
+ keyString = args[0];
+ String password = args[1];
+
+ String enc = encryptPKC(password);
+ System.out.println("Encrypted password: " + enc);
+
+ System.out.println("Decrypted password (to verify): " + decryptPKC(enc));
+ }
+
+}
diff --git a/music-core/src/main/java/org/onap/music/main/CorePropertiesLoader.java b/music-core/src/main/java/org/onap/music/main/CorePropertiesLoader.java
new file mode 100644
index 00000000..2e5ca689
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/main/CorePropertiesLoader.java
@@ -0,0 +1,120 @@
+/*
+ * ============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;
+
+public class CorePropertiesLoader {
+
+ 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"));
+ }
+
+ }
+
+}
diff --git a/music-core/src/main/java/org/onap/music/main/DeadlockDetectionUtil.java b/music-core/src/main/java/org/onap/music/main/DeadlockDetectionUtil.java
new file mode 100644
index 00000000..004bd550
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/main/DeadlockDetectionUtil.java
@@ -0,0 +1,152 @@
+/*
+ * ============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.main;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+public class DeadlockDetectionUtil {
+ private Map<String, Node> nodeList = null;
+ public enum OwnershipType {NONE, CREATED, ACQUIRED};
+
+ private class Node implements Comparable<Node> {
+ private String id;
+ private List<Node> 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<Node> 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);
+ }
+
+ return findCycle(currentNode);
+ }
+
+ 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..30d2bc47
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/main/MusicCore.java
@@ -0,0 +1,264 @@
+/*
+ * ============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 createLockReferenceAtomic(String fullyQualifiedKey) throws MusicLockingException {
+ return musicCore.createLockReferenceAtomic(fullyQualifiedKey);
+ }
+
+ public static String createLockReference(String fullyQualifiedKey, String owner) throws MusicLockingException {
+ return musicCore.createLockReference(fullyQualifiedKey, owner);
+ }
+
+ public static String createLockReferenceAtomic(String fullyQualifiedKey, LockType locktype) throws MusicLockingException {
+ return musicCore.createLockReferenceAtomic(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<String> 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<String> 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<String, Object> 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<String> 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<String, String> rowParams)
+ throws MusicServiceException, MusicQueryException{
+ return musicCore.select(jsonSelect, rowParams);
+ }
+
+ public static ResultSet selectCritical(JsonInsert jsonInsertObj, MultivaluedMap<String, String> 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<String, String> rowParams)
+ throws MusicLockingException, MusicQueryException, MusicServiceException{
+ return musicCore.updateTable(jsonUpdateObj, rowParams);
+ }
+
+ public static ReturnType deleteFromTable(JsonDelete jsonDeleteObj,MultivaluedMap<String, String> 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..4b8b1059
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/main/MusicUtil.java
@@ -0,0 +1,881 @@
+/*
+ * ============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.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Scanner;
+import java.util.Set;
+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 LOCAL_QUORUM = "local_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 long lockDaemonSleepms = 1000;
+ private static Set<String> keyspacesToCleanLocks = new HashSet<>();
+
+ 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<String,ConsistencyLevel> 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;
+ private static int cassandraConnectTimeOutMS;
+ private static int cassandraReadTimeOutMS;
+
+ // 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 = "";
+
+ private static long createLockWaitPeriod = 300;
+ private static int createLockWaitIncrement = 50;
+
+ public static long getCreateLockWaitPeriod() {
+ return createLockWaitPeriod;
+ }
+
+ public static void setCreateLockWaitPeriod(long createLockWaitPeriod) {
+ MusicUtil.createLockWaitPeriod = createLockWaitPeriod;
+ }
+
+ public static int getCreateLockWaitIncrement() {
+ return createLockWaitIncrement;
+ }
+
+ public static void setCreateLockWaitIncrement(int createLockWaitIncrement) {
+ MusicUtil.createLockWaitIncrement = createLockWaitIncrement;
+ }
+
+ 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;
+ }
+
+ public static int getCassandraConnectTimeOutMS() {
+ return cassandraConnectTimeOutMS;
+ }
+
+ public static void setCassandraConnectTimeOutMS(int cassandraConnectTimeOutMS) {
+ MusicUtil.cassandraConnectTimeOutMS = cassandraConnectTimeOutMS;
+ }
+
+ public static int getCassandraReadTimeOutMS() {
+ return cassandraReadTimeOutMS;
+ }
+
+ public static void setCassandraReadTimeOutMS(int cassandraReadTimeOutMS) {
+ MusicUtil.cassandraReadTimeOutMS = cassandraReadTimeOutMS;
+ }
+
+ /**
+ * 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<String, Object> otMap = (Map<String, Object>) 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<String, Object>) valueObj;
+ case LIST:
+ return valueObj;
+ case BLOB:
+
+ default:
+ return valueObjString;
+ }
+ }
+
+ public static ByteBuffer convertToActualDataType(DataType colType, byte[] valueObj) {
+
+ return ByteBuffer.wrap(valueObj);
+ }
+
+ /**
+ *
+ * Utility function to parse json map into sql like string
+ *
+ * @param jMap
+ * @param lineDelimiter
+ * @return
+ */
+
+ public static String jsonMaptoSqlString(Map<String, Object> jMap, String lineDelimiter) throws Exception{
+ StringBuilder sqlString = new StringBuilder();
+ int counter = 0;
+ for (Map.Entry<String, Object> 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
+ return ordinal * MaxLockReferenceTimePart + (timeOfWrite - MusicEternityEpochMillis);
+ }
+
+ public static MusicCoreService getMusicCoreService() {
+ if(getLockUsing().equals(MusicUtil.CASSANDRA))
+ return MusicCassaCore.getInstance();
+ else
+ return MusicCassaCore.getInstance();
+ }
+
+ /**
+ * @param lockName
+ * @return
+ */
+ public static Map<String, Object> validateLock(String lockName) {
+ Map<String, Object> 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;
+ }
+
+ /**
+ * @return the sleep time, in milliseconds, for the lock cleanup daemon
+ */
+ public static long getLockDaemonSleepTimeMs() {
+ return lockDaemonSleepms;
+ }
+
+ /**
+ * set the sleep time, in milliseconds, for the lock cleanup daemon
+ */
+ public static void setLockDaemonSleepTimeMs(long timeoutms) {
+ MusicUtil.lockDaemonSleepms = timeoutms;
+ }
+
+ public static Set<String> getKeyspacesToCleanLocks() {
+ return keyspacesToCleanLocks;
+ }
+
+ public static void setKeyspacesToCleanLocks(Set<String> keyspaces) {
+ MusicUtil.keyspacesToCleanLocks = keyspaces;
+ }
+
+ 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/ResultType.java b/music-core/src/main/java/org/onap/music/main/ResultType.java
index 61ba0295..f5ef2070 100644
--- a/src/main/java/org/onap/music/main/ResultType.java
+++ b/music-core/src/main/java/org/onap/music/main/ResultType.java
@@ -19,13 +19,14 @@
* ============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.");
-
+ SYNTAXERROR("SyntaxError"), EXCEPTION("Exception"),
+ BODYMISSING("Incomplete Request body. Please correct your input request and retry.");
+
private String result;
ResultType(String result) {
diff --git a/src/main/java/org/onap/music/main/ReturnType.java b/music-core/src/main/java/org/onap/music/main/ReturnType.java
index 1453a1bf..f02dabbf 100644
--- a/src/main/java/org/onap/music/main/ReturnType.java
+++ b/music-core/src/main/java/org/onap/music/main/ReturnType.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.main;
import java.util.HashMap;
@@ -28,6 +29,8 @@ public class ReturnType {
private ResultType result;
private String message;
+ private String timingInfo;
+
public ReturnType(ResultType result, String message) {
super();
this.result = result;
@@ -42,8 +45,6 @@ public class ReturnType {
this.timingInfo = timingInfo;
}
- private String timingInfo;
-
public ResultType getResult() {
return result;
}
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..753d9b28
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/service/MusicCoreService.java
@@ -0,0 +1,189 @@
+/*
+ * ============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 createLockReferenceAtomic(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 owner the owner of the lock, for deadlock prevention
+ */
+ public String createLockReference(String fullyQualifiedKey, String owner) 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}
+ */
+ public String createLockReferenceAtomic(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<String> 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<String> getLockQueue(String fullyQualifiedKey)
+ throws MusicServiceException, MusicQueryException, MusicLockingException;
+
+ public long getLockQueueSize(String fullyQualifiedKey)
+ throws MusicServiceException, MusicQueryException, MusicLockingException;
+
+ public Map<String, Object> validateLock(String lockName);
+
+ public MusicLockState releaseLock(String lockId, boolean voluntaryRelease) throws MusicLockingException;
+
+ public List<String> 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<String, String> rowParams) throws MusicServiceException, MusicQueryException;
+
+ public ResultSet selectCritical(JsonInsert jsonInsertObj, MultivaluedMap<String, String> rowParams)
+ throws MusicLockingException, MusicQueryException, MusicServiceException;
+
+ public ReturnType insertIntoTable(JsonInsert jsonInsert) throws MusicLockingException, MusicQueryException, MusicServiceException;
+
+ public ReturnType updateTable(JsonUpdate jsonUpdateObj,MultivaluedMap<String, String> rowParams)
+ throws MusicLockingException, MusicQueryException, MusicServiceException;
+
+ public ReturnType deleteFromTable(JsonDelete jsonDeleteObj,MultivaluedMap<String, String> 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..8055a48d
--- /dev/null
+++ b/music-core/src/main/java/org/onap/music/service/impl/MusicCassaCore.java
@@ -0,0 +1,1236 @@
+/*
+ * ============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.Collections;
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.StringTokenizer;
+import java.util.concurrent.atomic.AtomicInteger;
+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 static Set<String> set = Collections.synchronizedSet(new HashSet<String>());
+ HashMap<String, Integer> map = new HashMap<>();
+ AtomicInteger wait = new AtomicInteger(0);
+
+ private MusicCassaCore() {
+ // not going to happen
+ }
+
+ public static CassaLockStore getmLockHandle() {
+ return mLockHandle;
+ }
+
+ //for unit testing purposes
+ 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 createLockReferenceAtomic(String fullyQualifiedKey) throws MusicLockingException {
+ return createLockReferenceAtomic(fullyQualifiedKey, LockType.WRITE);
+ }
+ public String createLockReference(String fullyQualifiedKey, String owner) throws MusicLockingException {
+ return createLockReference(fullyQualifiedKey, LockType.WRITE, owner);
+ }
+
+
+ /**
+ * This will be called for Atomic calls
+ * it ensures that only one thread tries to create a lock on each key at a time
+ */
+ public String createLockReferenceAtomic(String fullyQualifiedKey, LockType locktype) throws MusicLockingException {
+ String[] splitString = fullyQualifiedKey.split("\\.");
+ if (splitString.length < 3) {
+ throw new MusicLockingException("Missing or incorrect lock details. Check table or key name.");
+ }
+ 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 = 0L;
+ long end = 0L;
+ String lockReference = null;
+ LockObject peek = null;
+
+ /** Lets check for an existing lock.
+ * This will allow us to limit the amount of requests going forward.
+ */
+ start = System.currentTimeMillis();
+ try {
+ peek = getLockingServiceHandle().peekLockQueue(keyspace, table, lockName);
+ } catch (MusicServiceException | MusicQueryException e) {
+ //logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(),e);
+ throw new MusicLockingException("Error getting lockholder info for key [" + lockName +"]:" + e.getMessage());
+ }
+
+ if(peek!=null && (peek.getLocktype()!=null && peek.getLocktype().equals(LockType.WRITE)) && peek.getAcquireTime()!=null && peek.getLockRef()!=null) {
+ long currentTime = System.currentTimeMillis();
+ if((currentTime-Long.parseLong(peek.getAcquireTime()))<MusicUtil.getDefaultLockLeasePeriod()){
+ //logger.info(EELFLoggerDelegate.applicationLogger,"Lock holder exists and lease not expired. Please try again for key="+lockName);
+ throw new MusicLockingException("Unable to create lock reference for key [" + lockName + "]. Please try again.");
+ }
+ }
+ end = System.currentTimeMillis();
+ logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to check for lock reference for key [" + lockName + "]:" + (end - start) + " ms");
+
+ start = System.currentTimeMillis();
+ /* We are Creating a Thread safe set and adding the key to the set.
+ * if a key exists then it wil be passed over and not go to the lock creation.
+ * If a key doesn't exist then it will set the value in the set and continue to create a lock.
+ *
+ * This will ensure that no 2 threads using the same key will be able to try to create a lock
+ * This wil in turn squash the amout of LWT Chatter in Cassandra an reduce the amount of
+ * WriteTimeoutExceptions being experiences on single keys.
+ */
+ if ( set.add(fullyQualifiedKey)) {
+ try {
+ lockReference = "" + getLockingServiceHandle().genLockRefandEnQueue(keyspace, table, lockName, locktype,null);
+ set.remove(fullyQualifiedKey);
+ } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
+ set.remove(fullyQualifiedKey);
+ throw new MusicLockingException(e.getMessage());
+ } catch (Exception e) {
+ set.remove(fullyQualifiedKey);
+ e.printStackTrace();
+ logger.error(EELFLoggerDelegate.applicationLogger,"Exception in creatLockEnforced:"+ e.getMessage(),e);
+ throw new MusicLockingException("Unable to create lock reference for key [" + lockName + "]. " + e.getMessage());
+ }
+ } else {
+ throw new MusicLockingException("Unable to create lock reference for key [" + lockName + "]. Please try again.");
+ }
+ end = System.currentTimeMillis();
+ logger.info(EELFLoggerDelegate.debugLogger,"### Set = " + set);
+ logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to create lock reference for key [" + lockName + "]:" + (end - start) + " ms");
+ return lockReference;
+
+ //return createLockReference(fullyQualifiedKey, locktype, null);
+ }
+
+ public String createLockReference(String fullyQualifiedKey, LockType locktype, String owner) throws MusicLockingException {
+ String[] splitString = fullyQualifiedKey.split("\\.");
+ if (splitString.length < 3) {
+ throw new MusicLockingException("Missing or incorrect lock details. Check table or key name.");
+ }
+ 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 = 0L;
+ long end = 0L;
+ String lockReference = null;
+
+ /* Check for a Deadlock */
+ 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);
+ }
+ end = System.currentTimeMillis();
+ logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to check for deadlock for key [" + lockName + "]:" + (end - start) + " ms");
+
+ start = System.currentTimeMillis();
+ try {
+ lockReference = "" + getLockingServiceHandle().genLockRefandEnQueue(keyspace, table, lockName, locktype, owner);
+ } catch (MusicLockingException | MusicServiceException | MusicQueryException e) {
+ logger.info(EELFLoggerDelegate.applicationLogger,e.getMessage(),e);
+ throw new MusicLockingException("Unable to create lock reference for key [" + lockName + "]. Please try again: " + e.getMessage());
+ } catch (Exception e) {
+ logger.error(EELFLoggerDelegate.applicationLogger,e.getMessage(),e);
+ throw new MusicLockingException("Unable to create lock reference. " + e.getMessage(), e);
+ }
+ end = System.currentTimeMillis();
+ logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to create lock reference for key [" + lockName + "]:" + (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 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 = MusicDataStoreHandle.getDSHandle().executePut(queryObject, "eventual");
+ if (result == false) {
+ return ResultType.FAILURE;
+ }
+ result = false;
+
+ // 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<String> 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<String> releaseAllLocksForOwner(String ownerId, String keyspace, String table) throws MusicLockingException, MusicServiceException, MusicQueryException {
+// System.out.println("IN RELEASEALLLOCKSFOROWNER, ");
+
+ List<String> 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 = createLockReferenceAtomic(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 = createLockReferenceAtomic(fullyQualifiedKey, LockType.READ);
+ 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<String, Object> 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<String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> 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/music-core/src/main/resources/LICENSE.txt
index cc6cdea5..cc6cdea5 100644
--- a/src/main/resources/LICENSE.txt
+++ b/music-core/src/main/resources/LICENSE.txt
diff --git a/src/main/resources/Resources.properties b/music-core/src/main/resources/Resources.properties
index 72269cb8..72269cb8 100644
--- a/src/main/resources/Resources.properties
+++ b/music-core/src/main/resources/Resources.properties
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 @@
+<!--
+ ============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=============================================
+ ====================================================================
+-->
+<configuration scan="true" scanPeriod="3 seconds">
+ <!--<jmxConfigurator /> -->
+ <!-- directory path for all other type logs -->
+ <property name="logDir" value="/opt/app/music/logs" />
+
+ <!-- directory path for debugging type logs -->
+ <property name="debugDir" value="debug-logs" />
+
+ <!-- specify the component name -->
+ <!-- <property name="componentName" value="EELF"></property> -->
+ <property name="componentName" value="MUSIC"></property>
+
+ <!-- log file names -->
+ <property name="generalLogName" value="music" />
+ <property name="securityLogName" value="security" />
+ <property name="errorLogName" value="error" />
+ <property name="metricsLogName" value="metrics" />
+ <property name="auditLogName" value="audit" />
+ <property name="debugLogName" value="debug" />
+ <property name="defaultPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n" />
+ <!-- <property name="applicationLoggerPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %msg%n" /> -->
+ <property name="applicationLoggerPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5level %X{keyspace} [transactionId:%X{transactionId}] - %msg%n" />
+ <property name="auditLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
+ <property name="metricsLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
+ <!-- <property name="errorLoggerPattern" value= "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %msg%n " /> -->
+ <property name="errorLoggerPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5level %X{keyspace} - %msg%n" />
+ <property name="debugLoggerPattern" value="%date{ISO8601,UTC}|%X{RequestId}| %msg%n" ></property>
+ <property name="logDirectory" value="${logDir}/${componentName}" />
+ <property name="debugLogDirectory" value="${debugDir}/${componentName}" />
+ <!-- Example evaluator filter applied against console appender -->
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <!-- <encoder>
+ <pattern>${defaultPattern}</pattern>
+ </encoder> -->
+ <layout class="">
+ <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n</pattern>
+ </layout>
+ </appender>
+
+ <!-- ============================================================================ -->
+ <!-- EELF Appenders -->
+ <!-- ============================================================================ -->
+ <!-- <appender name="EELF" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${generalLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${generalLogName}.%i.log.zip</fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>100MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${applicationLoggerPattern}</pattern>
+ </encoder>
+ </appender> -->
+
+ <!-- <appender name="EELF" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${generalLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
+ daily rollover
+ <fileNamePattern>${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
+ <maxFileSize>1GB</maxFileSize>
+ <maxHistory>5</maxHistory>
+ <totalSizeCap>5GB</totalSizeCap>
+ </rollingPolicy>
+ <encoder>
+ <pattern>${applicationLoggerPattern}</pattern>
+ </encoder>
+ </appender> -->
+
+
+ <appender name="EELF" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${generalLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
+ <!-- daily rollover -->
+ <fileNamePattern>${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
+ <maxFileSize>1GB</maxFileSize>
+ <maxHistory>5</maxHistory>
+ <totalSizeCap>5GB</totalSizeCap>
+ </rollingPolicy>
+ <encoder>
+ <pattern>${applicationLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELF" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <includeCallerData>true</includeCallerData>
+ <appender-ref ref="EELF" />
+ </appender>
+
+ <!-- EELF Security Appender. This appender is used to record security events
+ to the security log file. Security events are separate from other loggers
+ in EELF so that security log records can be captured and managed in a secure
+ way separate from the other logs. This appender is set to never discard any
+ events. -->
+ <appender name="EELFSecurity" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${securityLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${securityLogName}.%i.log.zip</fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n </pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFSecurity" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <discardingThreshold>0</discardingThreshold>
+ <appender-ref ref="EELFSecurity" />
+ </appender>
+
+
+
+
+ <!-- EELF Audit Appender. This appender is used to record audit engine
+ related logging events. The audit logger and appender are specializations
+ of the EELF application root logger and appender. This can be used to segregate
+ Policy engine events from other components, or it can be eliminated to record
+ these events as part of the application root log. -->
+
+ <appender name="EELFAudit" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${auditLogName}.log</file>
+ <rollingPolicy
+ class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${auditLogName}.%i.log.zip</fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${auditLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+ <appender name="asyncEELFAudit" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFAudit" />
+ </appender>
+
+ <appender name="EELFMetrics" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${metricsLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${metricsLogName}.%i.log.zip
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} - %msg%n"</pattern> -->
+ <pattern>${metricsLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+
+
+ <appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFMetrics"/>
+ </appender>
+
+ <appender name="EELFError" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${errorLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${errorLogName}.%i.log.zip</fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${errorLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFError"/>
+ </appender>
+
+ <appender name="EELFDebug" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${debugLogDirectory}/${debugLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${debugLogDirectory}/${debugLogName}.%i.log.zip</fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${debugLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFDebug" />
+ <includeCallerData>true</includeCallerData>
+ </appender>
+
+
+ <!-- ============================================================================ -->
+ <!-- EELF loggers -->
+ <!-- ============================================================================ -->
+ <logger name="com.att.eelf" level="info" additivity="false">
+ <appender-ref ref="asyncEELF" />
+ </logger>
+
+ <logger name="com.att.eelf.security" level="info" additivity="false">
+ <appender-ref ref="asyncEELFSecurity" />
+ </logger>
+
+
+ <logger name="com.att.eelf.audit" level="info" additivity="false">
+ <appender-ref ref="asyncEELFAudit" />
+ </logger>
+
+ <logger name="com.att.eelf.metrics" level="info" additivity="false">
+ <appender-ref ref="asyncEELFMetrics" />
+ </logger>
+
+
+ <logger name="com.att.eelf.error" level="error" additivity="false">
+ <appender-ref ref="asyncEELFError" />
+ </logger>
+
+ <logger name="com.att.eelf.debug" level="debug" additivity="false">
+ <appender-ref ref="asyncEELFDebug" />
+
+ </logger>
+
+ <root level="INFO">
+ <appender-ref ref="asyncEELF" />
+ <appender-ref ref="STDOUT" />
+ </root>
+
+ <!-- Conductor Specific additions to squash WARNING and INFO -->
+ <logger name="com.datastax.driver.core.Cluster" level="ERROR"/>
+ <logger name="org.onap.music.main.MusicCore" level="ERROR"/>
+
+</configuration>
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/src/test/java/LICENSE.txt b/music-core/src/test/java/LICENSE.txt
index cc6cdea5..cc6cdea5 100644
--- a/src/test/java/LICENSE.txt
+++ b/music-core/src/test/java/LICENSE.txt
diff --git a/music-core/src/test/java/org/onap/music/cassandra/MusicUtilTest.java b/music-core/src/test/java/org/onap/music/cassandra/MusicUtilTest.java
new file mode 100644
index 00000000..b7245d78
--- /dev/null
+++ b/music-core/src/test/java/org/onap/music/cassandra/MusicUtilTest.java
@@ -0,0 +1,345 @@
+/*
+ * ============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.cassandra;
+
+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<String,Object> myMap = new HashMap<String,Object>();
+ 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<String> myList = new ArrayList<String>();
+ List<String> newList = myList;
+ myList.add("TOM");
+ assertEquals(MusicUtil.convertToActualDataType(DataType.list(DataType.varchar()),myList),newList);
+ Map<String,Object> myMap = new HashMap<String,Object>();
+ myMap.put("name","tom");
+ Map<String,Object> 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<String,Object> 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 testGetCassandraConnectTimeOutMS() {
+ MusicUtil.setCassandraConnectTimeOutMS(2000);
+ assertEquals(2000,MusicUtil.getCassandraConnectTimeOutMS());
+ }
+
+ @Test
+ public void testGetCassandraReadTimeOutMS() {
+ MusicUtil.setCassandraReadTimeOutMS(2000);
+ assertEquals(2000,MusicUtil.getCassandraReadTimeOutMS());
+ }
+
+ /*
+ @Test
+ public void testLoadProperties() {
+ PropertiesLoader pl = new PropertiesLoader();
+ pl.loadProperties();
+ }
+ */
+}
diff --git a/music-core/src/test/java/org/onap/music/datastore/ConditionTest.java b/music-core/src/test/java/org/onap/music/datastore/ConditionTest.java
new file mode 100644
index 00000000..2aac62af
--- /dev/null
+++ b/music-core/src/test/java/org/onap/music/datastore/ConditionTest.java
@@ -0,0 +1,61 @@
+/*******************************************************************************
+ * ============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.datastore;
+
+import org.onap.music.datastore.Condition;
+import org.onap.music.datastore.PreparedQueryObject;
+import org.onap.music.exceptions.MusicServiceException;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.spy;
+import java.util.Map;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.mockito.Spy;
+
+public class ConditionTest {
+
+ @Spy
+ private Condition condition;
+ private Map<String, Object> conditions;
+ private PreparedQueryObject selectQueryForTheRow;
+
+ @Before
+ public void setup() {
+ conditions = Mockito.mock(Map.class);
+ selectQueryForTheRow = Mockito.mock(PreparedQueryObject.class);
+ condition = spy(new Condition(conditions, selectQueryForTheRow));
+ }
+
+ @Test
+ public void testCondition() throws Exception {
+ ResultSet rs = Mockito.mock(ResultSet.class);
+ Row row = Mockito.mock(Row.class);
+ MusicDataStore dsHandle = Mockito.mock(MusicDataStore.class);
+ Mockito.when(rs.one()).thenReturn(row);
+ Mockito.doReturn(rs).when(condition).quorumGet(Mockito.any());
+ boolean result = false;
+ Mockito.when(dsHandle.doesRowSatisfyCondition(Mockito.any(), Mockito.any())).thenReturn(true);
+ Mockito.doReturn(dsHandle).when(condition).getDSHandle();
+ result = condition.testCondition();
+ assertEquals(true, result);
+ }
+}
diff --git a/music-core/src/test/java/org/onap/music/datastore/MusicDataStoreTest.java b/music-core/src/test/java/org/onap/music/datastore/MusicDataStoreTest.java
new file mode 100644
index 00000000..9260cd92
--- /dev/null
+++ b/music-core/src/test/java/org/onap/music/datastore/MusicDataStoreTest.java
@@ -0,0 +1,436 @@
+/*******************************************************************************
+ * ============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.datastore;
+
+import static org.junit.Assert.*;
+import java.math.BigInteger;
+import java.nio.ByteBuffer;
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.Iterator;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import java.util.function.Consumer;
+import org.junit.Before;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.onap.music.exceptions.MusicQueryException;
+import org.onap.music.exceptions.MusicServiceException;
+import org.onap.music.main.MusicUtil;
+import com.datastax.driver.core.Cluster;
+import com.datastax.driver.core.CodecRegistry;
+import com.datastax.driver.core.ColumnDefinitions;
+import com.datastax.driver.core.ColumnDefinitions.Definition;
+import com.datastax.driver.core.exceptions.WriteTimeoutException;
+import com.datastax.driver.core.ColumnMetadata;
+import com.datastax.driver.core.Configuration;
+import com.datastax.driver.core.ConsistencyLevel;
+import com.datastax.driver.core.DataType;
+import com.datastax.driver.core.KeyspaceMetadata;
+import com.datastax.driver.core.Metadata;
+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.Statement;
+import com.datastax.driver.core.TableMetadata;
+import com.datastax.driver.core.WriteType;
+
+@RunWith(MockitoJUnitRunner.class)
+public class MusicDataStoreTest {
+
+ MusicDataStore dataStore;
+
+ @Mock
+ Session session;
+
+ @Mock
+ Cluster cluster;
+
+ @Before
+ public void before() {
+ CodecRegistry cr = Mockito.mock(CodecRegistry.class);
+ Configuration config = Mockito.mock(Configuration.class);
+ Mockito.when(cluster.getConfiguration()).thenReturn(config);
+ Mockito.when(config.getCodecRegistry()).thenReturn(cr);
+ dataStore = new MusicDataStore(cluster, session);
+ }
+
+
+ @Test
+ public void testMusicDataStoreClusterSession() {
+ Session session = Mockito.mock(Session.class);
+ Cluster cluster = Mockito.mock(Cluster.class);
+
+ CodecRegistry cr = Mockito.mock(CodecRegistry.class);
+ Configuration config = Mockito.mock(Configuration.class);
+ Mockito.when(cluster.getConfiguration()).thenReturn(config);
+ Mockito.when(config.getCodecRegistry()).thenReturn(cr);
+
+
+ MusicDataStore mds = new MusicDataStore(cluster, session);
+ assertEquals(session, mds.getSession());
+ assertEquals(cluster, mds.getCluster());
+ }
+
+ @Test
+ public void testSession() {
+ Session session = Mockito.mock(Session.class);
+ dataStore.setSession(session);
+ assertEquals(session, dataStore.getSession());
+ }
+
+ @Test
+ public void testCluster() {
+ Cluster cluster = Mockito.mock(Cluster.class);
+ CodecRegistry cr = Mockito.mock(CodecRegistry.class);
+ Configuration config = Mockito.mock(Configuration.class);
+ Mockito.when(cluster.getConfiguration()).thenReturn(config);
+ Mockito.when(config.getCodecRegistry()).thenReturn(cr);
+
+ dataStore.setCluster(cluster);
+ assertEquals(cluster, dataStore.getCluster());
+ }
+
+ @Test
+ public void testClose() {
+ dataStore.close();
+ Mockito.verify(session).close();
+ }
+
+ @Test
+ public void testReturnColumnDataType() {
+ Metadata meta = Mockito.mock(Metadata.class);
+ Mockito.when(cluster.getMetadata()).thenReturn(meta);
+ KeyspaceMetadata ksmd = Mockito.mock(KeyspaceMetadata.class);
+ Mockito.when(meta.getKeyspace("keyspace")).thenReturn(ksmd);
+ TableMetadata tmd = Mockito.mock(TableMetadata.class);
+ Mockito.when(ksmd.getTable("table")).thenReturn(tmd);
+ ColumnMetadata cmd = Mockito.mock(ColumnMetadata.class);
+ Mockito.when(tmd.getColumn("columnName")).thenReturn(cmd);
+ Mockito.when(cmd.getType()).thenReturn(com.datastax.driver.core.DataType.text());
+
+ com.datastax.driver.core.DataType dt = dataStore.returnColumnDataType("keyspace", "table", "columnName");
+ assertEquals(com.datastax.driver.core.DataType.text(), dt);
+ }
+
+ @Test
+ public void testReturnColumnMetadata() {
+ Metadata meta = Mockito.mock(Metadata.class);
+ Mockito.when(cluster.getMetadata()).thenReturn(meta);
+ KeyspaceMetadata ksmd = Mockito.mock(KeyspaceMetadata.class);
+ Mockito.when(meta.getKeyspace("keyspace")).thenReturn(ksmd);
+ TableMetadata tmd = Mockito.mock(TableMetadata.class);
+ Mockito.when(ksmd.getTable("tableName")).thenReturn(tmd);
+
+ dataStore.returnColumnMetadata("keyspace", "tableName");
+ assertEquals(tmd, dataStore.returnColumnMetadata("keyspace", "tableName"));
+ }
+
+ @Test
+ public void testReturnKeyspaceMetadata() {
+ Metadata meta = Mockito.mock(Metadata.class);
+ Mockito.when(cluster.getMetadata()).thenReturn(meta);
+ KeyspaceMetadata ksmd = Mockito.mock(KeyspaceMetadata.class);
+ Mockito.when(meta.getKeyspace("keyspace")).thenReturn(ksmd);
+
+ assertEquals(ksmd, dataStore.returnKeyspaceMetadata("keyspace"));
+ }
+
+ @Test
+ public void testGetColValue() {
+ Row row = Mockito.mock(Row.class);
+ Mockito.when(row.getString("columnName")).thenReturn("value");
+ UUID uuid = UUID.randomUUID();
+ Mockito.when(row.getUUID("columnName")).thenReturn(uuid);
+ Mockito.when(row.getVarint("columnName")).thenReturn(BigInteger.ONE);
+ Mockito.when(row.getLong("columnName")).thenReturn((long) 117);
+ Mockito.when(row.getInt("columnName")).thenReturn(5);
+ Mockito.when(row.getFloat("columnName")).thenReturn(Float.MAX_VALUE);
+ Mockito.when(row.getDouble("columnName")).thenReturn(Double.valueOf("2.5"));
+ Mockito.when(row.getBool("columnName")).thenReturn(true);
+ Mockito.when(row.getMap("columnName", String.class, String.class)).thenReturn(new HashMap<String, String>());
+ Mockito.when(row.getList("columnName", String.class)).thenReturn(new ArrayList<String>());
+
+
+ assertEquals("value", dataStore.getColValue(row, "columnName", DataType.varchar()));
+ assertEquals(uuid, dataStore.getColValue(row, "columnName", DataType.uuid()));
+ assertEquals(BigInteger.ONE, dataStore.getColValue(row, "columnName", DataType.varint()));
+ assertEquals((long) 117, dataStore.getColValue(row, "columnName", DataType.bigint()));
+ assertEquals(5, dataStore.getColValue(row, "columnName", DataType.cint()));
+ assertEquals(Float.MAX_VALUE, dataStore.getColValue(row, "columnName", DataType.cfloat()));
+ assertEquals(2.5, dataStore.getColValue(row, "columnName", DataType.cdouble()));
+ assertEquals(true, dataStore.getColValue(row, "columnName", DataType.cboolean()));
+ assertEquals(0, ((Map<String, String>) dataStore.getColValue(row, "columnName",
+ DataType.map(DataType.varchar(), DataType.varchar()))).size());
+ assertEquals(0,
+ ((List<String>) dataStore.getColValue(row, "columnName", DataType.list(DataType.varchar()))).size());
+ }
+
+ @Test
+ public void testGetBlobValue() {
+ Row row = Mockito.mock(Row.class);
+ Mockito.when(row.getBytes("col")).thenReturn(ByteBuffer.allocate(16));
+
+ byte[] byteArray = dataStore.getBlobValue(row, "col", DataType.blob());
+ assertEquals(16, byteArray.length);
+ }
+
+ @Test
+ public void testDoesRowSatisfyCondition() throws Exception {
+ Row row = Mockito.mock(Row.class);
+ ColumnDefinitions cd = Mockito.mock(ColumnDefinitions.class);
+ Mockito.when(row.getColumnDefinitions()).thenReturn(cd);
+ Mockito.when(cd.getType("col1")).thenReturn(DataType.varchar());
+
+ Map<String, Object> condition = new HashMap<>();
+ condition.put("col1", "val1");
+
+ Mockito.when(row.getString("col1")).thenReturn("val1");
+
+ assertTrue(dataStore.doesRowSatisfyCondition(row, condition));
+
+ condition.put("col1", "val2");
+ assertFalse(dataStore.doesRowSatisfyCondition(row, condition));
+ }
+
+ @Test
+ public void testMarshalData() {
+ ResultSet results = Mockito.mock(ResultSet.class);
+ Row row = Mockito.mock(Row.class);
+ Mockito.when(row.getString("colName")).thenReturn("rowValue");
+ //mock for (Row row: results)
+ Iterator mockIterator = Mockito.mock(Iterator.class);
+ //Mockito.doCallRealMethod().when(results).forEach(Mockito.any(Consumer.class));
+ Mockito.when(results.iterator()).thenReturn(mockIterator);
+ Mockito.when(mockIterator.hasNext()).thenReturn(true, false);
+ Mockito.when(mockIterator.next()).thenReturn(row);
+
+ ColumnDefinitions cd = Mockito.mock(ColumnDefinitions.class);
+ Mockito.when(row.getColumnDefinitions()).thenReturn(cd);
+ //for (Definition: colDefinitions)
+ Iterator mockIterator2 = Mockito.mock(Iterator.class);
+ //Mockito.doCallRealMethod().when(cd).forEach(Mockito.any(Consumer.class));
+ Mockito.when(cd.iterator()).thenReturn(mockIterator2);
+ Mockito.when(mockIterator2.hasNext()).thenReturn(true, false);
+ Definition def = Mockito.mock(Definition.class);
+ Mockito.when(mockIterator2.next()).thenReturn(def);
+ Mockito.when(def.getType()).thenReturn(DataType.varchar());
+ Mockito.when(def.getName()).thenReturn("colName");
+
+ Map<String, HashMap<String, Object>> data = dataStore.marshalData(results);
+ System.out.println("Marshalled data: " + data);
+
+ assertTrue(data.containsKey("row 0"));
+ assertEquals("rowValue", data.get("row 0").get("colName"));
+ }
+
+ private ArgumentCaptor<SimpleStatement> sessionExecuteResponse() {
+ ResultSet rs = Mockito.mock(ResultSet.class);
+ Mockito.when(session.execute(Mockito.any(Statement.class))).thenReturn(rs);
+
+ ArgumentCaptor<SimpleStatement> argument = ArgumentCaptor.forClass(SimpleStatement.class);
+ return argument;
+ }
+
+ @Test
+ public void testExecutePutPreparedQueryObjectString() throws Exception {
+ ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
+ String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);";
+ String lastName = "KRUIKSWIJK";
+ String firstName = "Steven";
+
+ PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
+ dataStore.executePut(query, MusicUtil.CRITICAL);
+
+ Mockito.verify(session).execute(argument.capture());
+ assertEquals(ConsistencyLevel.QUORUM, argument.getValue().getConsistencyLevel());
+ assertEquals(queryString, argument.getValue().getQueryString());
+ assertEquals(2, argument.getValue().valuesCount());
+ }
+
+ @Test
+ public void testExecutePut_ONE() throws Exception {
+ ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
+ String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);";
+ String lastName = "KRUIKSWIJK";
+ String firstName = "Steven";
+
+ PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
+ dataStore.executePut(query, MusicUtil.ONE);
+
+ Mockito.verify(session).execute(argument.capture());
+ assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
+ assertEquals(queryString, argument.getValue().getQueryString());
+ assertEquals(2, argument.getValue().valuesCount());
+ }
+
+ @Test
+ public void testExecutePut_quorum() throws Exception {
+ ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
+ String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);";
+ String lastName = "KRUIKSWIJK";
+ String firstName = "Steven";
+
+ PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
+ dataStore.executePut(query, MusicUtil.QUORUM);
+
+ Mockito.verify(session).execute(argument.capture());
+ //should be quorum!
+ assertEquals(ConsistencyLevel.LOCAL_QUORUM, argument.getValue().getConsistencyLevel());
+ assertEquals(queryString, argument.getValue().getQueryString());
+ assertEquals(2, argument.getValue().valuesCount());
+ }
+
+ @Test
+ public void testExecutePut_ALL() throws Exception {
+ ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
+ String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);";
+ String lastName = "KRUIKSWIJK";
+ String firstName = "Steven";
+
+ PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName);
+ dataStore.executePut(query, MusicUtil.ALL);
+
+ Mockito.verify(session).execute(argument.capture());
+ assertEquals(ConsistencyLevel.ALL, argument.getValue().getConsistencyLevel());
+ assertEquals(queryString, argument.getValue().getQueryString());
+ assertEquals(2, argument.getValue().valuesCount());
+ }
+
+ @Test(expected = MusicQueryException.class)
+ public void testExecutePut_BadQueryObj() throws Exception {
+ String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES (?,?);";
+ String lastName = "KRUIKSWIJK";
+ String firstName = "Steven";
+
+ //Provide extra value here, middle initial
+ PreparedQueryObject query = new PreparedQueryObject(queryString, lastName, firstName, "P");
+ try {
+ dataStore.executePut(query, MusicUtil.CRITICAL);
+ } catch (Exception e) {
+ System.out.println(e.getMessage());
+ throw e;
+ }
+
+ fail("Should have throw error");
+ }
+
+ @Test
+ public void testExecutePutPreparedQueryObjectStringLong() throws Exception {
+ ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
+ String queryString = "INSERT INTO cycling.cyclist_name (lastname, firstname) VALUES ('KRUIKSWIJK','Steven');";
+
+
+ PreparedQueryObject query = new PreparedQueryObject(queryString);
+ dataStore.executePut(query, MusicUtil.EVENTUAL, 10);
+
+ Mockito.verify(session).execute(argument.capture());
+ assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
+ assertEquals(queryString, argument.getValue().getQueryString());
+ }
+
+ @Test
+ public void testExecuteGet() throws Exception {
+ ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
+
+ PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
+
+ dataStore.executeGet(query, MusicUtil.ONE);
+
+ Mockito.verify(session).execute(argument.capture());
+ assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
+ assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
+ }
+
+ @Test (expected = MusicQueryException.class)
+ public void testExecuteGet_badQuery() throws Exception {
+ ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
+
+ PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE", "broken");
+
+ dataStore.executeGet(query, MusicUtil.ONE);
+
+ Mockito.verify(session).execute(argument.capture());
+ assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
+ assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
+ }
+
+ @Test
+ public void testExecuteOneConsistencyGet() throws Exception {
+ ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
+ PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
+
+ dataStore.executeOneConsistencyGet(query);
+
+
+ Mockito.verify(session).execute(argument.capture());
+ assertEquals(ConsistencyLevel.ONE, argument.getValue().getConsistencyLevel());
+ assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
+ }
+
+ @Test
+ public void testExecuteLocalQuorumConsistencyGet() throws Exception {
+ ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
+ PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
+
+ dataStore.executeLocalQuorumConsistencyGet(query);
+
+ Mockito.verify(session).execute(argument.capture());
+ assertEquals(ConsistencyLevel.LOCAL_QUORUM, argument.getValue().getConsistencyLevel());
+ assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
+ }
+
+ @Test
+ public void testExecuteQuorumConsistencyGet() throws Exception {
+ ArgumentCaptor<SimpleStatement> argument = sessionExecuteResponse();
+ PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM KEYSPACE.TABLE");
+
+ dataStore.executeQuorumConsistencyGet(query);
+
+ Mockito.verify(session).execute(argument.capture());
+ assertEquals(ConsistencyLevel.QUORUM, argument.getValue().getConsistencyLevel());
+ assertEquals("SELECT * FROM KEYSPACE.TABLE", argument.getValue().getQueryString());
+ }
+
+
+ @Test
+ public void testExecutePut() {
+ Mockito.when(session.execute(Mockito.any(SimpleStatement.class)))
+ .thenThrow(new WriteTimeoutException(ConsistencyLevel.QUORUM, WriteType.CAS, 1, 3));
+
+ try {
+ dataStore.executePut(new PreparedQueryObject("Test query"), "critical");
+ } catch (MusicServiceException e) {
+ return;
+ } catch (MusicQueryException e) {
+ // should never reach here
+ fail();
+ }
+ fail();
+ }
+}
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/datastore/jsonobjects/JSONObjectTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JSONObjectTest.java
new file mode 100644
index 00000000..9fb549d2
--- /dev/null
+++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JSONObjectTest.java
@@ -0,0 +1,54 @@
+
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP MUSIC
+ * ===================================================================
+ * Copyright (C) 2020 IBM Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class JSONObjectTest {
+
+ @Test
+ public void testGetData(){
+ JSONObject js=new JSONObject();
+ js.setData("test");
+ assertEquals(js.getData(),"test");
+
+ }
+}
diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonDeleteTest.java
index 885694bd..5b9cef8b 100644
--- a/src/test/java/org/onap/music/unittests/jsonobjects/JsonDeleteTest.java
+++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonDeleteTest.java
@@ -4,6 +4,8 @@
* ===================================================================
* 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
@@ -19,30 +21,29 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
-package org.onap.music.unittests.jsonobjects;
+
+package org.onap.music.datastore.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<String,Object> mapSo = new HashMap<>();
- mapSo = new HashMap<>();
mapSo.put("key1","one");
mapSo.put("key2","two");
jd.setConditions(mapSo);
@@ -52,7 +53,6 @@ public class JsonDeleteTest {
@Test
public void testGetConsistencyInfo() {
Map<String,String> mapSs = new HashMap<>();
- mapSs = new HashMap<>();
mapSs.put("key3","three");
mapSs.put("key4","four");
jd.setConsistencyInfo(mapSs);
@@ -61,8 +61,7 @@ public class JsonDeleteTest {
@Test
public void testGetColumns() {
- ArrayList<String> ary = new ArrayList<>();
- ary = new ArrayList<>();
+ List<String> ary = new ArrayList<>();
ary.add("e1");
ary.add("e2");
ary.add("e3");
@@ -83,4 +82,32 @@ public class JsonDeleteTest {
}
+ @Test
+ public void testGetKeyspaceName() {
+ jd.setKeyspaceName("keyspace");
+ assertEquals("keyspace",jd.getKeyspaceName());
+
+ }
+
+ @Test
+ public void testGetTableName() {
+ jd.setTableName("tablename");
+ assertEquals("tablename",jd.getTableName());
+
+ }
+
+ @Test
+ public void testGetPrimarKeyValue() {
+ jd.setPrimarKeyValue("primarykey");
+ assertEquals("primarykey",jd.getPrimarKeyValue());
+
+ }
+
+ @Test
+ public void testRowIdString() {
+ StringBuilder builder = new StringBuilder("testing");
+ jd.setRowIdString(builder);
+ assertEquals(jd.getRowIdString().toString(),builder.toString());
+ }
+
}
diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonOnboardTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonIndexTest.java
index 82f1748a..0d89a339 100644
--- a/src/test/java/org/onap/music/unittests/jsonobjects/JsonOnboardTest.java
+++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonIndexTest.java
@@ -19,60 +19,56 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
-package org.onap.music.unittests.jsonobjects;
+
+package org.onap.music.datastore.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.JsonOnboard;
+import org.onap.music.datastore.PreparedQueryObject;
-public class JsonOnboardTest {
+public class JsonIndexTest {
- JsonOnboard jo = null;
+ JsonIndex ji = null;
+
@Before
public void init() {
- jo = new JsonOnboard();
+ ji = new JsonIndex(null, null, null, null);
}
-
+
+
@Test
- public void testGetPassword() {
- String password = "password";
- jo.setPassword(password);
- assertEquals(password,jo.getPassword());
+ public void testKeyspace() {
+ ji.setKeyspaceName("keyspaceName");
+ assertEquals("keyspaceName", ji.getKeyspaceName());
}
-
+
@Test
- public void testGetAid() {
- String aid = "aid";
- jo.setAid(aid);
- assertEquals(aid,jo.getAid());
-
+ public void testIndexName() {
+ ji.setIndexName("indexName");
+ assertEquals("indexName", ji.getIndexName());
}
-
+
@Test
- public void testGetAppname() {
- String appName = "appName";
- jo.setAppname(appName);
- assertEquals(appName,jo.getAppname());
-
+ public void testFieldName() {
+ ji.setFieldName("field");
+ assertEquals("field", ji.getFieldName());
}
-
+
@Test
- public void testGetUserId() {
- String userId = "userId";
- jo.setUserId(userId);
- assertEquals(userId,jo.getUserId());
-
+ public void testTableName() {
+ ji.setTableName("table");
+ assertEquals("table", ji.getTableName());
}
-
+
@Test
- public void testGetIsAAF() {
- String aaf = "true";
- jo.setIsAAF(aaf);
- assertEquals(aaf,jo.getIsAAF());
-
+ public void testCreateIndexQuery() {
+ JsonIndex ji2 = new JsonIndex("index", "keyspace", "table", "field");
+ PreparedQueryObject query = ji2.genCreateIndexQuery();
+ assertEquals("Create index if not exists index on keyspace.table (field);", query.getQuery());
}
-
}
diff --git a/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonInsertTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonInsertTest.java
new file mode 100644
index 00000000..ad71c9ea
--- /dev/null
+++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonInsertTest.java
@@ -0,0 +1,176 @@
+/*
+ * ============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 static org.junit.Assert.assertArrayEquals;
+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 org.apache.commons.lang3.SerializationUtils;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.mockito.internal.util.reflection.FieldSetter;
+import org.onap.music.datastore.MusicDataStore;
+import org.onap.music.datastore.MusicDataStoreHandle;
+import org.onap.music.datastore.PreparedQueryObject;
+import org.onap.music.exceptions.MusicQueryException;
+import org.onap.music.exceptions.MusicServiceException;
+import com.datastax.driver.core.ColumnMetadata;
+import com.datastax.driver.core.DataType;
+import com.datastax.driver.core.Session;
+//import org.mockito.internal.util.reflection.Whitebox;
+import com.datastax.driver.core.TableMetadata;
+
+
+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<String,String> 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<String,Object> 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<String,Object> 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<String,Object> 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<String, byte[]> map = new HashMap<>();
+ ji.setObjectMap(map);
+ assertEquals(map, ji.getObjectMap());
+ }
+
+ @Test
+ public void testPrimaryKey() {
+ ji.setPrimaryKeyVal("primKey");
+ assertEquals("primKey", ji.getPrimaryKeyVal());
+ }
+
+ @Test
+ public void testGenInsertPreparedQueryObj() throws Exception {
+ ji.setKeyspaceName("keyspace");
+ ji.setTableName("table");
+ ji.setPrimaryKeyVal("value");
+ Map<String,Object> rowSpec = new HashMap<>();
+ rowSpec.put("val1","one");
+ rowSpec.put("val2","two");
+ ji.setRowSpecification(rowSpec);
+ Map<String,Object> vals = new HashMap<>();
+ vals.put("val1","one");
+ vals.put("val2","two");
+ ji.setValues(vals);
+
+ Map<String,String> cons = new HashMap<>();
+ cons.put("type","quorum");
+ ji.setConsistencyInfo(cons);
+
+ MusicDataStore mds = Mockito.mock(MusicDataStore.class);
+ Session session = Mockito.mock(Session.class);
+ Mockito.when(mds.getSession()).thenReturn(session);
+ MusicDataStoreHandle mdsh = Mockito.mock(MusicDataStoreHandle.class);
+ FieldSetter.setField(mdsh, mdsh.getClass().getDeclaredField("mDstoreHandle"), mds);
+ TableMetadata tableMeta = Mockito.mock(TableMetadata.class);
+ Mockito.when(mds.returnColumnMetadata(Mockito.anyString(), Mockito.anyString()))
+ .thenReturn(tableMeta);
+
+ ColumnMetadata cmd = Mockito.mock(ColumnMetadata.class);
+ List<ColumnMetadata> listcmd = new ArrayList<>();
+ listcmd.add(cmd);
+ Mockito.when(tableMeta.getPrimaryKey()).thenReturn(listcmd);
+ Mockito.when(cmd.getName()).thenReturn("val1");
+ Mockito.when(tableMeta.getColumn("val1")).thenReturn(cmd);
+ Mockito.when(tableMeta.getColumn("val2")).thenReturn(cmd);
+ Mockito.when(cmd.getType()).thenReturn(DataType.text());
+
+ PreparedQueryObject query = ji.genInsertPreparedQueryObj();
+ System.out.println(query.getQuery());
+ System.out.println(query.getValues());
+
+
+ assertEquals("INSERT INTO keyspace.table (vector_ts,val2,val1) VALUES (?,?,?);", query.getQuery());
+ assertTrue(query.getValues().containsAll(vals.values()));
+ }
+
+}
diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonKeySpaceTest.java
index 882d5d5e..a3fa58e4 100644
--- a/src/test/java/org/onap/music/unittests/jsonobjects/JsonKeySpaceTest.java
+++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonKeySpaceTest.java
@@ -19,14 +19,14 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
-package org.onap.music.unittests.jsonobjects;
+
+package org.onap.music.datastore.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 {
diff --git a/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonLockTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonLockTest.java
new file mode 100644
index 00000000..75db75e5
--- /dev/null
+++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonLockTest.java
@@ -0,0 +1,50 @@
+/*******************************************************************************
+ * ============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.datastore.jsonobjects;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.music.lockingservice.cassandra.LockType;
+
+public class JsonLockTest {
+
+ JsonLock jsonLock;
+
+ @Before
+ public void setup() {
+ jsonLock = new JsonLock();
+ }
+
+ @Test
+ public void testSetLockType() {
+ jsonLock.setLockType(LockType.READ);
+ assertEquals(LockType.READ, jsonLock.getLocktype());
+
+ jsonLock.setLockType(LockType.WRITE);
+ assertEquals(LockType.WRITE, jsonLock.getLocktype());
+
+ jsonLock.setLockType(LockType.PROMOTING);
+ assertEquals(LockType.PROMOTING, jsonLock.getLocktype());
+ }
+}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonSelectTest.java
index ef56c5de..baada1d5 100644
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonSelect.java
+++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonSelectTest.java
@@ -4,6 +4,8 @@
* ===================================================================
* 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
@@ -19,42 +21,48 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.datastore.jsonobjects;
-import java.io.ByteArrayOutputStream;
+import static org.junit.Assert.assertEquals;
+
import java.io.IOException;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
+import java.util.HashMap;
import java.util.Map;
-import org.apache.log4j.Logger;
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class JsonSelect implements Serializable {
- private Map<String, String> consistencyInfo;
- static Logger logger = Logger.getLogger(JsonSelect.class.getName());
+import org.junit.Test;
+
+public class JsonSelectTest {
+ JsonSelect js = new JsonSelect();
- public Map<String, String> getConsistencyInfo() {
- return consistencyInfo;
+ @Test
+ public void testGetConsistencyInfo() {
+ Map<String, String> mapSs = new HashMap<>();
+ mapSs.put("k1", "one");
+ js.setConsistencyInfo(mapSs);
+ assertEquals("one", js.getConsistencyInfo().get("k1"));
}
- public void setConsistencyInfo(Map<String, String> consistencyInfo) {
- this.consistencyInfo = consistencyInfo;
+ @Test
+ public void testSerialize() throws IOException {
+ Map<String, String> mapSs = new HashMap<>();
+ mapSs.put("Key", "Value");
+ js.setConsistencyInfo(mapSs);
+ js.serialize();
}
- public byte[] serialize() {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ObjectOutput out = null;
- try {
- out = new ObjectOutputStream(bos);
- out.writeObject(this);
- } catch (IOException e) {
- // TODO Auto-generated catch block
- logger.error("Error", e);
- e.printStackTrace();
- }
- return bos.toByteArray();
+ @Test
+ public void testGetKeyspaceName() {
+ js.setKeyspaceName("testkeyspace");
+ assertEquals("testkeyspace",js.getKeyspaceName());
+
+ }
+
+ @Test
+ public void testGetTableName() {
+ js.setTableName("testkeyspace");
+ assertEquals("testkeyspace",js.getTableName());
+
}
}
diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonTableTest.java
index e4c800fc..3ab32d40 100644
--- a/src/test/java/org/onap/music/unittests/jsonobjects/JsonTableTest.java
+++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonTableTest.java
@@ -4,6 +4,8 @@
* ===================================================================
* 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
@@ -20,14 +22,14 @@
* ====================================================================
*/
-package org.onap.music.unittests.jsonobjects;
+package org.onap.music.datastore.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;
+import org.onap.music.exceptions.MusicQueryException;
public class JsonTableTest {
@@ -51,6 +53,7 @@ public class JsonTableTest {
Map<String, Object> properties = new HashMap<>();
properties.put("k1", "one");
jt.setProperties(properties);
+ assertEquals(properties.size(), jt.getProperties().size());
}
@Test
@@ -76,18 +79,18 @@ public class JsonTableTest {
}
@Test
- public void testGetSortingKey() {
- String sortKey = "sortkey";
- jt.setSortingKey(sortKey);
- assertEquals(sortKey,jt.getSortingKey());
- }
-
- @Test
public void testGetClusteringOrder() {
String clusteringOrder = "clusteringOrder";
jt.setClusteringOrder(clusteringOrder);
assertEquals(clusteringOrder,jt.getClusteringOrder());
}
+
+ @Test
+ public void testGetClusterKey() {
+ String clusterKey = "clusterKey";
+ jt.setClusteringKey(clusterKey);
+ assertEquals(clusterKey, jt.getClusteringKey());
+ }
@Test
public void testGetPrimaryKey() {
@@ -95,5 +98,56 @@ public class JsonTableTest {
jt.setPrimaryKey(primaryKey);
assertEquals(primaryKey,jt.getPrimaryKey());
}
+
+ @Test
+ public void testFilteringKey() {
+ jt.setFilteringKey("FilteringKey");
+ assertEquals("FilteringKey",jt.getFilteringKey());
+ }
+
+ @Test
+ public void testPartitionKey() {
+ jt.setPartitionKey("ParitionKey");
+ assertEquals("ParitionKey",jt.getPartitionKey());
+ }
+ @Test
+ public void genCreateTableQuery() throws MusicQueryException {
+ JsonTable jt2 = new JsonTable();
+ jt2.setKeyspaceName("keyspace");
+ jt2.setTableName("table");
+ Map<String, String> fields = new HashMap<>();
+ fields.put("k1", "one");
+ jt2.setFields(fields);
+ jt2.setPrimaryKey("k1");
+ Map<String, String> mapSs = new HashMap<>();
+ mapSs.put("k1", "one");
+ jt2.setConsistencyInfo(mapSs);
+ String clusteringOrder = "clusteringOrder";
+ jt.setClusteringOrder(clusteringOrder);
+ String clusterKey = "clusterKey";
+ jt.setClusteringKey(clusterKey);
+
+ System.out.println(jt2.genCreateTableQuery().getQuery());
+ assertEquals("CREATE TABLE keyspace.table (vector_ts text,k1 one, PRIMARY KEY ( (k1) ));",
+ jt2.genCreateTableQuery().getQuery());
+ }
+
+ @Test
+ public void genDropTableQuery() throws MusicQueryException {
+ JsonTable jt2 = new JsonTable();
+ jt2.setKeyspaceName("keyspace");
+ jt2.setTableName("table");
+ Map<String, String> fields = new HashMap<>();
+ fields.put("k1", "one");
+ jt2.setFields(fields);
+ jt2.setPrimaryKey("k1");
+ Map<String, String> mapSs = new HashMap<>();
+ mapSs.put("k1", "one");
+ jt.setConsistencyInfo(mapSs);
+
+ System.out.println(jt2.genDropTableQuery().getQuery());
+ assertEquals("DROP TABLE keyspace.table;",
+ jt2.genDropTableQuery().getQuery());
+ }
}
diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonUpdateTest.java
index 54db0540..37c729f4 100644
--- a/src/test/java/org/onap/music/unittests/jsonobjects/JsonUpdateTest.java
+++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/JsonUpdateTest.java
@@ -4,6 +4,8 @@
* ===================================================================
* 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
@@ -19,14 +21,23 @@
* ============LICENSE_END=============================================
* ====================================================================
*******************************************************************************/
-package org.onap.music.unittests.jsonobjects;
+
+package org.onap.music.datastore.jsonobjects;
import static org.junit.Assert.*;
+import java.util.ArrayList;
+import java.util.Arrays;
import java.util.HashMap;
+import java.util.List;
import java.util.Map;
+import javax.ws.rs.core.MultivaluedMap;
import org.junit.Before;
import org.junit.Test;
-import org.onap.music.datastore.jsonobjects.JsonUpdate;
+import org.mockito.Mockito;
+import org.onap.music.datastore.jsonobjects.JsonUpdate.RowIdentifier;
+import com.datastax.driver.core.ColumnMetadata;
+import com.datastax.driver.core.DataType;
+import com.datastax.driver.core.TableMetadata;
public class JsonUpdateTest {
@@ -99,5 +110,57 @@ public class JsonUpdateTest {
ju.setValues(cons);
assertEquals("one",ju.getValues().get("val1"));
}
+
+ @Test
+ public void testSerialize() {
+ assertTrue(ju.serialize() instanceof byte[]);
+ }
+
+ @Test
+ public void testRowIdString() {
+ ju.setRowIdString("testing");
+ assertEquals("testing", ju.getRowIdString());
+ }
+
+ @Test
+ public void testPrimaryKeyValue() {
+ ju.setPrimarKeyValue("primeKey");
+ assertEquals("primeKey", ju.getPrimarKeyValue());
+ }
+ @Test
+ public void testGenUpdatePreparedQueryObj() throws Exception {
+ JsonUpdate ju = Mockito.spy(JsonUpdate.class);
+ MultivaluedMap<String, String> rowParams = Mockito.mock(MultivaluedMap.class);
+
+ ju.setKeyspaceName("keyspace");
+ ju.setTableName("table");
+ ju.setPrimarKeyValue("primaryKeyValue");
+ Map<String, String> consistencyInfo = new HashMap<>();
+ consistencyInfo.put("type", "critical");
+ ju.setConsistencyInfo(consistencyInfo);
+ Map<String, Object> values = new HashMap<>();
+ values.put("col1", "val1");
+ ju.setValues(values);
+
+ TableMetadata tmd = Mockito.mock(TableMetadata.class);
+ Mockito.doReturn(tmd).when(ju).returnColumnMetadata(Mockito.anyString(), Mockito.anyString());
+ ColumnMetadata cmd = Mockito.mock(ColumnMetadata.class);
+ Mockito.when(tmd.getColumn("col1")).thenReturn(cmd);
+ List<ColumnMetadata> colList = new ArrayList<>();
+ colList.add(cmd);
+ Mockito.when(tmd.getPrimaryKey()).thenReturn(colList);
+ Mockito.when(cmd.getType()).thenReturn(DataType.varchar());
+
+ RowIdentifier rowId = Mockito.mock(RowIdentifier.class);
+ Mockito.doReturn(rowId).when(ju).getRowIdentifier(Mockito.anyString(), Mockito.anyString(), Mockito.any(),
+ Mockito.any());
+
+ Mockito.when(rowId.getRowIdString()).thenReturn("col1");
+ Mockito.when(rowId.getPrimaryKeyValue()).thenReturn("val1");
+
+
+ assertEquals("UPDATE keyspace.table SET vector_ts=?,col1= ? WHERE col1;",
+ ju.genUpdatePreparedQueryObj(rowParams).getQuery());
+ }
}
diff --git a/music-core/src/test/java/org/onap/music/datastore/jsonobjects/RowIdentifierTest.java b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/RowIdentifierTest.java
new file mode 100644
index 00000000..e29f0377
--- /dev/null
+++ b/music-core/src/test/java/org/onap/music/datastore/jsonobjects/RowIdentifierTest.java
@@ -0,0 +1,60 @@
+/*-
+ * ============LICENSE_START==========================================
+ * ONAP MUSIC
+ * ===================================================================
+ * Copyright (C) 2020 IBM Intellectual Property. All rights reserved.
+ * ===================================================================
+ *
+ * Unless otherwise specified, all software contained herein is licensed
+ * under the Apache License, Version 2.0 (the "License");
+ * you may not use this software except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * Unless otherwise specified, all documentation contained herein is licensed
+ * under the Creative Commons License, Attribution 4.0 Intl. (the "License");
+ * you may not use this documentation except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * https://creativecommons.org/licenses/by/4.0/
+ *
+ * Unless required by applicable law or agreed to in writing, documentation
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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.datastore.jsonobjects.JsonUpdate;
+import org.junit.Before;
+import org.junit.Test;
+
+import static org.junit.Assert.assertEquals;
+
+public class RowIdentifierTest {
+ String primarykey="primarykey";
+ String rowIdString="123";
+ PreparedQueryObject queryObject=new PreparedQueryObject("select * from employee");
+ JsonUpdate ju=new JsonUpdate();
+ JsonUpdate.RowIdentifier rowId= ju.new RowIdentifier(primarykey,rowIdString,queryObject);
+ @Test
+ public void testConstructor(){
+ rowId.setPrimaryKeyValue(primarykey);
+ rowId.setRowIdString(rowIdString);
+ assertEquals(rowId.getPrimaryKeyValue(),"primarykey");
+ assertEquals(rowId.getRowIdString(),"123");
+ }
+}
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/eelf/logging/format/ErrorSeverityTest.java b/music-core/src/test/java/org/onap/music/eelf/logging/format/ErrorSeverityTest.java
new file mode 100644
index 00000000..b2b0fafa
--- /dev/null
+++ b/music-core/src/test/java/org/onap/music/eelf/logging/format/ErrorSeverityTest.java
@@ -0,0 +1,41 @@
+/*
+ * ============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.Test;
+
+public class ErrorSeverityTest {
+
+ @Test
+ public void TestErrorServerity()
+ {
+ assertEquals("INFO",ErrorSeverity.INFO.name());
+ assertEquals("WARN",ErrorSeverity.WARN.name());
+ assertEquals("ERROR",ErrorSeverity.ERROR.name());
+ assertEquals("FATAL",ErrorSeverity.FATAL.name());
+ assertEquals("CRITICAL",ErrorSeverity.CRITICAL.name());
+ assertEquals("MAJOR",ErrorSeverity.MAJOR.name());
+ assertEquals("MINOR",ErrorSeverity.MINOR.name());
+ assertEquals("NONE",ErrorSeverity.NONE.name());
+ }
+}
diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/AAFResponseTest.java b/music-core/src/test/java/org/onap/music/eelf/logging/format/ErrorTypesTest.java
index 354668c7..ff7b188b 100644
--- a/src/test/java/org/onap/music/unittests/jsonobjects/AAFResponseTest.java
+++ b/music-core/src/test/java/org/onap/music/eelf/logging/format/ErrorTypesTest.java
@@ -3,6 +3,7 @@
* 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.
@@ -20,35 +21,28 @@
* ====================================================================
*/
-package org.onap.music.unittests.jsonobjects;
+package org.onap.music.eelf.logging.format;
-import static org.junit.Assert.*;
-import java.util.ArrayList;
-import org.junit.Test;
-import org.onap.music.datastore.jsonobjects.AAFResponse;
-import org.onap.music.datastore.jsonobjects.NameSpace;
-
-public class AAFResponseTest {
+import static org.junit.Assert.assertEquals;
- @Test
- public void testGetNs() {
- NameSpace ns = new NameSpace();
- AAFResponse ar = new AAFResponse();
- ArrayList<NameSpace> nsArray = new ArrayList<>();
- ns.setName("tom");
- ArrayList<String> admin = new ArrayList<>();
- admin.add("admin1");
- ns.setAdmin(admin);
- nsArray.add(ns);
- ar.setNs(nsArray);
- assertEquals("tom",ar.getNs().get(0).getName());
- assertEquals("admin1",ar.getNs().get(0).getAdmin().get(0));
-
- }
+import org.junit.Test;
-// @Test
-// public void testSetNs() {
-// fail("Not yet implemented");
-// }
+public class ErrorTypesTest {
+ @Test
+ public void Test1()
+ {
+ assertEquals("CONNECTIONERROR",ErrorTypes.CONNECTIONERROR.name());
+ assertEquals("SESSIONEXPIRED",ErrorTypes.SESSIONEXPIRED.name());
+ assertEquals("AUTHENTICATIONERROR",ErrorTypes.AUTHENTICATIONERROR.name());
+ assertEquals("CACHEERROR",ErrorTypes.CACHEERROR.name());
+ assertEquals("SERVICEUNAVAILABLE",ErrorTypes.SERVICEUNAVAILABLE.name());
+ assertEquals("QUERYERROR",ErrorTypes.QUERYERROR.name());
+ assertEquals("DATAERROR",ErrorTypes.DATAERROR.name());
+ assertEquals("GENERALSERVICEERROR",ErrorTypes.GENERALSERVICEERROR.name());
+ assertEquals("MUSICSERVICEERROR",ErrorTypes.MUSICSERVICEERROR.name());
+ assertEquals("LOCKINGERROR",ErrorTypes.LOCKINGERROR.name());
+ assertEquals("UNKNOWN",ErrorTypes.UNKNOWN.name());
+
+ }
}
diff --git a/music-core/src/test/java/org/onap/music/exceptions/MusicDeadlockExceptionTest.java b/music-core/src/test/java/org/onap/music/exceptions/MusicDeadlockExceptionTest.java
new file mode 100644
index 00000000..db0e10ea
--- /dev/null
+++ b/music-core/src/test/java/org/onap/music/exceptions/MusicDeadlockExceptionTest.java
@@ -0,0 +1,135 @@
+/*
+ * ============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 MusicDeadlockExceptionTest {
+
+ private String owner = "tester";
+ private String keyspace = "testing";
+ private String table = "lockq";
+ private String key = "test";
+
+ @Test
+ public void TestException1() {
+ String s1 = "Value1";
+ String s2 = "value2";
+ try {
+ if (!s1.equalsIgnoreCase(s2)) {
+ throw new MusicDeadlockException();
+ }
+ } catch (MusicDeadlockException mde) {
+ assertEquals("org.onap.music.exceptions.MusicDeadlockException", mde.getClass().getName());
+ }
+
+ }
+
+ @Test
+ public void TestException6() {
+ String s1 = "Value1";
+ String s2 = "value2";
+ try {
+ if (!s1.equalsIgnoreCase(s2)) {
+ throw new MusicDeadlockException("org.onap.music.exceptions.MusicDeadlockException");
+ }
+ } catch (MusicDeadlockException mde) {
+ assertEquals(mde.getMessage(),"org.onap.music.exceptions.MusicDeadlockException");
+ }
+
+ }
+
+ @Test
+ public void TestException2() {
+ String s1 = "Value1";
+ String s2 = "value2";
+ try {
+ if (!s1.equalsIgnoreCase(s2)) {
+ throw new MusicDeadlockException("MusicDeadlockException Exception occured..");
+ }
+ } catch (MusicDeadlockException mde) {
+ assertEquals(mde.getMessage(), "MusicDeadlockException Exception occured..");
+ }
+
+ }
+
+ @Test
+ public void TestException3() {
+ String s1 = "Value1";
+ String s2 = "value2";
+ try {
+ if (!s1.equalsIgnoreCase(s2)) {
+ throw new MusicDeadlockException(new Throwable());
+ }
+ } catch (MusicDeadlockException mve) {
+ assertEquals("org.onap.music.exceptions.MusicDeadlockException", mve.getClass().getName());
+ }
+
+ }
+
+ @Test
+ public void TestException4() {
+ String message = "Exception occured";
+ String s1 = "Value1";
+ String s2 = "value2";
+ try {
+ if (!s1.equalsIgnoreCase(s2)) {
+ throw new MusicDeadlockException(message, new Throwable());
+ }
+ } catch (MusicDeadlockException mde) {
+ assertEquals("org.onap.music.exceptions.MusicDeadlockException", mde.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 MusicDeadlockException(message, new Throwable(), enableSuppression,
+ writableStackTrace);
+ }
+ } catch (MusicDeadlockException mde) {
+ assertEquals("org.onap.music.exceptions.MusicDeadlockException", mde.getClass().getName());
+ }
+
+ }
+
+ @Test
+ public void TestSetValues()
+ {
+ MusicDeadlockException mde=new MusicDeadlockException();
+ mde.setValues(owner,keyspace,table,key);
+ assertEquals("tester",mde.getOwner());
+ assertEquals("testing",mde.getKeyspace());
+ assertEquals("lockq",mde.getTable());
+ assertEquals("test",mde.getKey());
+ }
+}
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/lockingservice/cassandra/CassaLockStoreTest.java b/music-core/src/test/java/org/onap/music/lockingservice/cassandra/CassaLockStoreTest.java
new file mode 100644
index 00000000..a608a970
--- /dev/null
+++ b/music-core/src/test/java/org/onap/music/lockingservice/cassandra/CassaLockStoreTest.java
@@ -0,0 +1,311 @@
+/*
+ * ============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.lockingservice.cassandra;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.fail;
+import java.util.Iterator;
+import java.util.List;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.music.datastore.MusicDataStore;
+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 com.datastax.driver.core.ConsistencyLevel;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.WriteType;
+import com.datastax.driver.core.exceptions.WriteTimeoutException;
+
+public class CassaLockStoreTest {
+
+ private CassaLockStore cassaLockStore;
+ private CassaLockStore.LockObject lockObject;
+ private MusicDataStore dsHandle;
+
+ @Before
+ public void setUp() {
+ dsHandle = Mockito.mock(MusicDataStore.class);
+ cassaLockStore = new CassaLockStore(dsHandle);
+ lockObject = cassaLockStore.new LockObject(false, null, null, null, null, null);
+ }
+
+ @Test
+ public void testLockOwner() {
+ lockObject.setIsLockOwner(true);
+ assertEquals(true, lockObject.getIsLockOwner());
+
+ lockObject.setIsLockOwner(false);
+ assertEquals(false, lockObject.getIsLockOwner());
+ }
+
+ @Test
+ public void testAcquireTime() {
+ lockObject.setAcquireTime("2019-11-11T15:42:12+00:00");
+ assertEquals("2019-11-11T15:42:12+00:00", lockObject.getAcquireTime());
+ }
+
+ @Test
+ public void testCreateTime() {
+ lockObject.setCreateTime("2019-11-11T15:43:44+00:00");
+ assertEquals("2019-11-11T15:43:44+00:00", lockObject.getCreateTime());
+ }
+
+ @Test
+ public void testLockRef() {
+ lockObject.setLockRef("LockReference");
+ assertEquals("LockReference", lockObject.getLockRef());
+ }
+
+ @Test
+ public void testLockType() {
+ lockObject.setLocktype(LockType.READ);
+ assertEquals(LockType.READ, lockObject.getLocktype());
+ }
+
+ @Test
+ public void testOwner() {
+ lockObject.setOwner("Owner");
+ assertEquals("Owner", lockObject.getOwner());
+ }
+
+ @Test
+ public void testCreateLockQueue() {
+ try {
+ Mockito.when(dsHandle.executePut(Mockito.any(), Mockito.any())).thenReturn(true);
+ assertEquals(true, cassaLockStore.createLockQueue("keyspace1", "table1"));
+ } catch (MusicServiceException | MusicQueryException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testGenLockRefandEnQueue() {
+ ResultSet resultSetMock = Mockito.mock(ResultSet.class);
+ List<Row> latestGuardRow = Mockito.mock(List.class);
+ Mockito.when(latestGuardRow.isEmpty()).thenReturn(false);
+ Row row = Mockito.mock(Row.class);
+ Mockito.when(latestGuardRow.get(0)).thenReturn(row);
+ Mockito.when(row.getLong(0)).thenReturn((long) 4);
+ Mockito.when(resultSetMock.all()).thenReturn(latestGuardRow);
+ try {
+ Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.any())).thenReturn(resultSetMock);
+ Mockito.when(dsHandle.executePut(Mockito.any(), Mockito.any())).thenReturn(true);
+ assertEquals("$keyspace2.table2.lockName2$5",
+ cassaLockStore.genLockRefandEnQueue("keyspace2", "table2", "lockName2", LockType.READ, "owner2"));
+ } catch (MusicServiceException | MusicQueryException | MusicLockingException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testGetLockQueue() {
+ ResultSet resultSetMock = Mockito.mock(ResultSet.class);
+ Iterator<Row> iterator = Mockito.mock(Iterator.class);
+ Mockito.when(iterator.hasNext()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
+ Row row = Mockito.mock(Row.class);
+ Mockito.when(row.getLong("lockReference")).thenReturn((long)1).thenReturn((long)2).thenReturn((long)3);
+ Mockito.when(row.get("lockType", LockType.class)).thenReturn(LockType.WRITE).thenReturn(LockType.WRITE).thenReturn(LockType.WRITE);
+ Mockito.when(iterator.next()).thenReturn(row).thenReturn(row).thenReturn(row);
+ Mockito.when(resultSetMock.iterator()).thenReturn(iterator);
+
+ try {
+ Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.any())).thenReturn(resultSetMock);
+ assertEquals("2", cassaLockStore.getLockQueue("keyspace2", "table2", "key2").get(1));
+ } catch (MusicServiceException | MusicQueryException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testGetLockQueueSize() {
+ ResultSet resultSetMock = Mockito.mock(ResultSet.class);
+ Row row = Mockito.mock(Row.class);
+ Mockito.when(resultSetMock.one()).thenReturn(row);
+ Mockito.when(row.getLong("count")).thenReturn((long) 6);
+ try {
+ Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.any())).thenReturn(resultSetMock);
+ assertEquals(6, cassaLockStore.getLockQueueSize("keyspace3", "table3", "key3"));
+ } catch (MusicServiceException | MusicQueryException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testPeekLockQueue() {
+ ResultSet resultSetMock = Mockito.mock(ResultSet.class);
+ Row row = Mockito.mock(Row.class);
+ Mockito.when(row.isNull("lockReference")).thenReturn(false);
+ Mockito.when(row.getLong("lockReference")).thenReturn((long) 6);
+ Mockito.when(row.getString("createTime")).thenReturn("2019-11-13T15:05:45+00:00");
+ Mockito.when(row.getString("acquireTime")).thenReturn("2019-11-13T15:05:45+00:00");
+ Mockito.when(row.isNull("lockReference")).thenReturn(false);
+ Mockito.when(resultSetMock.one()).thenReturn(row);
+ try {
+ Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.any())).thenReturn(resultSetMock);
+ assertEquals("6", cassaLockStore.peekLockQueue("keyspace4", "table4", "key4").getLockRef());
+ } catch (MusicServiceException | MusicQueryException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testGetCurrentLockHolders() {
+ ResultSet resultSetMock = Mockito.mock(ResultSet.class);
+ Iterator<Row> iterator = Mockito.mock(Iterator.class);
+ Mockito.when(iterator.hasNext()).thenReturn(true).thenReturn(true).thenReturn(false);
+ Row row = Mockito.mock(Row.class);
+ Mockito.when(row.getLong("lockReference")).thenReturn((long) 5).thenReturn((long) 5);
+ Mockito.when(row.get("lockType", LockType.class)).thenReturn(LockType.WRITE);
+ Mockito.when(iterator.next()).thenReturn(row).thenReturn(row);
+ Mockito.when(resultSetMock.iterator()).thenReturn(iterator);
+ try {
+ Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.any())).thenReturn(resultSetMock);
+ assertEquals("$keyspace5.table5.key5$5", cassaLockStore.getCurrentLockHolders("keyspace5", "table5", "key5").get(1));
+ } catch (MusicServiceException | MusicQueryException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testIsLockOwner() {
+ ResultSet resultSetMock = Mockito.mock(ResultSet.class);
+ Iterator<Row> iterator = Mockito.mock(Iterator.class);
+ Mockito.when(iterator.hasNext()).thenReturn(true).thenReturn(true).thenReturn(false);
+ Row row = Mockito.mock(Row.class);
+ Mockito.when(row.getLong("lockReference")).thenReturn((long) 5);
+ Mockito.when(row.get("lockType", LockType.class)).thenReturn(LockType.WRITE);
+ Mockito.when(iterator.next()).thenReturn(row).thenReturn(row);
+ Mockito.when(resultSetMock.iterator()).thenReturn(iterator);
+ try {
+ Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.any())).thenReturn(resultSetMock);
+ assertEquals(true, cassaLockStore.isLockOwner("keyspace5", "table5", "key5", "5"));
+ } catch (MusicServiceException | MusicQueryException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testGetLockInfo() {
+ ResultSet resultSetMock = Mockito.mock(ResultSet.class);
+ Row row = Mockito.mock(Row.class);
+ Mockito.when(row.isNull("lockReference")).thenReturn(false);
+ Mockito.when(row.getLong("lockReference")).thenReturn((long) 6);
+ Mockito.when(row.getString("createTime")).thenReturn("2019-11-13T15:05:45+00:00");
+ Mockito.when(row.getString("acquireTime")).thenReturn("2019-11-13T15:05:45+00:00");
+ LockType locktype = Mockito.mock(LockType.class);
+ Mockito.when(row.get("lockType", LockType.class)).thenReturn(locktype);
+ Mockito.when(row.getString("owner")).thenReturn("owner6");
+ Mockito.when(resultSetMock.one()).thenReturn(row);
+
+ try {
+ Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.any())).thenReturn(resultSetMock);
+ CassaLockStore csLockStore = Mockito.spy(cassaLockStore);
+ Mockito.doReturn(true).when(csLockStore).isLockOwner(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any());
+ assertEquals("6", csLockStore.getLockInfo("keyspace6", "table6", "key6", "6").getLockRef());
+ } catch (MusicServiceException | MusicQueryException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testCheckForDeadlock() {
+ DeadlockDetectionUtil ddu = Mockito.mock(DeadlockDetectionUtil.class);
+ ResultSet resultSetMock = Mockito.mock(ResultSet.class);
+ Iterator<Row> it = Mockito.mock(Iterator.class);
+ Row row = Mockito.mock(Row.class);
+ Mockito.when(it.hasNext()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
+ Mockito.when(row.getString("key")).thenReturn("key8");
+ Mockito.when(row.getString("owner")).thenReturn("owner8");
+ Mockito.when(row.getString("acquiretime")).thenReturn("1");
+ Mockito.when(it.next()).thenReturn(row).thenReturn(row).thenReturn(row);
+ Mockito.when(resultSetMock.iterator()).thenReturn(it);
+ CassaLockStore csLockStore = Mockito.spy(cassaLockStore);
+ Mockito.doReturn(ddu).when(csLockStore).getDeadlockDetectionUtil();
+ Mockito.when(ddu.checkForDeadlock(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(true);
+ try {
+ Mockito.when(dsHandle.executeLocalQuorumConsistencyGet(Mockito.any())).thenReturn(resultSetMock);
+ assertEquals(false,
+ cassaLockStore.checkForDeadlock("keyspace8", "table8", "lockName8", LockType.WRITE, "owner8", true));
+ } catch (MusicServiceException | MusicQueryException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testGetAllLocksForOwner() {
+ ResultSet resultSetMock = Mockito.mock(ResultSet.class);
+ Iterator<Row> it = Mockito.mock(Iterator.class);
+ Mockito.when(it.hasNext()).thenReturn(true).thenReturn(true).thenReturn(false);
+ Row row = Mockito.mock(Row.class);
+ Mockito.when(row.getString("key")).thenReturn("key10");
+ Mockito.when(row.getLong("lockreference")).thenReturn((long) 10);
+ Mockito.when(it.next()).thenReturn(row);
+ Mockito.when(resultSetMock.iterator()).thenReturn(it);
+ try {
+ Mockito.when(dsHandle.executeQuorumConsistencyGet(Mockito.any())).thenReturn(resultSetMock);
+ assertEquals("key10$10", cassaLockStore.getAllLocksForOwner("owneer10", "keyspace10", "table10").get(1));
+ } catch (MusicServiceException | MusicQueryException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testDequeueLockRef() throws Exception {
+ cassaLockStore.deQueueLockRef("keyspace1", "table1", "key6", "6", 2);
+
+ // note only expecting 1 call to this instance, expecting it to succeed
+ Mockito.verify(dsHandle, Mockito.times(1)).executePut(Mockito.any(), Mockito.anyString());
+ }
+
+ @Test
+ public void testDequeueLockRefWriteTimeout() throws Exception {
+ int retryCount = 22;
+ try {
+ Mockito.when(dsHandle.executePut(Mockito.any(), Mockito.anyString()))
+ .thenThrow(new MusicServiceException("Cassandra timeout during..."));
+ cassaLockStore.deQueueLockRef("keyspace1", "table1", "key6", "6", retryCount);
+
+ // Should never reach here
+ fail();
+ } catch (MusicServiceException | MusicQueryException | MusicLockingException e) {
+ // should throw an error
+ }
+
+ Mockito.verify(dsHandle, Mockito.times(retryCount)).executePut(Mockito.any(), Mockito.anyString());
+ }
+}
diff --git a/music-core/src/test/java/org/onap/music/lockingservice/cassandra/MusicLockStateTest.java b/music-core/src/test/java/org/onap/music/lockingservice/cassandra/MusicLockStateTest.java
new file mode 100644
index 00000000..e5b655bd
--- /dev/null
+++ b/music-core/src/test/java/org/onap/music/lockingservice/cassandra/MusicLockStateTest.java
@@ -0,0 +1,86 @@
+/*******************************************************************************
+ * ============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.lockingservice.cassandra;
+
+import static org.junit.Assert.assertEquals;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus;
+
+public class MusicLockStateTest {
+
+ MusicLockState musicLockState;
+
+ @Before
+ public void setup() {
+ musicLockState = new MusicLockState(LockStatus.LOCKED, "", true);
+ }
+
+ @Test
+ public void testGetLeasePeriod() {
+ musicLockState.setLeasePeriod(200L);
+ assertEquals(200L, musicLockState.getLeasePeriod());
+ }
+
+ @Test
+ public void testIsNeedToSyncQuorum() {
+ assertEquals(true, musicLockState.isNeedToSyncQuorum());
+ }
+
+ @Test
+ public void testGetLeaseStartTime() {
+ musicLockState.setLeaseStartTime(200L);
+ assertEquals(200L, musicLockState.getLeaseStartTime());
+ }
+
+ @Test
+ public void testGetLockStatus() {
+ musicLockState.setLockStatus(LockStatus.LOCKED);
+ assertEquals(LockStatus.LOCKED, musicLockState.getLockStatus());
+ }
+
+ @Test
+ public void testGetLockHolder() {
+ musicLockState.setLockHolder("lockHolder");
+ assertEquals("lockHolder", musicLockState.getLockHolder());
+ }
+
+ @Test
+ public void testGetErrorMessage() {
+ MusicLockState musicLockState2 = new MusicLockState("This is error message");
+ assertEquals("This is error message", musicLockState2.getErrorMessage());
+ }
+
+ @Test
+ public void testSerialize() {
+ byte[] serializedBytes = musicLockState.serialize();
+ MusicLockState musicLockState3 = musicLockState.deSerialize(serializedBytes);
+ assertEquals(musicLockState.getLeasePeriod(),musicLockState3.getLeasePeriod());
+ assertEquals(musicLockState.isNeedToSyncQuorum(),musicLockState3.isNeedToSyncQuorum());
+ assertEquals(musicLockState.getLeaseStartTime(),musicLockState3.getLeaseStartTime());
+ assertEquals(musicLockState.getLockStatus(),musicLockState3.getLockStatus());
+ assertEquals(musicLockState.getLockHolder(),musicLockState3.getLockHolder());
+ assertEquals(musicLockState.getErrorMessage(),musicLockState3.getErrorMessage());
+ }
+
+}
diff --git a/music-core/src/test/java/org/onap/music/main/CipherUtilTest.java b/music-core/src/test/java/org/onap/music/main/CipherUtilTest.java
new file mode 100644
index 00000000..ff187ffd
--- /dev/null
+++ b/music-core/src/test/java/org/onap/music/main/CipherUtilTest.java
@@ -0,0 +1,55 @@
+/*
+ * ============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.main;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Before;
+import org.junit.Test;
+
+public class CipherUtilTest {
+
+ private CipherUtil cipherUtil;
+
+ @Before
+ public void setup() {
+ cipherUtil = new CipherUtil();
+ }
+
+ @Test
+ public void testEncryptPKC() {
+ String encryptedText = CipherUtil.encryptPKC("This is another string to be encrypted",
+ "4BFF9DCCD774F3650E20C4D3F69F8C99");
+ System.out.println("*************************" + encryptedText);
+ assertEquals(88, encryptedText.length());
+ }
+
+ @Test
+ public void testDecryptPKC() {
+ String encryptedText = CipherUtil.encryptPKC("This is another string to be encrypted",
+ "4BFF9DCCD774F3650E20C4D3F69F8C99");
+ assertEquals("This is another string to be encrypted",
+ CipherUtil.decryptPKC(encryptedText, "4BFF9DCCD774F3650E20C4D3F69F8C99"));
+ }
+
+}
diff --git a/music-core/src/test/java/org/onap/music/main/DeadlockDetectionUtilTest.java b/music-core/src/test/java/org/onap/music/main/DeadlockDetectionUtilTest.java
new file mode 100644
index 00000000..ab767e17
--- /dev/null
+++ b/music-core/src/test/java/org/onap/music/main/DeadlockDetectionUtilTest.java
@@ -0,0 +1,87 @@
+/*
+ * ============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.main;
+
+import static org.junit.Assert.assertEquals;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+
+import org.junit.Before;
+import org.junit.Test;
+//import org.junit.experimental.runners.Enclosed;
+//import org.junit.runner.RunWith;
+import org.onap.music.main.DeadlockDetectionUtil.OwnershipType;
+
+//@RunWith(Enclosed.class)
+public class DeadlockDetectionUtilTest {
+ private DeadlockDetectionUtil ddu;
+
+ @Before
+ public void setup() {
+ ddu = new DeadlockDetectionUtil();
+ }
+
+ @Test
+ public void testListAllNodes() {
+ ddu = new DeadlockDetectionUtil();
+ ddu.setExisting("r1", "o2", OwnershipType.ACQUIRED);
+ ddu.setExisting("r3", "o2", OwnershipType.ACQUIRED);
+
+ ByteArrayOutputStream outContent = new ByteArrayOutputStream();
+ System.setOut(new PrintStream(outContent));
+ ddu.listAllNodes();
+
+ /*
+ * String expectedOutput = "In DeadlockDetectionUtil: \n" +
+ * " o2 : Node [id=o2, links=r3, visited=false, onStack=false]\n" +
+ * " r3 : Node [id=r3, links=, visited=false, onStack=false]\n" +
+ * " r1 : Node [id=r1, links=o2, visited=false, onStack=false]\n";
+ * assertEquals(expectedOutput, outContent.toString());
+ *
+ * ddu = new DeadlockDetectionUtil(); ddu.setExisting("111", "222",
+ * OwnershipType.CREATED); ddu.setExisting("333", "222", OwnershipType.CREATED);
+ * outContent = new ByteArrayOutputStream(); System.setOut(new
+ * PrintStream(outContent)); ddu.listAllNodes(); expectedOutput =
+ * "In DeadlockDetectionUtil: \n" +
+ * " o222 : Node [id=o222, links=r111r333, visited=false, onStack=false]\n" +
+ * " r333 : Node [id=r333, links=, visited=false, onStack=false]\n" +
+ * " r111 : Node [id=r111, links=, visited=false, onStack=false]";
+ * assertEquals(expectedOutput, outContent.toString());
+ */
+ }
+
+ @Test
+ public void testcheckForDeadlock() {
+ ddu = new DeadlockDetectionUtil();
+ ddu.setExisting("111", "222", DeadlockDetectionUtil.OwnershipType.ACQUIRED);
+ ddu.setExisting("333", "444", DeadlockDetectionUtil.OwnershipType.ACQUIRED);
+ assertEquals(false, ddu.checkForDeadlock("111", "444", DeadlockDetectionUtil.OwnershipType.CREATED));
+
+ ddu = new DeadlockDetectionUtil();
+ ddu.setExisting("111", "222", DeadlockDetectionUtil.OwnershipType.ACQUIRED);
+ ddu.setExisting("333", "444", DeadlockDetectionUtil.OwnershipType.ACQUIRED);
+ ddu.setExisting("333", "222", DeadlockDetectionUtil.OwnershipType.CREATED);
+ assertEquals(true, ddu.checkForDeadlock("111", "444", DeadlockDetectionUtil.OwnershipType.CREATED));
+ }
+}
diff --git a/music-core/src/test/java/org/onap/music/main/MusicCoreTest.java b/music-core/src/test/java/org/onap/music/main/MusicCoreTest.java
new file mode 100644
index 00000000..4714778b
--- /dev/null
+++ b/music-core/src/test/java/org/onap/music/main/MusicCoreTest.java
@@ -0,0 +1,391 @@
+/*******************************************************************************
+ * ============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.main;
+
+import static org.junit.Assert.assertEquals;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import javax.ws.rs.core.MultivaluedMap;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.mockito.internal.util.reflection.FieldSetter;
+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.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 MusicCoreTest {
+
+ MusicCore mCore;
+ MusicCoreService musicCore;
+ CassaLockStore mLockHandle;
+
+ @Before
+ public void setup() {
+ mCore = new MusicCore();
+ musicCore = Mockito.mock(MusicCoreService.class);
+ mLockHandle = Mockito.mock(CassaLockStore.class);
+ try {
+ FieldSetter.setField(mCore, mCore.getClass().getDeclaredField("musicCore"), musicCore);
+ } catch (NoSuchFieldException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ } catch (SecurityException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ @Test
+ public void testAcquireLock() throws MusicLockingException, MusicQueryException, MusicServiceException {
+ ReturnType returnType = Mockito.mock(ReturnType.class);
+ ReturnType result = null;
+ Mockito.when(musicCore.acquireLock(Mockito.any(), Mockito.any())).thenReturn(returnType);
+ result = MusicCore.acquireLock("key1", "lockid1");
+ assertEquals(returnType, result);
+ }
+
+ @Test
+ public void testacquireLockWithLease() throws MusicLockingException, MusicQueryException, MusicServiceException {
+ ReturnType returnType = Mockito.mock(ReturnType.class);
+ ReturnType result = null;
+ Mockito.when(musicCore.acquireLockWithLease(Mockito.anyString(), Mockito.anyString(), Mockito.anyLong()))
+ .thenReturn(returnType);
+ result = MusicCore.acquireLockWithLease("key1", "lockid1", 100L);
+ assertEquals(returnType, result);
+ }
+
+ @Test
+ public void testCreateLockReferenceAtomic() throws MusicLockingException {
+ String result = null;
+ Mockito.when(musicCore.createLockReferenceAtomic(Mockito.any())).thenReturn("lockreference1");
+ result = MusicCore.createLockReferenceAtomic("key2");
+ assertEquals("lockreference1", result);
+ }
+
+ @Test
+ public void testCreateLockReference() throws MusicLockingException {
+ String result = null;
+ Mockito.when(musicCore.createLockReference(Mockito.any(), Mockito.any())).thenReturn("lockreference2");
+ result = MusicCore.createLockReference("key3", "owner3");
+ assertEquals("lockreference2", result);
+ }
+
+ @Test
+ public void testCreateLockReferenceAtomic2() throws MusicLockingException {
+ String result = null;
+ Mockito.when(musicCore.createLockReferenceAtomic(Mockito.any(), Mockito.any())).thenReturn("lockreference3");
+ result = MusicCore.createLockReferenceAtomic("key4", LockType.READ);
+ assertEquals("lockreference3", result);
+ }
+
+ @Test
+ public void testCreateLockReference2() throws MusicLockingException {
+ String result = null;
+ Mockito.when(musicCore.createLockReference(Mockito.any(), Mockito.any(), Mockito.any()))
+ .thenReturn("lockreference4");
+ result = MusicCore.createLockReference("key4", LockType.READ, "owner4");
+ assertEquals("lockreference4", result);
+ }
+
+ @Test
+ public void testCreateTable() throws MusicServiceException {
+ ResultType resultType = Mockito.mock(ResultType.class);
+ ResultType result = null;
+ Mockito.when(musicCore.createTable(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
+ .thenReturn(resultType);
+ result = MusicCore.createTable("keyspace1", "table1", new PreparedQueryObject(), "consistency");
+ assertEquals(resultType, result);
+ }
+
+ @Test
+ public void testQuorumGet() {
+ ResultSet rs = Mockito.mock(ResultSet.class);
+ Mockito.when(musicCore.quorumGet(Mockito.any())).thenReturn(rs);
+ assertEquals(rs, MusicCore.quorumGet(new PreparedQueryObject()));
+ }
+
+ @Test
+ public void testWhoseTurnIsIt() {
+ Mockito.when(musicCore.whoseTurnIsIt(Mockito.any())).thenReturn("turn");
+ assertEquals("turn", MusicCore.whoseTurnIsIt("key5"));
+ }
+
+ @Test
+ public void testGetCurrentLockHolders() {
+ List<String> result = Mockito.mock(List.class);
+ Mockito.when(musicCore.getCurrentLockHolders(Mockito.any())).thenReturn(result);
+ assertEquals(result, MusicCore.getCurrentLockHolders("key6"));
+ }
+
+ @Test
+ public void testPromoteLock() throws MusicLockingException {
+ ReturnType returnType = Mockito.mock(ReturnType.class);
+ ReturnType result = null;
+ Mockito.when(musicCore.promoteLock(Mockito.any())).thenReturn(returnType);
+ result = MusicCore.promoteLock("lockid2");
+ assertEquals(returnType, result);
+ }
+
+ @Test
+ public void testEventualPut() {
+ ReturnType returnType = Mockito.mock(ReturnType.class);
+ Mockito.when(musicCore.eventualPut(Mockito.any())).thenReturn(returnType);
+ assertEquals(returnType, MusicCore.eventualPut(new PreparedQueryObject()));
+ }
+
+ @Test
+ public void testEventualPut_nb() {
+ ReturnType returnType = Mockito.mock(ReturnType.class);
+ Mockito.when(musicCore.eventualPut_nb(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
+ .thenReturn(returnType);
+ assertEquals(returnType,
+ MusicCore.eventualPut_nb(new PreparedQueryObject(), "keyspace2", "table2", "primarykey1"));
+ }
+
+ @Test
+ public void testCriticalPut() {
+ ReturnType returnType = Mockito.mock(ReturnType.class);
+ Mockito.when(musicCore.criticalPut(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(),
+ Mockito.any())).thenReturn(returnType);
+ assertEquals(returnType, MusicCore.criticalPut("keyspace3", "table3", "primarykey2", new PreparedQueryObject(),
+ "lockreference2", new Condition(new HashMap(), new PreparedQueryObject())));
+ }
+
+ @Test
+ public void testNonKeyRelatedPut() throws MusicServiceException, MusicQueryException {
+ ResultType resultType = Mockito.mock(ResultType.class);
+ ResultType result = null;
+ Mockito.when(musicCore.nonKeyRelatedPut(Mockito.any(), Mockito.any())).thenReturn(resultType);
+ result = MusicCore.nonKeyRelatedPut(new PreparedQueryObject(), "consistency2");
+ assertEquals(resultType, result);
+ }
+
+ @Test
+ public void testGet() throws MusicServiceException {
+ ResultSet rs = Mockito.mock(ResultSet.class);
+ ResultSet result = null;
+ Mockito.when(musicCore.get(Mockito.any())).thenReturn(rs);
+ result = MusicCore.get(new PreparedQueryObject());
+ assertEquals(rs, result);
+ }
+
+ @Test
+ public void testCriticalGet() throws MusicServiceException {
+ ResultSet rs = Mockito.mock(ResultSet.class);
+ ResultSet result = null;
+ Mockito.when(musicCore.criticalGet(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
+ .thenReturn(rs);
+ result = MusicCore.criticalGet("keyspace4", "table4", "primarykey3", new PreparedQueryObject(),
+ "lockreference3");
+ assertEquals(rs, result);
+ }
+
+ @Test
+ public void testAtomicPut() throws MusicLockingException, MusicQueryException, MusicServiceException {
+ ReturnType returnType = Mockito.mock(ReturnType.class);
+ ReturnType result = null;
+ Mockito.when(musicCore.atomicPut(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
+ .thenReturn(returnType);
+ result = MusicCore.atomicPut("keyspace5", "table5", "primarykey4", new PreparedQueryObject(),
+ new Condition(new HashMap(), new PreparedQueryObject()));
+ assertEquals(returnType, result);
+ }
+
+ @Test
+ public void testAtomicGet() throws MusicServiceException, MusicLockingException, MusicQueryException {
+ ResultSet rs = Mockito.mock(ResultSet.class);
+ ResultSet result = null;
+ Mockito.when(musicCore.atomicGet(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(rs);
+ result = MusicCore.atomicGet("keyspace5", "table5", "primarykey4", new PreparedQueryObject());
+ assertEquals(rs, result);
+ }
+
+ @Test
+ public void testGetLockQueue() throws MusicServiceException, MusicQueryException, MusicLockingException {
+ List<String> result = Mockito.mock(List.class);
+ List<String> rst = null;
+ Mockito.when(musicCore.getLockQueue(Mockito.any())).thenReturn(result);
+ rst = MusicCore.getLockQueue("key5");
+ assertEquals(result, rst);
+ }
+
+ @Test
+ public void testGetLockQueueSize() throws MusicServiceException, MusicQueryException, MusicLockingException {
+ long result = 0L;
+ Mockito.when(musicCore.getLockQueueSize(Mockito.any())).thenReturn(100L);
+ result = MusicCore.getLockQueueSize("key6");
+ assertEquals(100L, result);
+ }
+
+ @Test
+ public void testatomicPutWithDeleteLock() throws MusicLockingException {
+ ReturnType returnType = Mockito.mock(ReturnType.class);
+ ReturnType result = null;
+ Mockito.when(musicCore.atomicPutWithDeleteLock(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(),
+ Mockito.any())).thenReturn(returnType);
+ result = MusicCore.atomicPutWithDeleteLock("keyspace5", "table5", "primarykey4", new PreparedQueryObject(),
+ new Condition(new HashMap(), new PreparedQueryObject()));
+ assertEquals(returnType, result);
+ }
+
+ @Test
+ public void testAtomicGetWithDeleteLock() throws MusicServiceException, MusicLockingException {
+ ResultSet rs = Mockito.mock(ResultSet.class);
+ ResultSet result = null;
+ Mockito.when(musicCore.atomicGetWithDeleteLock(Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()))
+ .thenReturn(rs);
+ result = MusicCore.atomicGetWithDeleteLock("keyspace5", "table5", "primarykey4", new PreparedQueryObject());
+ assertEquals(rs, result);
+ }
+
+ @Test
+ public void testValidateLock() {
+ Map<String, Object> map = Mockito.mock(Map.class);
+ Mockito.when(musicCore.validateLock(Mockito.any())).thenReturn(map);
+ assertEquals(map, MusicCore.validateLock("lockname"));
+ }
+
+ @Test
+ public void testReleaseLock() throws MusicLockingException {
+ MusicLockState musicLockState = Mockito.mock(MusicLockState.class);
+ MusicLockState result = null;
+ Mockito.when(musicCore.releaseLock(Mockito.anyString(), Mockito.anyBoolean())).thenReturn(musicLockState);
+ result = MusicCore.releaseLock("lockid", true);
+ assertEquals(musicLockState, result);
+ }
+
+ @Test
+ public void testReleaseAllLocksForOwner() throws MusicLockingException, MusicServiceException, MusicQueryException {
+ List<String> result = Mockito.mock(List.class);
+ List<String> rst = null;
+ Mockito.when(musicCore.releaseAllLocksForOwner(Mockito.any(), Mockito.any(), Mockito.any())).thenReturn(result);
+ rst = MusicCore.releaseAllLocksForOwner("owner2", "keyspace6", "table6");
+ assertEquals(result, rst);
+ }
+
+ @Test
+ public void testCreateKeyspace() throws MusicServiceException, MusicQueryException {
+ ResultType resultType = Mockito.mock(ResultType.class);
+ ResultType result = null;
+ Mockito.when(musicCore.createKeyspace(Mockito.any(), Mockito.any())).thenReturn(resultType);
+ result = MusicCore.createKeyspace(new JsonKeySpace(), "consistency3");
+ assertEquals(resultType, result);
+ }
+
+ @Test
+ public void testDropKeyspace() throws MusicServiceException, MusicQueryException {
+ ResultType resultType = Mockito.mock(ResultType.class);
+ ResultType result = null;
+ Mockito.when(musicCore.dropKeyspace(Mockito.any(), Mockito.any())).thenReturn(resultType);
+ result = MusicCore.dropKeyspace(new JsonKeySpace(), "consistency4");
+ assertEquals(resultType, result);
+ }
+
+ @Test
+ public void testCreateTable2() throws MusicServiceException, MusicQueryException {
+ ResultType resultType = Mockito.mock(ResultType.class);
+ ResultType result = null;
+ Mockito.when(musicCore.createTable(Mockito.any(), Mockito.any())).thenReturn(resultType);
+ result = MusicCore.createTable(new JsonTable(), "consistency5");
+ assertEquals(resultType, result);
+ }
+
+ @Test
+ public void testDropTable() throws MusicServiceException, MusicQueryException {
+ ResultType resultType = Mockito.mock(ResultType.class);
+ ResultType result = null;
+ Mockito.when(musicCore.dropTable(Mockito.any(), Mockito.any())).thenReturn(resultType);
+ result = MusicCore.dropTable(new JsonTable(), "consistency5");
+ assertEquals(resultType, result);
+ }
+
+ @Test
+ public void testCreateIndex() throws MusicServiceException, MusicQueryException {
+ ResultType resultType = Mockito.mock(ResultType.class);
+ ResultType result = null;
+ Mockito.when(musicCore.createIndex(Mockito.any(), Mockito.any())).thenReturn(resultType);
+ result = MusicCore.createIndex(new JsonIndex("indexName", "keyspace7", "table7", "field"), "consistency6");
+ assertEquals(resultType, result);
+ }
+
+ @Test
+ public void testSelect() throws MusicServiceException, MusicQueryException {
+ ResultSet rs = Mockito.mock(ResultSet.class);
+ ResultSet result = null;
+ Mockito.when(musicCore.select(Mockito.any(), Mockito.any())).thenReturn(rs);
+ MultivaluedMap<String, String> map = Mockito.mock(MultivaluedMap.class);
+ result = MusicCore.select(new JsonSelect(), map);
+ assertEquals(rs, result);
+ }
+
+ @Test
+ public void testSelectCritical() throws MusicLockingException, MusicQueryException, MusicServiceException {
+ ResultSet rs = Mockito.mock(ResultSet.class);
+ ResultSet result = null;
+ Mockito.when(musicCore.selectCritical(Mockito.any(), Mockito.any())).thenReturn(rs);
+ MultivaluedMap<String, String> map = Mockito.mock(MultivaluedMap.class);
+ result = MusicCore.selectCritical(new JsonInsert(), map);
+ assertEquals(rs, result);
+ }
+
+ @Test
+ public void testInsertIntoTable() throws MusicLockingException, MusicQueryException, MusicServiceException {
+ ReturnType returnType = Mockito.mock(ReturnType.class);
+ ReturnType result = null;
+ Mockito.when(musicCore.insertIntoTable(Mockito.any())).thenReturn(returnType);
+ result = MusicCore.insertIntoTable(new JsonInsert());
+ assertEquals(returnType, result);
+ }
+
+ @Test
+ public void testUpdateTable() throws MusicLockingException, MusicQueryException, MusicServiceException {
+ ReturnType returnType = Mockito.mock(ReturnType.class);
+ ReturnType result = null;
+ Mockito.when(musicCore.updateTable(Mockito.any(), Mockito.any())).thenReturn(returnType);
+ MultivaluedMap<String, String> map = Mockito.mock(MultivaluedMap.class);
+ result = MusicCore.updateTable(new JsonUpdate(), map);
+ assertEquals(returnType, result);
+ }
+
+ @Test
+ public void testDeleteFromTable() throws MusicLockingException, MusicQueryException, MusicServiceException {
+ ReturnType returnType = Mockito.mock(ReturnType.class);
+ ReturnType result = null;
+ MultivaluedMap<String, String> map = Mockito.mock(MultivaluedMap.class);
+ Mockito.when(musicCore.deleteFromTable(Mockito.any(), Mockito.any())).thenReturn(returnType);
+ result = MusicCore.deleteFromTable(new JsonDelete(), map);
+ assertEquals(returnType, result);
+ }
+}
diff --git a/src/test/java/org/onap/music/unittests/ResultTypeTest.java b/music-core/src/test/java/org/onap/music/main/ResultTypeTest.java
index 012629e0..d6ccc1f1 100644
--- a/src/test/java/org/onap/music/unittests/ResultTypeTest.java
+++ b/music-core/src/test/java/org/onap/music/main/ResultTypeTest.java
@@ -20,11 +20,10 @@
* ====================================================================
*/
-package org.onap.music.unittests;
+package org.onap.music.main;
import static org.junit.Assert.*;
import org.junit.Test;
-import org.onap.music.main.ResultType;
public class ResultTypeTest {
diff --git a/src/test/java/org/onap/music/unittests/ReturnTypeTest.java b/music-core/src/test/java/org/onap/music/main/ReturnTypeTest.java
index c22b0155..fbb5f84d 100644
--- a/src/test/java/org/onap/music/unittests/ReturnTypeTest.java
+++ b/music-core/src/test/java/org/onap/music/main/ReturnTypeTest.java
@@ -20,15 +20,14 @@
* ====================================================================
*/
-package org.onap.music.unittests;
+package org.onap.music.main;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.*;
import java.util.Map;
-import org.apache.tools.ant.filters.TokenFilter.ContainsString;
-import org.hamcrest.core.AnyOf;
+
import org.junit.Test;
-import org.onap.music.main.ResultType;
-import org.onap.music.main.ReturnType;
public class ReturnTypeTest {
diff --git a/music-core/src/test/java/org/onap/music/service/impl/MusicCassaCoreTest.java b/music-core/src/test/java/org/onap/music/service/impl/MusicCassaCoreTest.java
new file mode 100644
index 00000000..33debfaa
--- /dev/null
+++ b/music-core/src/test/java/org/onap/music/service/impl/MusicCassaCoreTest.java
@@ -0,0 +1,485 @@
+/*******************************************************************************
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ * Copyright (c) 2018 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.impl;
+
+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.junit.runner.RunWith;
+import org.mockito.ArgumentCaptor;
+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.JsonKeySpace;
+import org.onap.music.datastore.jsonobjects.JsonTable;
+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.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;
+
+@RunWith(MockitoJUnitRunner.class)
+public class MusicCassaCoreTest {
+
+ @Mock
+ private CassaLockStore mLockHandle;
+
+ @Mock
+ private MusicDataStore dsHandle;
+
+ @Mock
+ private Session session;
+
+ MusicCassaCore core;
+
+ @Before
+ public void before() {
+ core = MusicCassaCore.getInstance();
+ MusicCassaCore.setmLockHandle(mLockHandle);
+ MusicDataStoreHandle.setMDstoreHandle(dsHandle);
+ Mockito.when(dsHandle.getSession()).thenReturn(session);
+ }
+
+ @Test
+ public void testGetmLockHandle() {
+ assertEquals(mLockHandle, MusicCassaCore.getmLockHandle());
+ }
+
+ @Test
+ public void testSetmLockHandle() {
+ CassaLockStore m2 = Mockito.mock(CassaLockStore.class);
+ MusicCassaCore.setmLockHandle(m2);
+ assertEquals(m2, MusicCassaCore.getmLockHandle());
+ //revert back to original handle
+ MusicCassaCore.setmLockHandle(mLockHandle);
+ }
+
+ @Test
+ public void testGetInstance() {
+ assertEquals(core, MusicCassaCore.getInstance());
+ }
+
+ @Test
+ public void testGetLockingServiceHandle() {
+ assertEquals(mLockHandle, MusicCassaCore.getmLockHandle());
+ }
+
+ @Test
+ public void testCreateLockReferenceAtomicString() throws Exception {
+ String fullyQualifiedKey = "keyspace.table.lockName";
+ Mockito.when(mLockHandle.genLockRefandEnQueue("keyspace", "table", "lockName", LockType.WRITE, null))
+ .thenReturn("lockReturned");
+
+ String lockRef = core.createLockReferenceAtomic(fullyQualifiedKey);
+
+ Mockito.verify(mLockHandle).genLockRefandEnQueue("keyspace", "table", "lockName", LockType.WRITE, null);
+ assertEquals("lockReturned", lockRef);
+ }
+
+ @Test
+ public void testCreateLockReferenceStringString() throws Exception {
+ String fullyQualifiedKey = "keyspace.table.lockName";
+ String owner = "owner1";
+ Mockito.when(mLockHandle.genLockRefandEnQueue("keyspace", "table", "lockName", LockType.WRITE, owner))
+ .thenReturn("lockReturned");
+
+ String lockRef = core.createLockReference(fullyQualifiedKey, owner);
+
+ Mockito.verify(mLockHandle).genLockRefandEnQueue("keyspace", "table", "lockName", LockType.WRITE, owner);
+ assertEquals("lockReturned", lockRef);
+ }
+
+ @Test
+ public void testCreateLockReferenceAtomicStringLockType() throws Exception {
+ String fullyQualifiedKey = "keyspace.table.lockName";
+ Mockito.when(mLockHandle.genLockRefandEnQueue("keyspace", "table", "lockName", LockType.READ, null))
+ .thenReturn("lockReturned");
+
+ String lockRef = core.createLockReferenceAtomic(fullyQualifiedKey, LockType.READ);
+
+ Mockito.verify(mLockHandle).genLockRefandEnQueue("keyspace", "table", "lockName", LockType.READ, null);
+ assertEquals("lockReturned", lockRef);
+ }
+
+ @Test
+ public void testCreateLockReferenceStringLockTypeString() throws Exception {
+ String fullyQualifiedKey = "keyspace.table.lockName";
+ String owner = "owner1";
+ Mockito.when(mLockHandle.genLockRefandEnQueue("keyspace", "table", "lockName", LockType.READ, owner))
+ .thenReturn("lockReturned");
+
+ String lockRef = core.createLockReference(fullyQualifiedKey, LockType.READ, owner);
+
+ Mockito.verify(mLockHandle).genLockRefandEnQueue("keyspace", "table", "lockName", LockType.READ, owner);
+ assertEquals("lockReturned", lockRef);
+ }
+
+ @Test
+ public void testPromoteLock() throws Exception {
+ String lockId = "$keyspace.table.lockName$1";
+ Mockito.when(mLockHandle.promoteLock("keyspace", "table", "lockName", "1"))
+ .thenReturn(new ReturnType(ResultType.SUCCESS, "Lock Promoted"));
+
+ ReturnType rt = core.promoteLock(lockId);
+ assertEquals(ResultType.SUCCESS, rt.getResult());
+ assertEquals("Lock Promoted", rt.getMessage());
+ }
+
+ @Test
+ public void testAcquireLockWithLease() throws Exception {
+ String fullyQualifiedKey = "keyspace.table.lockName";
+ String lockId = "$keyspace.table.lockName$1";
+ long leasePeriod = 1000;
+ String currTime = String.valueOf(System.currentTimeMillis());
+ Mockito.when(mLockHandle.peekLockQueue("keyspace", "table", "lockName"))
+ .thenReturn(mLockHandle.new LockObject(true, lockId, currTime, currTime, LockType.WRITE, null));
+ Mockito.when(mLockHandle.getLockInfo("keyspace", "table", "lockName", "1"))
+ .thenReturn(mLockHandle.new LockObject(false, lockId, null, null, LockType.WRITE, null));
+
+ ReturnType rt = core.acquireLockWithLease(fullyQualifiedKey, lockId, leasePeriod);
+ assertEquals(ResultType.FAILURE, rt.getResult());
+ }
+
+ @Test
+ public void testAcquireLock() throws Exception {
+ String fullyQualifiedKey = "keyspace.table.lockName";
+ String lockId = "$keyspace.table.lockName$1";
+ Mockito.when(mLockHandle.getLockInfo("keyspace", "table", "lockName", "1"))
+ .thenReturn(mLockHandle.new LockObject(false, lockId, null, null, LockType.WRITE, null));
+
+ ReturnType rt = core.acquireLock(fullyQualifiedKey, lockId);
+
+ assertEquals(ResultType.FAILURE, rt.getResult());
+ Mockito.verify(mLockHandle).getLockInfo("keyspace", "table", "lockName", "1");
+ /*TODO: if we successfully acquire the lock we hit an error by trying to read MusicDatastoreHandle */
+ }
+
+ @Test
+ public void testWhoseTurnIsIt() throws Exception {
+ String fullyQualifiedKey = "keyspace.table.lockName";
+ Mockito.when(mLockHandle.peekLockQueue("keyspace", "table", "lockName"))
+ .thenReturn(mLockHandle.new LockObject(true, "1", "", "", LockType.WRITE, null));
+
+ String topOfQ = core.whoseTurnIsIt(fullyQualifiedKey);
+ System.out.println(topOfQ);
+
+ assertEquals("$"+fullyQualifiedKey+"$1", topOfQ);
+ }
+
+ @Test
+ public void testGetCurrentLockHolders() throws Exception {
+ String fullyQualifiedKey = "keyspace.table.lockName";
+ List<String> currentHolders = new ArrayList<>();
+ currentHolders.add("$"+fullyQualifiedKey+"$1");
+ currentHolders.add("$"+fullyQualifiedKey+"$2");
+ Mockito.when(mLockHandle.getCurrentLockHolders("keyspace", "table", "lockName"))
+ .thenReturn(currentHolders);
+
+ List<String> holders = core.getCurrentLockHolders(fullyQualifiedKey);
+
+ assertTrue(currentHolders.containsAll(holders) && holders.containsAll(currentHolders));
+ }
+
+ @Test
+ public void testGetLockNameFromId() {
+ String lockId = "$keyspace.table.lockName$1";
+ assertEquals("keyspace.table.lockName", core.getLockNameFromId(lockId));
+ }
+
+ @Test
+ public void testDestroyLockRefString() throws Exception {
+ String lockId = "$keyspace.table.lockName$1";
+
+ core.destroyLockRef(lockId);
+ Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "1", MusicUtil.getRetryCount());
+ }
+
+ @Test
+ public void testDestroyLockRefStringString() throws Exception {
+ String fullyQualifiedKey = "keyspace.table.lockName";
+ String lockReference = "1";
+
+ core.destroyLockRef(fullyQualifiedKey, lockReference);
+ Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "1", MusicUtil.getRetryCount());
+ }
+
+ @Test
+ public void testReleaseLock() throws Exception {
+ String lockId = "$keyspace.table.lockName$1";
+
+ core.releaseLock(lockId, true);
+
+ Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "1", MusicUtil.getRetryCount());
+ }
+
+ @Test
+ public void testVoluntaryReleaseLock() throws Exception {
+ String fullyQualifiedKey = "keyspace.table.lockName";
+ String lockReference = "1";
+
+ core.voluntaryReleaseLock(fullyQualifiedKey, lockReference);
+
+ Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "1", MusicUtil.getRetryCount());
+ }
+
+ @Test
+ public void testReleaseAllLocksForOwner() throws Exception {
+ List<String> ownersLocks = new ArrayList<>();
+ ownersLocks.add("lockName$1");
+ ownersLocks.add("lockName$2");
+ Mockito.when(mLockHandle.getAllLocksForOwner("ownerId", "keyspace", "table"))
+ .thenReturn(ownersLocks);
+
+ List<String> locksReleased = core.releaseAllLocksForOwner("ownerId", "keyspace", "table");
+
+ Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "1", MusicUtil.getRetryCount());
+ Mockito.verify(mLockHandle).deQueueLockRef("keyspace", "table", "lockName", "2", MusicUtil.getRetryCount());
+ assertTrue(ownersLocks.containsAll(locksReleased) && locksReleased.containsAll(ownersLocks));
+ }
+
+
+ @Test
+ public void testValidateLock() {
+ String lockId = "$keyspace.table.lockName$1";
+
+ assertFalse(core.validateLock(lockId).containsKey("Error"));
+ }
+
+ @Test
+ public void testGetLockQueue() throws Exception {
+ String fullyQualifiedKey = "keyspace.table.lockName";
+ List<String> myList = new ArrayList<>();
+ Mockito.when(mLockHandle.getLockQueue("keyspace", "table", "lockName"))
+ .thenReturn(myList);
+ List<String> theirList = core.getLockQueue(fullyQualifiedKey);
+
+ assertEquals(myList, theirList);
+ }
+
+ @Test
+ public void testGetLockQueueSize() throws Exception {
+ String fullyQualifiedKey = "keyspace.table.lockName";
+ Mockito.when(mLockHandle.getLockQueueSize("keyspace", "table", "lockName"))
+ .thenReturn((long) 23);
+ long theirSize = core.getLockQueueSize(fullyQualifiedKey);
+
+ assertEquals(23, theirSize);
+ }
+
+ @Test
+ public void testCreateTable() throws MusicServiceException, MusicQueryException {
+ String keyspaceName = "keyspace";
+ String tableName = "table";
+ JsonTable table = new JsonTable();
+ table.setTableName(tableName);
+ table.setKeyspaceName(keyspaceName);
+ Map<String, String> fields = new HashMap<>();
+ fields.put("employee", "text");
+ fields.put("salary", "int");
+ table.setFields(fields);
+ table.setPrimaryKey("employee");
+
+ Mockito.when(mLockHandle.createLockQueue(Mockito.matches(keyspaceName), Mockito.matches(tableName)))
+ .thenReturn(true);
+ Mockito.when(dsHandle.executePut(Mockito.any(PreparedQueryObject.class), Mockito.matches("eventual"))).thenReturn(true);
+ ResultType rs = core.createTable(table , "eventual");
+
+ assertEquals(ResultType.SUCCESS, rs);
+ }
+
+ @Test
+ public void testDropTable() throws MusicServiceException, MusicQueryException {
+ String keyspaceName = "keyspace";
+ String tableName = "table";
+ JsonTable table = new JsonTable();
+ table.setTableName(tableName);
+ table.setKeyspaceName(keyspaceName);
+
+ ArgumentCaptor<PreparedQueryObject> queryCaptor = ArgumentCaptor.forClass(PreparedQueryObject.class);
+ Mockito.when(dsHandle.executePut(queryCaptor.capture(), Mockito.matches("eventual"))).thenReturn(true);
+
+ ResultType rs = core.dropTable(table, "eventual");
+ assertEquals(ResultType.SUCCESS, rs);
+ assertEquals("DROP TABLE keyspace.table;", queryCaptor.getValue().getQuery());
+ }
+
+ @Test
+ public void testQuorumGet() throws MusicServiceException, MusicQueryException {
+ PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM EMPLOYEES;");
+ ResultSet rs = Mockito.mock(ResultSet.class);
+ Mockito.when(dsHandle.executeQuorumConsistencyGet(Mockito.same(query))).thenReturn(rs);
+ ResultSet returnedRs = core.quorumGet(query);
+
+ assertEquals(rs, returnedRs);
+ }
+
+ @Test
+ public void testForciblyReleaseLock() throws MusicServiceException, MusicQueryException, MusicLockingException {
+ String fullyQualifiedKey = "keyspace.table.lockName";
+ ArgumentCaptor<PreparedQueryObject> unsyncedQuery = ArgumentCaptor.forClass(PreparedQueryObject.class);
+ Mockito.doReturn(true).when(dsHandle).executePut(unsyncedQuery.capture(), Mockito.matches("critical"));
+ core.forciblyReleaseLock(fullyQualifiedKey, "123");
+
+ assertEquals("insert into keyspace.unsyncedKeys_table (key) values (?);",unsyncedQuery.getValue().getQuery());
+ }
+
+ @Test
+ public void testEventualPut() throws MusicServiceException, MusicQueryException {
+ PreparedQueryObject query = new PreparedQueryObject("INSERT INTO EMPLOYEES VALUES ('John', 1);");
+ Mockito.when(dsHandle.executePut(Mockito.same(query), Mockito.matches("eventual"))).thenReturn(true);
+
+ assertEquals(ResultType.SUCCESS, core.eventualPut(query).getResult());
+ }
+
+ @Test
+ public void testEventualPutNB() throws MusicServiceException, MusicQueryException {
+ String keyspace = "keyspace";
+ String table = "EMPLOYEES";
+ String primaryKey = "NAME";
+ PreparedQueryObject query = new PreparedQueryObject("INSERT INTO EMPLOYEES VALUES ('John', 1);");
+
+ ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class);
+ ResultSet rs = Mockito.mock(ResultSet.class);
+ Row row = Mockito.mock(Row.class);
+ Mockito.when(dsHandle.executeQuorumConsistencyGet(queryCapture.capture())).thenReturn(rs);
+ Mockito.when(rs.one()).thenReturn(row);
+
+ Mockito.when(dsHandle.executePut(queryCapture.capture(), Mockito.matches("eventual"))).thenReturn(true);
+
+ ReturnType rt = core.eventualPut_nb(query, keyspace, table, primaryKey);
+
+ assertEquals("SELECT guard FROM keyspace.lockq_EMPLOYEES WHERE key = ? ;",
+ queryCapture.getAllValues().get(0).getQuery());
+ assertEquals("INSERT INTO EMPLOYEES VALUES ('John', 1);", queryCapture.getAllValues().get(1).getQuery());
+
+ assertEquals(ResultType.SUCCESS, rt.getResult());
+ }
+
+ @Test
+ public void testCriticalPut() throws MusicServiceException, MusicQueryException {
+ String keyspace = "keyspace";
+ String table = "table";
+ String primaryKey = "lockName";
+ PreparedQueryObject query = new PreparedQueryObject("INSERT INTO TABLE VALUES ('John', 1);");
+ String lockId = "$keyspace.table.lockName$1";
+
+ Mockito.when(mLockHandle.getLockInfo("keyspace", "table", "lockName", "1"))
+ .thenReturn(mLockHandle.new LockObject(true, lockId, null, null, LockType.WRITE, null));
+
+ ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class);
+ Mockito.when(dsHandle.executePut(queryCapture.capture(), Mockito.matches("critical"))).thenReturn(true);
+ ReturnType rt = core.criticalPut(keyspace, table, primaryKey, query, lockId, null);
+
+ assertEquals(true, queryCapture.getValue().getQuery()
+ .startsWith("INSERT INTO TABLE VALUES ('John', 1) USING TIMESTAMP"));
+ assertEquals(ResultType.SUCCESS, rt.getResult());
+ }
+
+ @Test
+ public void testNonKeyRelatedPut() throws MusicServiceException, MusicQueryException {
+ PreparedQueryObject query = new PreparedQueryObject("INSERT INTO TABLE VALUES ('John', 1);");
+ String consistency = "eventual";
+ ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class);
+ Mockito.when(dsHandle.executePut(queryCapture.capture(), Mockito.matches(consistency))).thenReturn(true);
+
+ core.nonKeyRelatedPut(query, consistency);
+
+ assertEquals(query.getQuery(), queryCapture.getValue().getQuery());
+ }
+
+ @Test
+ public void testGet() throws MusicServiceException, MusicQueryException {
+ PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM EMPLOYEES;");
+ ResultSet rs = Mockito.mock(ResultSet.class);
+ Mockito.when(dsHandle.executeOneConsistencyGet(Mockito.same(query))).thenReturn(rs);
+ assertEquals(rs, core.get(query));
+ }
+
+ @Test
+ public void testCriticalGet() throws MusicServiceException, MusicQueryException {
+ String keyspace = "keyspace";
+ String table = "table";
+ String primaryKey = "lockName";
+ PreparedQueryObject query = new PreparedQueryObject("SELECT * FROM EMPLOYEES WHERE LOCKNAME='lockName';");
+ String lockId = "$keyspace.table.lockName$1";
+
+ Mockito.when(mLockHandle.getLockInfo("keyspace", "table", "lockName", "1"))
+ .thenReturn(mLockHandle.new LockObject(true, lockId, null, null, LockType.WRITE, null));
+
+ ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class);
+ ResultSet rs = Mockito.mock(ResultSet.class);
+ Mockito.when(dsHandle.executeQuorumConsistencyGet(queryCapture.capture())).thenReturn(rs);
+ assertEquals(rs, core.criticalGet(keyspace, table, primaryKey, query, lockId));
+ }
+
+ @Test
+ public void testCreateKeyspace() throws MusicServiceException, MusicQueryException {
+ String keyspace = "cycling";
+ JsonKeySpace ks = new JsonKeySpace();
+ ks.setKeyspaceName(keyspace);
+ ks.setDurabilityOfWrites("true");
+
+ Map<String, Object> replicationInfo = new HashMap<>();
+ replicationInfo.put("class", "SimpleStrategy");
+ replicationInfo.put("replication_factor", 1);
+ ks.setReplicationInfo(replicationInfo);
+ Map<String, String> consistencyInfo = new HashMap<>();
+ consistencyInfo.put("consistency", "quorum");
+ ks.setConsistencyInfo(consistencyInfo);
+
+ ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class);
+ Mockito.when(dsHandle.executePut(queryCapture.capture(), Mockito.matches("eventual"))).thenReturn(true);
+
+ core.createKeyspace(ks , "eventual");
+
+ assertEquals("CREATE KEYSPACE cycling WITH replication = {'replication_factor':1,'class':'SimpleStrategy'} AND durable_writes = true;",
+ queryCapture.getValue().getQuery());
+ }
+
+ @Test
+ public void testDropKeyspace() throws MusicServiceException, MusicQueryException {
+ String keyspace = "cycling";
+ JsonKeySpace ks = new JsonKeySpace();
+ ks.setKeyspaceName(keyspace);
+
+ ArgumentCaptor<PreparedQueryObject> queryCapture = ArgumentCaptor.forClass(PreparedQueryObject.class);
+ Mockito.when(dsHandle.executePut(queryCapture.capture(), Mockito.matches("eventual"))).thenReturn(true);
+
+ core.dropKeyspace(ks , "eventual");
+
+ assertEquals("DROP KEYSPACE cycling;", queryCapture.getValue().getQuery());
+ }
+}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/NameSpace.java b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JSONObjectTest.java
index 232353c1..7f6af4c5 100644
--- a/src/main/java/org/onap/music/datastore/jsonobjects/NameSpace.java
+++ b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JSONObjectTest.java
@@ -2,46 +2,43 @@
* ============LICENSE_START==========================================
* org.onap.music
* ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
+ * 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.datastore.jsonobjects;
-import java.util.List;
+package org.onap.music.unittests.jsonobjects;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
-public class NameSpace {
- private String name;
- private List<String> admin;
+import org.onap.music.datastore.jsonobjects.JSONObject;
- public List<String> getAdmin() {
- return admin;
- }
-
- public String getName() {
- return name;
- }
+public class JSONObjectTest {
+ private JSONObject jsonObject;
- public void setAdmin(List<String> admin) {
- this.admin = admin;
+ @Before
+ public void setUp() {
+ jsonObject = new JSONObject();
}
- public void setName(String name) {
- this.name = name;
+ @Test
+ public void testGetSetData() {
+ jsonObject.setData("data");
+ Assert.assertEquals("data", jsonObject.getData());
}
-
}
diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java
index 63f901c6..b7dfa075 100644
--- a/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java
+++ b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/JsonLeasedLockTest.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.unittests.jsonobjects;
import static org.junit.Assert.*;
@@ -43,11 +44,4 @@ public class JsonLeasedLockTest {
assertEquals(lease,jl.getLeasePeriod());
}
- @Test
- public void testGetNotifyUrl() {
- String url = "http://somewhere.com";
- jl.setNotifyUrl(url);
- assertEquals(url,jl.getNotifyUrl());
- }
-
}
diff --git a/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/MusicHealthCheckTest.java
index 0243232f..ceda3f3a 100644
--- a/src/test/java/org/onap/music/unittests/jsonobjects/JsonSelectTest.java
+++ b/music-core/src/test/java/org/onap/music/unittests/jsonobjects/MusicHealthCheckTest.java
@@ -2,7 +2,7 @@
* ============LICENSE_START==========================================
* org.onap.music
* ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
+ * 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.
@@ -19,23 +19,30 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.unittests.jsonobjects;
-import static org.junit.Assert.*;
-import java.util.HashMap;
-import java.util.Map;
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Before;
import org.junit.Test;
-import org.onap.music.datastore.jsonobjects.JsonSelect;
+import org.onap.music.eelf.healthcheck.MusicHealthCheck;
-public class JsonSelectTest {
+public class MusicHealthCheckTest {
+ private MusicHealthCheck musicHealthCheck;
+
+ @Before
+ public void setUp()
+ {
+ musicHealthCheck= new MusicHealthCheck();
+ }
+
@Test
- public void testGetConsistencyInfo() {
- JsonSelect js = new JsonSelect();
- Map<String, String> mapSs = new HashMap<>();
- mapSs.put("k1", "one");
- js.setConsistencyInfo(mapSs);
- assertEquals("one",js.getConsistencyInfo().get("k1"));
+ 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/src/main/resources/cache.ccf b/music-core/src/test/resources/cache.ccf
index acc6831c..e152ee8b 100644
--- a/src/main/resources/cache.ccf
+++ b/music-core/src/test/resources/cache.ccf
@@ -1,18 +1,11 @@
# DEFAULT CACHE REGION
-jcs.default=
+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.cacheattributes.UseMemoryShrinker=false
-jcs.default.cacheattributes.MaxMemoryIdleTime=3600
-jcs.default.cacheattributes.ShrinkerInterval=60
jcs.default.elementattributes=org.apache.commons.jcs.engine.ElementAttributes
-jcs.default.elementattributes.IsEternal=false
-jcs.default.elementattributes.MaxLife=21600
-jcs.default.elementattributes.IdleTime=1800
+jcs.default.elementattributes.IsEternal=true
jcs.default.elementattributes.IsSpool=true
-jcs.default.elementattributes.IsRemote=true
-jcs.default.elementattributes.IsLateral=true
# PRE-DEFINED CACHE REGIONS
jcs.region.musicCache=
@@ -51,6 +44,19 @@ 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/main/resources/logback.xml b/music-core/src/test/resources/logback.xml
index b75fcd85..6bc5fd5e 100644
--- a/src/main/resources/logback.xml
+++ b/music-core/src/test/resources/logback.xml
@@ -39,10 +39,12 @@
<property name="auditLogName" value="audit" />
<property name="debugLogName" value="debug" />
<property name="defaultPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n" />
- <property name="applicationLoggerPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %msg%n" />
+ <!-- <property name="applicationLoggerPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %msg%n" /> -->
+ <property name="applicationLoggerPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5level %X{keyspace} - %msg%n" />
<property name="auditLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
<property name="metricsLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
- <property name="errorLoggerPattern" value= "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %msg%n " />
+ <!-- <property name="errorLoggerPattern" value= "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %msg%n " /> -->
+ <property name="errorLoggerPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5level %X{keyspace} - %msg%n" />
<property name="debugLoggerPattern" value="%date{ISO8601,UTC}|%X{RequestId}| %msg%n" ></property>
<property name="logDirectory" value="${logDir}/${componentName}" />
<property name="debugLogDirectory" value="${debugDir}/${componentName}" />
@@ -53,7 +55,7 @@
</encoder> -->
<layout class="">
<pattern>
- %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
+ %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
</pattern>
</layout>
</appender>
@@ -61,7 +63,7 @@
<!-- ============================================================================ -->
<!-- EELF Appenders -->
<!-- ============================================================================ -->
- <appender name="EELF"
+<!-- <appender name="EELF"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${logDirectory}/${generalLogName}.log</file>
<rollingPolicy
@@ -73,12 +75,41 @@
</rollingPolicy>
<triggeringPolicy
class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
- <maxFileSize>5MB</maxFileSize>
+ <maxFileSize>100MB</maxFileSize>
</triggeringPolicy>
<encoder>
<pattern>${applicationLoggerPattern}</pattern>
</encoder>
- </appender>
+ </appender> -->
+
+ <!-- <appender name="EELF" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${generalLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
+ daily rollover
+ <fileNamePattern>${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
+ <maxFileSize>1GB</maxFileSize>
+ <maxHistory>5</maxHistory>
+ <totalSizeCap>5GB</totalSizeCap>
+ </rollingPolicy>
+ <encoder>
+ <pattern>${applicationLoggerPattern}</pattern>
+ </encoder>
+ </appender> -->
+
+
+ <appender name="EELF" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${generalLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
+ <!-- daily rollover -->
+ <fileNamePattern>${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
+ <maxFileSize>1GB</maxFileSize>
+ <maxHistory>5</maxHistory>
+ <totalSizeCap>5GB</totalSizeCap>
+ </rollingPolicy>
+ <encoder>
+ <pattern>${applicationLoggerPattern}</pattern>
+ </encoder>
+ </appender>
<appender name="asyncEELF" class="ch.qos.logback.classic.AsyncAppender">
<queueSize>256</queueSize>
@@ -106,7 +137,7 @@
<maxFileSize>5MB</maxFileSize>
</triggeringPolicy>
<encoder>
- <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n </pattern>
+ <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n </pattern>
</encoder>
</appender>
@@ -261,11 +292,11 @@
<root level="INFO">
<appender-ref ref="asyncEELF" />
- <appender-ref ref="STDOUT" />
+ <!-- <appender-ref ref="STDOUT" /> -->
</root>
<!-- Conductor Specific additions to squash WARNING and INFO -->
<logger name="com.datastax.driver.core.Cluster" level="ERROR"/>
- <logger name="org.onap.music.main.MusicCore" level="ERROR"/>
+ <logger name="org.onap.music.main.MusicCore" level="ERROR"/>
</configuration>
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/src/main/resources/project.properties b/music-core/src/test/resources/project.properties
index 199afa33..199afa33 100644
--- a/src/main/resources/project.properties
+++ b/music-core/src/test/resources/project.properties
diff --git a/distribution/README.md b/music-rest/distribution/README.md
index 8b137891..8b137891 100644
--- a/distribution/README.md
+++ b/music-rest/distribution/README.md
diff --git a/distribution/cassandra/Dockerfile b/music-rest/distribution/cassandra/Dockerfile
index fe13322c..fe13322c 100644
--- a/distribution/cassandra/Dockerfile
+++ b/music-rest/distribution/cassandra/Dockerfile
diff --git a/distribution/cassandra/cassandra.yaml b/music-rest/distribution/cassandra/cassandra.yaml
index fa7c74a6..fa7c74a6 100644
--- a/distribution/cassandra/cassandra.yaml
+++ b/music-rest/distribution/cassandra/cassandra.yaml
diff --git a/music-rest/distribution/cassandra/docker-entrypoint.sh b/music-rest/distribution/cassandra/docker-entrypoint.sh
new file mode 100644
index 00000000..34825bd2
--- /dev/null
+++ b/music-rest/distribution/cassandra/docker-entrypoint.sh
@@ -0,0 +1,107 @@
+#!/bin/bash
+set -e
+
+# first arg is `-f` or `--some-option`
+# or there are no args
+if [ "$#" -eq 0 ] || [ "${1#-}" != "$1" ]; then
+ set -- cassandra -f "$@"
+fi
+
+# allow the container to be started with `--user`
+if [ "$1" = 'cassandra' -a "$(id -u)" = '0' ]; then
+ chown -R cassandra /var/lib/cassandra /var/log/cassandra "$CASSANDRA_CONFIG"
+ exec gosu cassandra "$BASH_SOURCE" "$@"
+fi
+
+_ip_address() {
+ # scrape the first non-localhost IP address of the container
+ # in Swarm Mode, we often get two IPs -- the container IP, and the (shared) VIP, and the container IP should always be first
+ ip address | awk '
+ $1 == "inet" && $NF != "lo" {
+ gsub(/\/.+$/, "", $2)
+ print $2
+ exit
+ }
+ '
+}
+
+if [ "$1" = 'cassandra' ]; then
+ : ${CASSANDRA_RPC_ADDRESS='0.0.0.0'}
+
+ : ${CASSANDRA_LISTEN_ADDRESS='auto'}
+ if [ "$CASSANDRA_LISTEN_ADDRESS" = 'auto' ]; then
+ CASSANDRA_LISTEN_ADDRESS="$(_ip_address)"
+ fi
+
+echo "#############################################"
+echo "############## Update music.cql #############"
+echo "#############################################"
+
+ if [ "$CASSANDRA_BROADCAST_ADDRESS" = 'auto' ]; then
+ CASSANDRA_BROADCAST_ADDRESS="$(_ip_address)"
+ fi
+ if [ "${MUSIC_REPLICATION_FACTOR}" ]; then
+ sed -ri 's/REPLICATION_FACTOR/'${MUSIC_REPLICATION_FACTOR}'/' "$f"
+ fi
+done
+
+echo "#############################################"
+echo "############## Update music.cql #############"
+echo "#############################################"
+
+for f in /docker-entrypoint-initdb.d/a_music.cql; do
+ if [ "${MUSIC_REPLICATION_CLASS}" ]; then
+ sed -ri 's/REPLICATION_CLASS/'${MUSIC_REPLICATION_CLASS}'/' "$f"
+ fi
+ if [ "${MUSIC_REPLICATION_FACTOR}" ]; then
+ sed -ri 's/REPLICATION_FACTOR/'${MUSIC_REPLICATION_FACTOR}'/' "$f"
+ fi
+done
+
+echo "#############################################"
+echo "######Updating username and password #######"
+echo "#############################################"
+for f in /docker-entrypoint-initdb.d/b_pw.cql; do
+ if [ "${CASSUSER}" ]; then
+ sed -ri 's/CASSUSER/'${CASSUSER}'/' "$f"
+ fi
+ if [ "${CASSPASS}" ]; then
+ sed -ri 's/CASSPASS/'${CASSPASS}'/' "$f"
+ fi
+done
+
+echo "#############################################"
+echo "############## Let run cql's ################"
+echo "#############################################"
+for f in /docker-entrypoint-initdb.d/*; do
+ case "$f" in
+ *zzz*.cql)
+ echo "$0: running $f" && until $AM && cqlsh -u ${CASSUSER} -p ${CASSPASS} -f "$f";
+ do >&2 echo "Cassandra is unavailable - sleeping [${f}] $C";let C=C+1; sleep 5; done & ;;
+ *a_music.cql)
+ echo "$0: running $f" && until $PW && cqlsh -u ${CASSUSER} -p ${CASSPASS} -f "$f" && AM=true;
+ do >&2 echo "Cassandra is unavailable - sleeping [${f}] $D";let D=D+1; sleep 5; done & ;;
+ *b_pw.cql)
+ echo "$0: running $f" && until cqlsh -u cassandra -p cassandra -f "$f" && PW=true;
+ do >&2 echo "Cassandra is unavailable - sleeping [${f}] $E";let E=E+1; sleep 5; done & ;;
+ *) echo "$0: ignoring $f" ;;
+ esac
+
+ echo
+done
+
+
+echo "#############################################"
+echo "########### Running Password CQL ############"
+echo "#############################################"
+
+#echo "$0: running $f" &&
+#until cqlsh -u cassandra -p cassandra -f /pw.cql;
+#do >&2 echo "Cassandra is unavailable - sleeping"; sleep 10; done
+
+echo "#############################################"
+echo "########### Cassandra Running ###############"
+echo "#############################################"
+
+
+exec "$@" \ No newline at end of file
diff --git a/music-rest/distribution/cassandra_job/Dockerfile b/music-rest/distribution/cassandra_job/Dockerfile
new file mode 100644
index 00000000..937afdee
--- /dev/null
+++ b/music-rest/distribution/cassandra_job/Dockerfile
@@ -0,0 +1,30 @@
+#
+# ============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=============================================
+# ====================================================================
+
+#registry.hub.docker.com/
+FROM library/cassandra:3.11
+ENV DEF_USER=cassandra
+ENV DEF_PASS=cassandra
+COPY runcql.sh /
+RUN mkdir -p cql/extra && \
+ chmod 755 runcql.sh && \
+ chown cassandra runcql.sh
+CMD ["/runcql.sh"]
diff --git a/distribution/cassandra_job/admin.cql b/music-rest/distribution/cassandra_job/admin.cql
index 904a2bab..904a2bab 100644
--- a/distribution/cassandra_job/admin.cql
+++ b/music-rest/distribution/cassandra_job/admin.cql
diff --git a/distribution/cassandra_job/admin_pw.cql b/music-rest/distribution/cassandra_job/admin_pw.cql
index bbad8d1d..bbad8d1d 100644
--- a/distribution/cassandra_job/admin_pw.cql
+++ b/music-rest/distribution/cassandra_job/admin_pw.cql
diff --git a/music-rest/distribution/cassandra_job/runcql.sh b/music-rest/distribution/cassandra_job/runcql.sh
new file mode 100644
index 00000000..89396bfc
--- /dev/null
+++ b/music-rest/distribution/cassandra_job/runcql.sh
@@ -0,0 +1,112 @@
+#! /bin/bash
+#
+# ============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=============================================
+# ====================================================================
+
+if [ -z "$TIMEOUT" ]; then
+ TIMEOUT=10;
+fi
+if [ -z "$DELAY" ]; then
+ DELAY=60;
+fi
+TO="--request-timeout=$TIMEOUT"
+
+if [ $CASS_HOSTNAME ]; then
+ echo "Sleeping for $DELAY seconds before running cql";
+ sleep $DELAY;
+ >&2 echo "#############################################"
+ >&2 echo "############## Let run cql's ################"
+ >&2 echo "#############################################"
+ >&2 echo "Current Variables in play"
+ >&2 echo "Default User"
+ >&2 echo "DEF_USER="$DEF_USER
+ >&2 echo "DEF_PASS=***********"
+ >&2 echo "New User"
+ >&2 echo "USERNAME="$USERNAME
+ >&2 echo "PASSWORD=***********"
+ >&2 echo "TIMEOUT="$TIMEOUT
+ >&2 echo "Running cqlsh $TO -u cassandra -p cassandra -e \"describe keyspaces;\" ${CASS_HOSTNAME} ${PORT};"
+ if cqlsh $TO -u cassandra -p cassandra -e "describe keyspaces;" ${CASS_HOSTNAME} ${PORT};
+ then
+ >&2 echo "Cassandra user still avalable, will continue as usual";
+ else
+ CASSFAIL=true
+ >&2 echo "$DEF_USER failed, trying with $USERNAME"
+ if cqlsh $TO -u $USERNAME -p $PASSWORD -e "describe keyspaces;" ${CASS_HOSTNAME} ${PORT};
+ then
+ >&2 echo "Password $USERNAME in play, update Variables"
+ DEF_USER=$USERNAME
+ DEF_PASS=$PASSWORD
+ >&2 echo "DEF_USER="$DEF_USER
+ >&2 echo "DEF_PASS=***********"
+ if cqlsh $TO -u $USERNAME -p $PASSWORD -e "describe keyspaces;" ${CASS_HOSTNAME} ${PORT} | grep admin;
+ then
+ >&2 echo "Admin table exists, everything looks good"
+ exit 0;
+ else
+ >&2 echo "Admin does not exists but password has changed. Continue as usual with proper username set"
+ >&2 echo "DEF_USER=" $DEF_USER
+ fi
+ else
+ if [ $CASSFAIL ]; then
+ >&2 echo "$DEF_USER and $USERNAME fail. DB might need to be initialized again. This shouldn't have happend."
+ exit 1;
+ else
+ >&2 echo "Continue and as usual"
+ fi
+ fi
+ fi
+ >&2 echo "Running admin.cql file:"
+ >&2 echo "Running cqlsh -u $DEF_USER -p $DEF_PASS -f /cql/admin.cql ${CASS_HOSTNAME} ${PORT}"
+ sleep 1;
+ if cqlsh $TO -u $DEF_USER -p $DEF_PASS -f /cql/admin.cql ${CASS_HOSTNAME} ${PORT};
+ then
+ >&2 echo "Success - admin.cql - Admin keyspace created";
+ else
+ >&2 echo "Failure - admin.cql";
+ exit 0;
+ fi
+ >&2 echo "Running admin_pw.cql file:"
+ >&2 echo "Running cqlsh -u $DEF_USER -p $DEF_PASS -f /cql/admin_pw.cql ${CASS_HOSTNAME} ${PORT}"
+ sleep 1;
+ if cqlsh $TO -u $DEF_USER -p $DEF_PASS -f /cql/admin_pw.cql ${CASS_HOSTNAME} ${PORT};
+ then
+ >&2 echo "Success - admin_pw.cql - Password Changed";
+ else
+ >&2 echo "Failure - admin_pw.cql";
+ exit 0;
+ fi
+
+ >&2 echo "Running Test - look for admin keyspace:"
+ >&2 echo "Running cqlsh -u $USERNAME -p $PASSWORD -e "select * from system_auth.roles;" ${CASS_HOSTNAME} ${PORT}"
+ sleep 1;
+ if cqlsh $TO -u $USERNAME -p $PASSWORD -e "select * from system_auth.roles;" ${CASS_HOSTNAME} ${PORT}
+ then
+ >&2 echo "Success - running test";
+ else
+ >&2 echo "Failure - running test";
+ exit 0;
+ fi
+
+else
+ >&2 echo "Missing CASS_HOSTNAME";
+ exit 0;
+fi
+
diff --git a/distribution/cassandra_job/test.cql b/music-rest/distribution/cassandra_job/test.cql
index 196fea22..196fea22 100644
--- a/distribution/cassandra_job/test.cql
+++ b/music-rest/distribution/cassandra_job/test.cql
diff --git a/music-rest/distribution/music/Dockerfile b/music-rest/distribution/music/Dockerfile
new file mode 100644
index 00000000..9868ceee
--- /dev/null
+++ b/music-rest/distribution/music/Dockerfile
@@ -0,0 +1,35 @@
+#
+# ============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=============================================
+# ====================================================================
+
+FROM openjdk:8
+LABEL purpose="Springboot for MUSIC"
+RUN apt-get update && apt-get install -y netcat telnet vim vim-common curl
+RUN groupadd --gid 1000 music && useradd --gid 1000 --uid 1000 music
+RUN mkdir -p /opt/app/music/logs/MUSIC
+COPY MUSIC-SB.jar /opt/app/music
+COPY startup.sh /opt/app/music
+RUN mkdir -p /opt/app/music/logs && \
+ mkdir -p /opt/app/music/etc && \
+ chown -R music:music /opt/app/music/ && \
+ chmod 755 /opt/app/music/startup.sh
+USER music:music
+WORKDIR /opt/app/music
+CMD ["/opt/app/music/startup.sh"]
diff --git a/music-rest/distribution/music/startup.sh b/music-rest/distribution/music/startup.sh
new file mode 100644
index 00000000..98b3ae09
--- /dev/null
+++ b/music-rest/distribution/music/startup.sh
@@ -0,0 +1,68 @@
+#!/bin/bash
+#
+# ============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=============================================
+# ====================================================================
+
+echo "Running startup script to get password from certman"
+PWFILE=/opt/app/aafcertman/.password
+LOGFILE=/opt/app/music/logs/MUSIC/music-sb.log
+PROPS=/opt/app/music/etc/music-sb.properties
+LOGBACK=/opt/app/music/etc/logback.xml
+LOGGING=
+DEBUG_PROP=
+# Debug Setup. Uses env variables
+# DEBUG and DEBUG_PORT
+# DEBUG=true/false | DEBUG_PORT=<Port valie must be integer>
+if [ "${DEBUG}" == "true" ]; then
+ if [ "${DEBUG_PORT}" == "" ]; then
+ DEBUG_PORT=8000
+ fi
+ echo "Debug mode on"
+ DEBUG_PROP="-Xdebug -Xrunjdwp:server=y,transport=dt_socket,address=${DEBUG_PORT},suspend=n"
+fi
+
+# LOGBACK file: if /opt/app/music/etc/logback.xml exists thenuse that.
+if [ -f $LOGBACK ]; then
+ LOGGING="--logging.config=file:${LOGBACK}"
+fi
+
+# Get Passwords from /opt/app/aafcertman
+if [ -f $PWFILE ]; then
+ echo "Found ${PWFILE}" >> $LOGFILE
+ PASSWORD=$(cat ${PWFILE})
+ echo "#### Using Password from ${PWFILE} for Certs" >> ${LOGFILE}
+else
+ PASSWORD=changeit
+ echo "#### Using Default Password for Certs" >> ${LOGFILE}
+fi
+
+# If music-sb.properties exists in /opt/app/music/etc then use that to override the application.properties
+if [ -f $PROPS ]; then
+ # Run with different Property file
+ #echo "java ${DEBUG_PROP} -jar MUSIC.jar --spring.config.location=file:${PROPS} ${LOGGING} 2>&1 | tee ${LOGFILE}"
+ java ${DEBUG_PROP} ${JAVA_OPTS} -jar MUSIC-SB.jar ${SPRING_OPTS} --spring.config.location=file:${PROPS} ${LOGGING} 2>&1 | tee ${LOGFILE}
+else
+ #echo "java ${DEBUG_PROP} -jar MUSIC.jar --server.ssl.key-store-password=${PASSWORD} ${LOGGING} 2>&1 | tee ${LOGFILE}"
+ java ${DEBUG_PROP} ${JAVA_OPTS} -jar MUSIC-SB.jar ${SPRING_OPTS} --server.ssl.key-store-password="${PASSWORD}" ${LOGGING} 2>&1 | tee ${LOGFILE}
+fi
+
+
+
+
diff --git a/music-rest/pom.xml b/music-rest/pom.xml
new file mode 100755
index 00000000..9bcfd396
--- /dev/null
+++ b/music-rest/pom.xml
@@ -0,0 +1,385 @@
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
+ ============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=============================================
+ ====================================================================
+-->
+<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
+ <modelVersion>4.0.0</modelVersion>
+ <groupId>org.onap.music</groupId>
+ <artifactId>MUSIC-rest</artifactId>
+ <packaging>jar</packaging>
+ <version>3.2.40-SNAPSHOT</version>
+ <description>
+ This is the MUSIC Spring-based REST service.
+ </description>
+ <name>music-rest</name>
+
+ <parent>
+ <groupId>org.onap.music</groupId>
+ <artifactId>MUSIC</artifactId>
+ <version>3.2.40-SNAPSHOT</version>
+ </parent>
+
+ <properties>
+ <start-class>org.onap.music.MusicApplication</start-class>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <java.version>1.8</java.version>
+ <jersey1.version>1.19</jersey1.version>
+ <jersey2.version>2.25.1</jersey2.version>
+ <jaxrs.version>2.0.1</jaxrs.version>
+
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+ <!--nexus -->
+ <nexusproxy>https://nexus.onap.org</nexusproxy>
+ <onap.nexus.url>https://nexus.onap.org</onap.nexus.url>
+ <snapshotNexusPath>/content/repositories/snapshots/</snapshotNexusPath>
+ <releaseNexusPath>/content/repositories/releases/</releaseNexusPath>
+ <stagingNexusPath>/content/repositories/staging/</stagingNexusPath>
+ <sitePath>/content/sites/site/org/onap/music/${project.version}</sitePath>
+ <!--maven -->
+ <timestamp>${maven.build.timestamp}</timestamp>
+ <maven.build.timestamp.format>yyyy.MM.dd.HH.mm</maven.build.timestamp.format>
+ <!--skip checkstyle -->
+ <maven.check.skip>false</maven.check.skip>
+ <!--docker -->
+ <docker.tag>${project.version}-${timestamp}</docker.tag>
+ <docker.latest.tag>${project.version}-latest</docker.latest.tag>
+ <maven.compiler.source>1.8</maven.compiler.source>
+ <maven.compiler.target>1.8</maven.compiler.target>
+ </properties>
+
+ <dependencyManagement>
+ <dependencies>
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-dependencies</artifactId>
+ <version>2.1.1.RELEASE</version>
+ <type>pom</type>
+ <scope>import</scope>
+ </dependency>
+ </dependencies>
+ </dependencyManagement>
+
+ <dependencies>
+
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework.data</groupId>
+ <artifactId>spring-data-cassandra</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-jersey</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-web</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-tomcat</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-starter-test</artifactId>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework</groupId>
+ <artifactId>spring-aop</artifactId>
+ <scope>compile</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-autoconfigure</artifactId>
+ </dependency>
+ <dependency>
+ <groupId>org.aspectj</groupId>
+ <artifactId>aspectjweaver</artifactId>
+ <scope>compile</scope>
+ </dependency>
+ <!-- Springboot -->
+ <dependency>
+ <groupId>org.onap.music</groupId>
+ <artifactId>MUSIC-core</artifactId>
+ <version>3.2.40-SNAPSHOT</version>
+ </dependency>
+ <!-- Jersey -->
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-client</artifactId>
+ <version>${jersey1.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>javax.ws.rs</groupId>
+ <artifactId>jsr311-api</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-server</artifactId>
+ <version>${jersey1.version}</version>
+ </dependency>
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-json</artifactId>
+ <version>${jersey1.version}</version>
+ <exclusions>
+ <exclusion>
+ <groupId>org.codehaus.jackson</groupId>
+ <artifactId>jackson-jaxrs</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>com.sun.jersey</groupId>
+ <artifactId>jersey-servlet</artifactId>
+ <version>${jersey1.version}</version>
+ </dependency>
+ <!-- /Jersey -->
+ <!-- Testing -->
+ <dependency>
+ <groupId>junit</groupId>
+ <artifactId>junit</artifactId>
+ <version>4.12</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.cassandraunit</groupId>
+ <artifactId>cassandra-unit-spring</artifactId>
+ <version>3.5.0.1</version>
+ <scope>test</scope>
+ <exclusions>
+ <exclusion>
+ <groupId>org.slf4j</groupId>
+ <artifactId>slf4j-log4j12</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>ch.qos.logback</groupId>
+ <artifactId>logback-classic</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>org.cassandraunit</groupId>
+ <artifactId>cassandra-unit</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>io.dropwizard.metrics</groupId>
+ <artifactId>metrics-core</artifactId>
+ </exclusion>
+ <exclusion>
+ <groupId>com.addthis.metrics</groupId>
+ <artifactId>reporter-config-base</artifactId>
+ </exclusion>
+ </exclusions>
+ </dependency>
+ <dependency>
+ <groupId>org.cassandraunit</groupId>
+ <artifactId>cassandra-unit-shaded</artifactId>
+ <version>3.5.0.1</version>
+ <scope>test</scope>
+ </dependency>
+ <dependency>
+ <groupId>org.mockito</groupId>
+ <artifactId>mockito-core</artifactId>
+ <version>2.23.4</version>
+ <scope>test</scope>
+ </dependency>
+ <!-- /Testing -->
+ </dependencies>
+
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>org.springframework.boot</groupId>
+ <artifactId>spring-boot-maven-plugin</artifactId>
+ <version>2.1.1.RELEASE</version>
+ <configuration>
+ <mainClass>org.onap.music.MusicApplication</mainClass>
+ <outputDirectory>${project.basedir}/distribution/music/</outputDirectory>
+ <addResources>true</addResources>
+ <finalName>MUSIC-SB</finalName>
+ <excludes>
+ <exclude>
+ <groupId>javax.ws.rs</groupId>
+ <artifactId>jsr311-api</artifactId>
+ </exclude>
+ </excludes>
+ </configuration>
+ <executions>
+ <execution>
+ <phase>package</phase>
+ <goals>
+ <goal>repackage</goal>
+ </goals>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ <pluginManagement><!-- lock down plugins versions to avoid using Maven defaults (may be moved to parent pom) -->
+ <plugins>
+ <!-- clean lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#clean_Lifecycle -->
+ <plugin>
+ <artifactId>maven-clean-plugin</artifactId>
+ <version>3.1.0</version>
+ </plugin>
+ <!-- default lifecycle, jar packaging: see https://maven.apache.org/ref/current/maven-core/default-bindings.html#Plugin_bindings_for_jar_packaging -->
+ <plugin>
+ <artifactId>maven-resources-plugin</artifactId>
+ <version>3.0.2</version>
+ </plugin>
+ <plugin>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <version>3.8.0</version>
+ </plugin>
+ <plugin>
+ <artifactId>maven-surefire-plugin</artifactId>
+ <version>2.22.1</version>
+ </plugin>
+ <plugin>
+ <artifactId>maven-jar-plugin</artifactId>
+ <version>3.0.2</version>
+ </plugin>
+ <plugin>
+ <artifactId>maven-install-plugin</artifactId>
+ <version>2.5.2</version>
+ </plugin>
+ <plugin>
+ <artifactId>maven-deploy-plugin</artifactId>
+ <version>2.8.2</version>
+ </plugin>
+ <!-- site lifecycle, see https://maven.apache.org/ref/current/maven-core/lifecycles.html#site_Lifecycle -->
+ <plugin>
+ <artifactId>maven-site-plugin</artifactId>
+ <version>3.7.1</version>
+ </plugin>
+ <plugin>
+ <artifactId>maven-project-info-reports-plugin</artifactId>
+ <version>3.0.0</version>
+ </plugin>
+ </plugins>
+ </pluginManagement>
+ </build>
+ <profiles>
+ <profile>
+ <id>docker</id>
+ <build>
+ <plugins>
+ <plugin>
+ <groupId>io.fabric8</groupId>
+ <artifactId>docker-maven-plugin</artifactId>
+ <version>0.19.1</version>
+ <configuration>
+ <verbose>true</verbose>
+ <apiVersion>1.23</apiVersion>
+ <registry>nexus3.onap.org:10003</registry>
+ <images>
+ <!-- MUSIC War -->
+ <image>
+ <name>onap/music/music_sb</name>
+ <alias>docker_music</alias>
+ <build>
+ <cleanup>true</cleanup>
+ <tags>
+ <tag>${docker.tag}</tag>
+ <tag>${docker.latest.tag}</tag>
+ </tags>
+ <dockerFileDir>${project.basedir}/distribution/music</dockerFileDir>
+ </build>
+ </image>
+ <!-- Cassandra -->
+ <image>
+ <name>onap/music/cassandra_3_11</name>
+ <alias>docker_cassandra_sec</alias>
+ <build>
+ <cleanup>true</cleanup>
+ <tags>
+ <tag>${docker.tag}</tag>
+ <tag>${docker.latest.tag}</tag>
+ </tags>
+ <dockerFileDir>${project.basedir}/distribution/cassandra</dockerFileDir>
+ </build>
+ </image>
+ <!-- Cassandra Job -->
+ <image>
+ <name>onap/music/cassandra_job</name>
+ <alias>docker_cassandra_job</alias>
+ <build>
+ <cleanup>true</cleanup>
+ <tags>
+ <tag>${docker.tag}</tag>
+ <tag>${docker.latest.tag}</tag>
+ </tags>
+ <dockerFileDir>${project.basedir}/distribution/cassandra_job</dockerFileDir>
+ </build>
+ </image>
+ </images>
+ </configuration>
+ <executions>
+ <execution>
+ <id>clean-images</id>
+ <phase>pre-clean</phase>
+ <goals>
+ <goal>remove</goal>
+ </goals>
+ <configuration>
+ <removeAll>true</removeAll>
+ <image>music</image>
+ </configuration>
+ </execution>
+ <execution>
+ <id>generate-images</id>
+ <phase>package</phase>
+ <goals>
+ <goal>build</goal>
+ </goals>
+ </execution>
+ <execution>
+ <id>push-images</id>
+ <phase>deploy</phase>
+ <goals>
+ <goal>push</goal>
+ </goals>
+ <configuration>
+ <image>onap/music/music</image>
+ </configuration>
+ </execution>
+ </executions>
+ </plugin>
+ </plugins>
+ </build>
+ </profile>
+ <profile>
+ <id>default</id>
+ </profile>
+ </profiles>
+</project>
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..0fe354d9
--- /dev/null
+++ b/music-rest/src/main/java/org/onap/music/MusicApplication.java
@@ -0,0 +1,208 @@
+/*
+ * ============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.lockingservice.cassandra.LockCleanUpDaemon;
+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);
+
+ LockCleanUpDaemon daemon = new LockCleanUpDaemon();
+ daemon.setDaemon(true);
+ daemon.start();
+ }
+
+ @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<Filter> loggingFilterRegistration() throws ServletException {
+ logger.info("loggingFilterRegistration called for log filter..");
+ propertyLoader.loadProperties();
+ FilterRegistrationBean<Filter> 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<Filter> cadiFilterRegistration() throws ServletException {
+ logger.info("cadiFilterRegistration called for cadi filter..");
+ FilterRegistrationBean<Filter> 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<Filter> cadiFilterRegistrationForAuth() throws ServletException {
+ logger.info("cadiFilterRegistrationForAuth called for cadi auth filter..");
+ FilterRegistrationBean<Filter> 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<AAFPermission> getAAFPermissions(ServletRequest request) {
+ CadiWrap wrapReq = (CadiWrap) request;
+
+ List<Permission> perms = wrapReq.getPermissions(wrapReq.getUserPrincipal());
+ List<AAFPermission> 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<AAFPermission> filterNameSpacesAAFPermissions(String nameSpace,
+ List<AAFPermission> allPermissionsList) {
+ List<AAFPermission> list = new ArrayList<>();
+ for (Iterator<AAFPermission> 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<Pattern> 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<AAFPermission> 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<AAFPermission> 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<AAFPermission> 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<String> 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 <code>CadiAuthFilter</code> 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<String,Object> tableValues;
+ private Map<String,Object> casscadeColumnData;
+ private Map<String,Map<String,String>> conditions;
+
+ public Map<String, Object> getTableValues() {
+ return tableValues;
+ }
+ public void setTableValues(Map<String, Object> tableValues) {
+ this.tableValues = tableValues;
+ }
+
+ public String getPrimaryKey() {
+ return primaryKey;
+ }
+ public String getPrimaryKeyValue() {
+ return primaryKeyValue;
+ }
+ public String getCasscadeColumnName() {
+ return casscadeColumnName;
+ }
+
+ public Map<String, Object> getCasscadeColumnData() {
+ return casscadeColumnData;
+ }
+
+
+
+ public void setPrimaryKey(String primaryKey) {
+ this.primaryKey = primaryKey;
+ }
+ public void setPrimaryKeyValue(String primaryKeyValue) {
+ this.primaryKeyValue = primaryKeyValue;
+ }
+ public Map<String, Map<String, String>> getConditions() {
+ return conditions;
+ }
+ public void setConditions(Map<String, Map<String, String>> conditions) {
+ this.conditions = conditions;
+ }
+ public void setCasscadeColumnName(String casscadeColumnName) {
+ this.casscadeColumnName = casscadeColumnName;
+ }
+
+ public void setCasscadeColumnData(Map<String, Object> 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..2c69c435
--- /dev/null
+++ b/music-rest/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java
@@ -0,0 +1,391 @@
+/*
+ * ============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<String, Object> casscadeColumnData, String primaryKey, Map<String, Object> valuesMap,
+ Map<String, String> status) throws Exception {
+
+ Map<String, PreparedQueryObject> 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<String, String> 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<String, String> 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.createLockReferenceAtomic(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<String, PreparedQueryObject> 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()) {
+ PreparedQueryObject qObject = queryBank.get(MusicUtil.INSERT);
+ qObject.setOperation(MusicUtil.INSERT);
+ logger.info(EELFLoggerDelegate.debugLogger,"### Conditional Insert");
+ MusicCore.criticalPut(keyspace, tableName, primaryKey, qObject, lockId, null);
+ //MusicDataStoreHandle.getDSHandle().executePut(queryBank.get(MusicUtil.INSERT), "critical");
+ return new ReturnType(ResultType.SUCCESS, MusicUtil.INSERT);
+
+ } else {
+ PreparedQueryObject qObject = queryBank.get(MusicUtil.UPDATE);
+ qObject.setOperation(MusicUtil.UPDATE);
+ logger.info(EELFLoggerDelegate.debugLogger,"### Condition Update");
+ MusicCore.criticalPut(keyspace, tableName, primaryKey, qObject, lockId, null);
+ //MusicDataStoreHandle.getDSHandle().executePut(queryBank.get(MusicUtil.UPDATE), "critical");
+ return new ReturnType(ResultType.SUCCESS, MusicUtil.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.createLockReferenceAtomic(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<String, String> 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 {
+ update.setOperation(MusicUtil.UPDATE);
+ MusicCore.criticalPut(dataObj.keyspace, dataObj.tableName, dataObj.primaryKeyValue, update, dataObj.lockId, null);
+ } 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());
+ }
+ PreparedQueryObject qObject = dataObj.getQueryBank().get(MusicUtil.UPSERT);
+ qObject.setOperation(MusicUtil.INSERT);
+ MusicCore.criticalPut(dataObj.keyspace, dataObj.tableName, dataObj.primaryKeyValue, qObject, dataObj.lockId, null);
+ 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<String, String> getValues(boolean isExists, Map<String, Object> casscadeColumnData,
+ Map<String, String> status) {
+
+ Map<String, String> returnMap = new HashMap<>();
+ Object key = casscadeColumnData.get("key");
+ String setStatus = "";
+ Map<String, String> value = (Map<String, String>) 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<String, Object> 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<String, Object> 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<String, String> cascadeColumnUpdateSpecific(Row row, Map<String, String> changeOfStatus,
+ String cascadeColumnName, String planId) {
+
+ ColumnDefinitions colInfo = row.getColumnDefinitions();
+ DataType colType = colInfo.getType(cascadeColumnName);
+ Object columnValue = getColValue(row, cascadeColumnName, colType);
+
+ Map<String, String> finalValues = new HashMap<>();
+ Map<String, String> values = (Map<String, String>) 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<String, Object> tableValues = jsonObj.getTableValues();
+ Map<String, Object> casscadeColumnData = jsonObj.getCasscadeColumnData();
+ Map<String, Map<String, String>> 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<String, Object> authMap = null;
+ Map<String, Object> valuesMap = new LinkedHashMap<>();
+ for (Map.Entry<String, Object> entry : tableValues.entrySet()) {
+ valuesMap.put(entry.getKey(), entry.getValue());
+ }
+
+ Map<String, String> 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<String, Object> casscadeColumnData = upObj.getCasscadeColumnData();
+ Map<String, Object> 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<String,String> casscadeColumnValueMap =
+ (Map<String, String>) 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<String,PreparedQueryObject> 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<String, PreparedQueryObject> queryBank;
+ String keyspace;
+ String tableName;
+ String primaryKey;
+ String primaryKeyValue;
+ String planId;
+ String cascadeColumnName;
+ Map<String, String> cascadeColumnValues;
+ String lockId;
+
+ public Map<String, PreparedQueryObject> getQueryBank() {
+ return queryBank;
+ }
+
+ public UpdateDataObject setQueryBank(Map<String, PreparedQueryObject> 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<String, String> getCascadeColumnValues() {
+ return cascadeColumnValues;
+ }
+
+ public UpdateDataObject setLockId(String lockId) {
+ this.lockId=lockId;
+ return this;
+ }
+
+ public String getLockId() {
+ return lockId;
+ }
+
+ public UpdateDataObject setCascadeColumnValues(Map<String, String> 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..acbbdd18
--- /dev/null
+++ b/music-rest/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java
@@ -0,0 +1,138 @@
+/*
+ * ============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 = nonKeyRelatedPut(pQuery, consistency);
+ logger.info(rs.toString());
+ return null != rs;
+
+ }
+
+ /*For unit testing purpose only*/
+ public ResultType nonKeyRelatedPut(PreparedQueryObject pQuery, String consistency) throws MusicServiceException, MusicQueryException {
+ return MusicCore.nonKeyRelatedPut(pQuery, consistency);
+ }
+
+ 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);
+ executeEventualPut(deleteQueryObject);
+ logger.info(EELFLoggerDelegate.applicationLogger, "Cassandra healthcheck responded and cleaned up.");
+ }
+
+ /*For unit testing purpose only*/
+ public void executeEventualPut(PreparedQueryObject deleteQueryObject) throws MusicServiceException, MusicQueryException {
+ MusicDataStoreHandle.getDSHandle().executePut(deleteQueryObject, "eventual");
+ }
+
+ 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..cda5b659
--- /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 <code>MusicApplication</code>
+ * 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<String, String> headerMap = null;
+ Map<String, String> 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<String, String> 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<String, String> getHeadersInfo(HttpServletRequest request) {
+
+ Map<String, String> map = new HashMap<String, String>();
+
+ Enumeration<String> 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/datastore/PreparedQueryObject.java b/music-rest/src/main/java/org/onap/music/exceptions/MusicAuthenticationException.java
index 694d9acd..ab44fd6e 100644
--- a/src/main/java/org/onap/music/datastore/PreparedQueryObject.java
+++ b/music-rest/src/main/java/org/onap/music/exceptions/MusicAuthenticationException.java
@@ -2,7 +2,7 @@
* ============LICENSE_START==========================================
* org.onap.music
* ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
+ * 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.
@@ -19,61 +19,57 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
-package org.onap.music.datastore;
-import java.util.ArrayList;
-import java.util.List;
+package org.onap.music.exceptions;
/**
- *
- * @author srupane
+ * @author inam
*
*/
-public class PreparedQueryObject {
-
-
- private List<Object> values;
- private StringBuilder query;
-
-
+public class MusicAuthenticationException extends Exception {
/**
*
*/
- public PreparedQueryObject() {
+ public MusicAuthenticationException() {
- this.values = new ArrayList<>();
- this.query = new StringBuilder();
}
/**
- * @return
+ * @param message
*/
- public List<Object> getValues() {
- return values;
+ public MusicAuthenticationException(String message) {
+ super(message);
+
}
/**
- * @param o
+ * @param cause
*/
- public void addValue(Object o) {
- this.values.add(o);
+ public MusicAuthenticationException(Throwable cause) {
+ super(cause);
+
}
/**
- * @param s
+ * @param message
+ * @param cause
*/
- public void appendQueryString(String s) {
- this.query.append(s);
+ public MusicAuthenticationException(String message, Throwable cause) {
+ super(message, cause);
+
}
/**
- * @return
+ * @param message
+ * @param cause
+ * @param enableSuppression
+ * @param writableStackTrace
*/
- public String getQuery() {
- return this.query.toString();
- }
-
+ 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/MusicExceptionMapper.java b/music-rest/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java
index 14a23d1f..c31fcf73 100644
--- a/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java
+++ b/music-rest/src/main/java/org/onap/music/exceptions/MusicExceptionMapper.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.exceptions;
import java.io.EOFException;
@@ -36,18 +37,20 @@ public class MusicExceptionMapper implements ExceptionMapper<Exception> {
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) {
+ 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 {
+ 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();
+ 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..11dc51dd
--- /dev/null
+++ b/music-rest/src/main/java/org/onap/music/main/PropertiesLoader.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.main;
+
+import java.util.HashSet;
+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("${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("${cassandra.connecttimeoutms}")
+ public String cassandraConnectTimeOutMS;
+
+ @Value("${cassandra.readtimeoutms}")
+ public String cassandraReadTimeOutMS;
+
+ @Value("${cadi}")
+ public String isCadi;
+
+ @Value("${keyspace.active}")
+ public String isKeyspaceActive;
+
+ @Value("${retry.count}")
+ public String rertryCount;
+
+ @Value("${lock.daemon.sleeptime.ms}")
+ public String lockDaemonSleeptimems;
+
+ @Value("${keyspaces.for.lock.cleanup}")
+ public String keyspacesForLockCleanup;
+
+ @Value("${create.lock.wait.period.ms}")
+ private long createLockWaitPeriod;
+
+ @Value("${create.lock.wait.increment.ms}")
+ private int createLockWaitIncrement;
+
+ @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;
+
+ @SuppressWarnings("unused")
+ private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PropertiesLoader.class);
+
+ @Bean
+ public static PropertySourcesPlaceholderConfigurer propertyConfigInDev() {
+
+ 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 (cassandraConnectTimeOutMS != null && !cassandraConnectTimeOutMS.equals("${cassandra.connecttimeoutms}")) {
+ MusicUtil.setCassandraConnectTimeOutMS(Integer.parseInt(cassandraConnectTimeOutMS));
+ }
+ if (cassandraReadTimeOutMS != null && !cassandraReadTimeOutMS.equals("${cassandra.readtimeoutms}")) {
+ MusicUtil.setCassandraReadTimeOutMS(Integer.parseInt(cassandraReadTimeOutMS));
+ }
+ 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 (lockDaemonSleeptimems != null && !lockDaemonSleeptimems.equals("${lock.daemon.sleeptime.ms}")) {
+ MusicUtil.setLockDaemonSleepTimeMs(Long.parseLong(lockDaemonSleeptimems));
+ }
+ if (keyspacesForLockCleanup !=null && !keyspacesForLockCleanup.equals("${keyspaces.for.lock.cleanup}")) {
+ HashSet<String> keyspaces = new HashSet<>();
+ for (String keyspace: keyspacesForLockCleanup.split(",")) {
+ keyspaces.add(keyspace);
+ }
+ MusicUtil.setKeyspacesToCleanLocks(keyspaces);
+ }
+ 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);
+ }
+
+ if(createLockWaitPeriod!=0) {
+ MusicUtil.setCreateLockWaitPeriod(createLockWaitPeriod);
+ }
+
+ if(createLockWaitIncrement!=0) {
+ MusicUtil.setCreateLockWaitIncrement(createLockWaitIncrement);
+ }
+ }
+
+ 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("cassandra.connectTimeOutMS")!=null) {
+ MusicUtil.setCassandraConnectTimeOutMS(Integer.parseInt(properties.getProperty("cassandra.connecttimeoutms")));
+ }
+
+ if(properties.getProperty("cassandra.readTimeOutMS")!=null) {
+ MusicUtil.setCassandraReadTimeOutMS(Integer.parseInt(properties.getProperty("cassandra.readtimeoutms")));
+ }
+
+ 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
+
+ }
+
+ /* For unit testing purpose only*/
+ protected void setProperties() {
+ cassandraHost = "127.0.0.1";
+ debug = "true";
+ version = "x.x.x";
+ build = "y.y";
+ musicProperties = "property";
+ lockLeasePeriod = "5000";
+ cassandraUser = "user";
+ cassandraPassword = "password";
+ cassandraPort = "8007";
+ cassandraConnectTimeOutMS = "1000";
+ cassandraReadTimeOutMS = "1000";
+ isCadi = "true";
+ isKeyspaceActive = "true";
+ rertryCount = "20";
+ transIdPrefix = "transId-";
+ conversationIdPrefix = "conversation-";
+ clientIdPrefix = "clientId-";
+ messageIdPrefix = "messageId-";
+ transIdRequired = true;
+ conversationIdRequired = true;
+ clientIdRequired = true;
+ messageIdRequired = true;
+ musicAafNs = "ns";
+ cipherEncKey = "key";
+ }
+
+}
diff --git a/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java b/music-rest/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java
index a406afce..5ae49f5d 100644
--- a/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java
+++ b/music-rest/src/main/java/org/onap/music/response/jsonobjects/JsonResponse.java
@@ -3,6 +3,8 @@
* 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.
@@ -19,19 +21,17 @@
* ============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.MusicLockState.LockStatus;
+import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus;
import org.onap.music.main.ResultType;
-import org.powermock.core.spi.testresult.Result;
-import com.datastax.driver.core.ColumnDefinitions;
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.Row;
-import com.datastax.driver.core.ColumnDefinitions.Definition;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiModelProperty;
@@ -39,7 +39,7 @@ import io.swagger.annotations.ApiModelProperty;
@ApiModel(value = "JsonResponse", description = "General Response JSON")
public class JsonResponse {
- /* Status is required */
+ /* Status is required */
private ResultType status;
/* Standard informational fields */
@@ -48,6 +48,7 @@ public class JsonResponse {
/* versioning */
private String musicVersion;
+ private String musicBuild;
/* Data Fields */
private Map<String, HashMap<String, Object>> dataResult;
@@ -55,9 +56,9 @@ public class JsonResponse {
/* Locking fields */
private String lock;
private LockStatus lockStatus;
- private String lockHolder;
+ private List<String> lockHolders;
private String lockLease;
-
+ private boolean isLockHolders=false;
/**
* Create a JSONLock Response
@@ -69,7 +70,16 @@ public class JsonResponse {
this.status = status;
}
- /**
+ public boolean isLockHolders() {
+ return isLockHolders;
+ }
+
+ public JsonResponse setisLockHolders(boolean isLockHolders) {
+ this.isLockHolders = isLockHolders;
+ return this;
+ }
+
+ /**
*
* @return
*/
@@ -126,33 +136,52 @@ public class JsonResponse {
/**
- *
+ * .
* @return the music version
*/
public String getMusicVersion() {
- return this.musicVersion;
+ return this.musicVersion;
}
/**
- *
+ * .
* @param version of music
* @return
*/
public JsonResponse setMusicVersion(String version) {
- this.musicVersion = version;
- return this;
+ 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<String, HashMap<String, Object>> getDataResult() {
- return this.dataResult;
+ return this.dataResult;
}
public JsonResponse setDataResult(Map<String, HashMap<String, Object>> map) {
- this.dataResult = map;
- return this;
+ this.dataResult = map;
+ return this;
}
- /**
+ /**
*
* @return
*/
@@ -193,8 +222,8 @@ public class JsonResponse {
* @return the lockHolder
*/
@ApiModelProperty(value = "Holder of the Lock")
- public String getLockHolder() {
- return lockHolder;
+ public List<String> getLockHolder() {
+ return lockHolders;
}
/**
@@ -202,10 +231,15 @@ public class JsonResponse {
* @param lockHolder
*/
public JsonResponse setLockHolder(String lockHolder) {
- this.lockHolder = lockHolder;
+ this.lockHolders = new ArrayList<String>();
+ this.lockHolders.add(lockHolder);
return this;
}
+ public JsonResponse setLockHolder(List<String> lockHolders) {
+ this.lockHolders = lockHolders;
+ return this;
+ }
/**
@@ -231,22 +265,45 @@ public class JsonResponse {
public Map<String, Object> toMap() {
Map<String, Object> fullMap = new HashMap<>();
fullMap.put("status", status);
- if (error!=null) {fullMap.put("error", error);}
- if (message!=null) {fullMap.put("message", message);}
+ if (error != null && !"".equals(error)) {
+ fullMap.put("error", error);
+ }
+ if (message != null) {
+ fullMap.put("message", message);
+ }
- if (musicVersion!=null) {fullMap.put("version", musicVersion);}
+ if (musicVersion != null) {
+ fullMap.put("version", musicVersion);
+ }
- if (dataResult!=null) {
- fullMap.put("result", dataResult);
+ if (musicBuild != null) {
+ fullMap.put("build", musicBuild);
+ }
+
+ if (dataResult != null) {
+ fullMap.put("result", dataResult);
}
- if (lock!=null) {
- Map<String, Object> lockMap = new HashMap<>();
- if (lock!=null) {lockMap.put("lock", lock);}
- if (lockStatus!=null) {lockMap.put("lock-status", lockStatus);}
- if (lockHolder!=null) {lockMap.put("lock-holder", lockHolder);}
- if (lockLease!=null) {lockMap.put("lock-lease", lockLease);}
- fullMap.put("lock", lockMap);
+ if (lock != null) {
+ Map<String, Object> 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;
@@ -259,7 +316,7 @@ public class JsonResponse {
public String toString() {
return "JsonLockResponse [status=" + status + ", error=" + error + ", message=" + message
+ ", lock=" + lock + ", lockStatus=" + lockStatus + ", lockHolder="
- + 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 <keyspace> Created\","
+ + "\"status\" : \"SUCCESS\"}")
+ })),
+ @ApiResponse(code=400, message = "Failure",examples = @Example( value = {
+ @ExampleProperty(mediaType="application/json",value =
+ "{\"error\" : \"<errorMessage>\","
+ + "\"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 <keyspace> Deleted\","
+ + "\"status\" : \"SUCCESS\"}")
+ })),
+ @ApiResponse(code=400, message = "Failure",examples = @Example( value = {
+ @ExampleProperty(mediaType="application/json",value =
+ "{\"error\" : \"<errorMessage>\","
+ + "\"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 <tablename> Created under keyspace <keyspace>\","
+ + "\"status\" : \"SUCCESS\"}")
+ })),
+ @ApiResponse(code=400, message = "Failure",examples = @Example( value = {
+ @ExampleProperty(mediaType="application/json",value =
+ "{\"error\" : \"<errorMessage>\","
+ + "\"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 <keyspace>.<table>.<field>\","
+ + "\"status\" : \"SUCCESS\"}")
+ })),
+ @ApiResponse(code=400, message = "Failure",examples = @Example( value = {
+ @ExampleProperty(mediaType="application/json",value =
+ "{\"error\" : \"<errorMessage>\","
+ + "\"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<String, String> 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\" : \"<errorMessage>\","
+ + "\"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\" : \"<errorMessage>\","
+ + "\"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\" : \"<errorMessage>\","
+ + "\"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\" : \"<errorMessage>\","
+ + "\"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<String, String> 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<String, List<String>> entry : rowParams.entrySet()) {
+ String keyName = entry.getKey();
+ List<String> 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<String, Object> 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<String, Object> 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$<integer>\"},"
+ + "\"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<String, Object> 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$<integer>\"},"
+ + "\"message\" : \"<integer> 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<String, Object> 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$<integer>\","
+ + "\"lock-lease\" : \"6000\"},"
+ + "\"message\" : \"<integer> 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<String, Object> 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$<integer>\"}},"
+ + "\"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<String, Object> 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$<integer1>\",\"$keyspace.table.rowId$<integer2>\"]}},"
+ + "\"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<String, Object> 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<String> 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$<integer>\"},"
+ + "\"message\" : \"<integer> 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<String, Object> 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$<integer>\"},"
+ + "\"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<String, Object> 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<String,Object> 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<String, Object> 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<String, Object> 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..63b72cda
--- /dev/null
+++ b/music-rest/src/main/java/org/onap/music/rest/RestMusicQAPI.java
@@ -0,0 +1,443 @@
+/*
+ * ============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<String, String> 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<String, Object> 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<String, HashMap<String, Object>> 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<String ,String> 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<String, HashMap<String, Object>> 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/music-rest/src/main/java/org/onap/music/rest/RestMusicTestAPI.java
index 287fa176..c1c04b09 100644
--- a/src/main/java/org/onap/music/rest/RestMusicTestAPI.java
+++ b/music-rest/src/main/java/org/onap/music/rest/RestMusicTestAPI.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.rest;
import java.util.HashMap;
@@ -41,27 +42,29 @@ import io.swagger.annotations.ApiOperation;
@Path("/v{version: [0-9]+}/test")
@Api(value="Test Api")
public class RestMusicTestAPI {
-
- @SuppressWarnings("unused")
+
+ @SuppressWarnings("unused")
private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicTestAPI.class);
- /**
- * Returns a test JSON. This will confirm that REST is working.
- * @return
- */
- @GET
- @ApiOperation(value = "Get Test", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Map<String, HashMap<String, String>> simpleTests(
- @Context HttpServletResponse response) {
- response.addHeader("X-latestVersion",MusicUtil.getVersion());
- Map<String, HashMap<String, String>> testMap = new HashMap<>();
- for(int i=0; i < 3; i++){
- HashMap<String, String> innerMap = new HashMap<>();
- innerMap.put(i+"", i+1+"");
- innerMap.put(i+1+"", i+2+"");
- testMap.put(i+"", innerMap);
- }
- return testMap;
- }
+ /**
+ * 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<String, HashMap<String, String>> simpleTests(
+ @Context HttpServletResponse response) {
+ response.addHeader("X-latestVersion",MusicUtil.getVersion());
+ Map<String, HashMap<String, String>> testMap = new HashMap<>();
+ for(int i=0; i < 3; i++){
+ HashMap<String, String> 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/music-rest/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java
index b9754f61..8c86152e 100644
--- a/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java
+++ b/music-rest/src/main/java/org/onap/music/rest/RestMusicVersionAPI.java
@@ -3,6 +3,8 @@
* 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.
@@ -19,6 +21,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.rest;
import java.util.Map;
@@ -43,18 +46,37 @@ import io.swagger.annotations.ApiOperation;
@Api(value="Version Api")
public class RestMusicVersionAPI {
- private EELFLoggerDelegate logger =EELFLoggerDelegate.getLogger(RestMusicVersionAPI.class);
-
- /**
- * Get the version of MUSIC
- * @return
- */
- @GET
- @ApiOperation(value = "Get Version", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Map<String,Object> 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:" + MusicUtil.getVersion()).toMap();
- }
+ 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<String,Object> 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<String,Object> 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/application.properties b/music-rest/src/main/resources/application.properties
new file mode 100755
index 00000000..6fbe6326
--- /dev/null
+++ b/music-rest/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-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/src/main/java/org/onap/music/lockingservice/LockListener.java b/music-rest/src/test/java/org/onap/music/JerseyConfigTest.java
index 33188e60..d7475a9d 100644
--- a/src/main/java/org/onap/music/lockingservice/LockListener.java
+++ b/music-rest/src/test/java/org/onap/music/JerseyConfigTest.java
@@ -1,39 +1,39 @@
-/*
+/*******************************************************************************
* ============LICENSE_START==========================================
* org.onap.music
* ===================================================================
- * Copyright (c) 2017 AT&T Intellectual Property
+ * 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.lockingservice;
+ *******************************************************************************/
+package org.onap.music;
-/**
- * This class has two methods which are call back methods when a lock is acquired and when the lock
- * is released.
- *
- */
-public interface LockListener {
- /**
- * call back called when the lock is acquired
- */
- public void lockAcquired();
+import org.junit.Before;
+import org.junit.Test;
- /**
- * call back called when the lock is released.
- */
- public void lockReleased();
+public class JerseyConfigTest {
+ JerseyConfig jerseyConfig;
+
+ @Before
+ public void setup() {
+ jerseyConfig = new JerseyConfig();
+ }
+
+ @Test
+ public void testInitJerseyConfig() {
+ jerseyConfig.init();
+ }
}
diff --git a/music-rest/src/test/java/org/onap/music/conductor/conditionals/JsonConditionalTest.java b/music-rest/src/test/java/org/onap/music/conductor/conditionals/JsonConditionalTest.java
new file mode 100644
index 00000000..07c43114
--- /dev/null
+++ b/music-rest/src/test/java/org/onap/music/conductor/conditionals/JsonConditionalTest.java
@@ -0,0 +1,82 @@
+/*******************************************************************************
+ * ============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.conductor.conditionals;
+
+import static org.junit.Assert.assertEquals;
+import java.util.Map;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+
+public class JsonConditionalTest {
+
+ Map<String,Object> tableValues;
+ Map<String,Object> casscadeColumnData;
+ Map<String,Map<String,String>> conditions;
+ JsonConditional jsonConditional;
+
+ @Before
+ public void setup() {
+ tableValues = Mockito.mock(Map.class);
+ casscadeColumnData = Mockito.mock(Map.class);
+ conditions = Mockito.mock(Map.class);
+ jsonConditional = new JsonConditional();
+ }
+
+ @Test
+ public void testSetTableValues() {
+ jsonConditional.setTableValues(tableValues);
+ assertEquals(tableValues, jsonConditional.getTableValues());
+ }
+
+ @Test
+ public void testSetPrimaryKey() {
+ jsonConditional.setPrimaryKey("primarykey");
+ assertEquals("primarykey", jsonConditional.getPrimaryKey());
+ }
+
+ @Test
+ public void testSetPrimaryKeyValue() {
+ jsonConditional.setPrimaryKeyValue("primarykeyvalue");
+ assertEquals("primarykeyvalue", jsonConditional.getPrimaryKeyValue());
+ }
+
+ @Test
+ public void testSetCasscadeColumnName() {
+ jsonConditional.setCasscadeColumnName("columnname");
+ assertEquals("columnname", jsonConditional.getCasscadeColumnName());
+ }
+
+ @Test
+ public void testSetCasscadeColumnData() {
+ jsonConditional.setCasscadeColumnData(casscadeColumnData);
+ assertEquals(casscadeColumnData, jsonConditional.getCasscadeColumnData());
+ }
+
+ @Test
+ public void testSetConditions() {
+ jsonConditional.setConditions(conditions);
+ assertEquals(conditions, jsonConditional.getConditions());
+ }
+
+}
diff --git a/music-rest/src/test/java/org/onap/music/conductor/conditionals/UpdateDataObjectTest.java b/music-rest/src/test/java/org/onap/music/conductor/conditionals/UpdateDataObjectTest.java
new file mode 100644
index 00000000..b651f5e9
--- /dev/null
+++ b/music-rest/src/test/java/org/onap/music/conductor/conditionals/UpdateDataObjectTest.java
@@ -0,0 +1,98 @@
+/*******************************************************************************
+ * ============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.conductor.conditionals;
+
+import static org.junit.Assert.assertEquals;
+import java.util.Map;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.music.datastore.PreparedQueryObject;
+
+public class UpdateDataObjectTest {
+
+ UpdateDataObject updateDataObject;
+ Map<String, PreparedQueryObject> queryBank;
+ Map<String, String> cascadeColumnValues;
+
+ @Before
+ public void setup() {
+ updateDataObject = new UpdateDataObject();
+ queryBank = Mockito.mock(Map.class);
+ cascadeColumnValues = Mockito.mock(Map.class);
+ }
+
+ @Test
+ public void testSetQueryBank() {
+ updateDataObject.setQueryBank(queryBank);
+ assertEquals(queryBank, updateDataObject.getQueryBank());
+ }
+
+ @Test
+ public void testSetKeyspace() {
+ updateDataObject.setKeyspace("keyspace");
+ assertEquals("keyspace", updateDataObject.getKeyspace());
+ }
+
+ @Test
+ public void testSetTableName() {
+ updateDataObject.setTableName("table");
+ assertEquals("table", updateDataObject.getTableName());
+ }
+
+ @Test
+ public void testSetPrimaryKey() {
+ updateDataObject.setPrimaryKey("primarykey");
+ assertEquals("primarykey", updateDataObject.getPrimaryKey());
+ }
+
+ @Test
+ public void testSetPrimaryKeyValue() {
+ updateDataObject.setPrimaryKeyValue("primarykeyvalue");
+ assertEquals("primarykeyvalue", updateDataObject.getPrimaryKeyValue());
+ }
+
+ @Test
+ public void testSetPlanId() {
+ updateDataObject.setPlanId("planid");
+ assertEquals("planid", updateDataObject.getPlanId());
+ }
+
+ @Test
+ public void testSetCascadeColumnName() {
+ updateDataObject.setCascadeColumnName("columnname");
+ assertEquals("columnname", updateDataObject.getCascadeColumnName());
+ }
+
+ @Test
+ public void testSetCascadeColumnValues() {
+ updateDataObject.setCascadeColumnValues(cascadeColumnValues);
+ assertEquals(cascadeColumnValues, updateDataObject.getCascadeColumnValues());
+ }
+
+ @Test
+ public void testSetLockId() {
+ updateDataObject.setLockId("lockid");
+ assertEquals("lockid", updateDataObject.getLockId());
+ }
+}
diff --git a/music-rest/src/test/java/org/onap/music/eelf/healthcheck/MusicHealthCheckTest.java b/music-rest/src/test/java/org/onap/music/eelf/healthcheck/MusicHealthCheckTest.java
new file mode 100644
index 00000000..66290630
--- /dev/null
+++ b/music-rest/src/test/java/org/onap/music/eelf/healthcheck/MusicHealthCheckTest.java
@@ -0,0 +1,61 @@
+/*******************************************************************************
+ * ============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.eelf.healthcheck;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.doNothing;
+import static org.mockito.Mockito.doReturn;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.music.datastore.MusicDataStore;
+import org.onap.music.datastore.MusicDataStoreHandle;
+import org.onap.music.exceptions.MusicQueryException;
+import org.onap.music.exceptions.MusicServiceException;
+import org.onap.music.main.MusicCore;
+import org.onap.music.main.ResultType;
+
+public class MusicHealthCheckTest {
+
+ MusicHealthCheck musicHealthCheck;
+
+ @Before
+ public void setup() {
+ musicHealthCheck = new MusicHealthCheck();
+ }
+
+ @Test
+ public void testSetCassandrHost() {
+ musicHealthCheck.setCassandrHost("127.0.0.1");
+ assertEquals("127.0.0.1", musicHealthCheck.getCassandrHost());
+ }
+
+ @Test
+ public void testGetCassandraStatus() throws MusicServiceException, MusicQueryException {
+ MusicHealthCheck mHealthCheck = Mockito.spy(MusicHealthCheck.class);
+ doReturn(ResultType.SUCCESS).when(mHealthCheck).nonKeyRelatedPut(Mockito.any(), Mockito.anyString());
+ doNothing().when(mHealthCheck).executeEventualPut(Mockito.any());
+ assertEquals("ACTIVE", mHealthCheck.getCassandraStatus("consistency"));
+ }
+
+}
diff --git a/music-rest/src/test/java/org/onap/music/eelf/logging/MusicContainerFilterTest.java b/music-rest/src/test/java/org/onap/music/eelf/logging/MusicContainerFilterTest.java
new file mode 100644
index 00000000..cd7a9ca4
--- /dev/null
+++ b/music-rest/src/test/java/org/onap/music/eelf/logging/MusicContainerFilterTest.java
@@ -0,0 +1,55 @@
+/*******************************************************************************
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ * Copyright (c) 2019 AT&T Intellectual Property
+ * ===================================================================
+ * Modifications Copyright (C) 2020 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 javax.servlet.ServletException;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerResponseContext;
+import javax.ws.rs.container.ContainerResponseFilter;
+
+import org.springframework.stereotype.Component;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.music.main.MusicUtil;
+
+public class MusicContainerFilterTest {
+ MusicContainerFilter filter;
+
+ @Before
+ public void setup() throws IOException {
+ filter = new MusicContainerFilter();
+ }
+
+ @Test
+ public void testDoFilter() throws IOException {
+ ContainerResponseFilter fil=Mockito.mock(ContainerResponseFilter.class);
+ ContainerRequestContext req=Mockito.mock(ContainerRequestContext.class);
+ ContainerResponseContext res=Mockito.mock(ContainerResponseContext.class);
+ filter.filter(req,res);
+ }
+
+}
diff --git a/music-rest/src/test/java/org/onap/music/eelf/logging/MusicLoggingServletFilterTest.java b/music-rest/src/test/java/org/onap/music/eelf/logging/MusicLoggingServletFilterTest.java
new file mode 100644
index 00000000..8f5d4521
--- /dev/null
+++ b/music-rest/src/test/java/org/onap/music/eelf/logging/MusicLoggingServletFilterTest.java
@@ -0,0 +1,64 @@
+/*******************************************************************************
+ * ============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.eelf.logging;
+
+import static org.mockito.Mockito.doNothing;
+import java.io.IOException;
+import java.util.Enumeration;
+import javax.servlet.FilterChain;
+import javax.servlet.ServletException;
+import javax.servlet.ServletRequest;
+import javax.servlet.ServletResponse;
+import javax.servlet.http.HttpServletRequest;
+import javax.servlet.http.HttpServletResponse;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.music.main.MusicUtil;
+
+public class MusicLoggingServletFilterTest {
+ MusicLoggingServletFilter filter;
+
+ @Before
+ public void setup() throws ServletException {
+ filter = new MusicLoggingServletFilter();
+ }
+
+ @Test
+ public void testDoFilter() throws IOException, ServletException {
+ FilterChain chain = Mockito.mock(FilterChain.class);
+ Enumeration<String> headerNames = Mockito.mock(Enumeration.class);
+ HttpServletRequest httpRequest = Mockito.mock(HttpServletRequest.class);
+ HttpServletResponse httpResponse = Mockito.mock(HttpServletResponse.class);
+ Mockito.when(headerNames.hasMoreElements()).thenReturn(true).thenReturn(true).thenReturn(true).thenReturn(false);
+ Mockito.when(headerNames.nextElement()).thenReturn("element1").thenReturn("element2").thenReturn("element3");
+ Mockito.when(httpRequest.getHeader(Mockito.anyString())).thenReturn("key1").thenReturn("key2").thenReturn("key3");
+ Mockito.when(httpRequest.getHeaderNames()).thenReturn(headerNames);
+ MusicUtil.setTransIdRequired(false);
+ MusicUtil.setConversationIdRequired(false);
+ MusicUtil.setMessageIdRequired(false);
+ MusicUtil.setClientIdRequired(false);
+ doNothing().when(chain).doFilter(Mockito.any(), Mockito.any());
+ filter.doFilter(httpRequest, httpResponse, chain);
+ }
+
+}
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/main/PropertiesLoaderTest.java b/music-rest/src/test/java/org/onap/music/main/PropertiesLoaderTest.java
new file mode 100644
index 00000000..7c10e8f1
--- /dev/null
+++ b/music-rest/src/test/java/org/onap/music/main/PropertiesLoaderTest.java
@@ -0,0 +1,146 @@
+/*******************************************************************************
+ * ============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.main;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import java.util.Properties;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.music.rest.RestMusicVersionAPI;
+
+public class PropertiesLoaderTest {
+ PropertiesLoader propertiesLoader;
+
+ @Before
+ public void setup() {
+ propertiesLoader = new PropertiesLoader();
+ }
+
+ @Test
+ public void testLoadProperties() {
+ Properties properties = Mockito.mock(Properties.class);
+ Mockito.when(properties.getProperty("cassandra.host")).thenReturn("127.0.0.1");
+ Mockito.when(properties.getProperty("cassandra.port")).thenReturn("8007");
+ Mockito.when(properties.getProperty("cassandra.user")).thenReturn("user");
+ Mockito.when(properties.getProperty("cassandra.password")).thenReturn("password");
+ Mockito.when(properties.getProperty("music.properties")).thenReturn("property");
+ Mockito.when(properties.getProperty("debug")).thenReturn("true");
+ Mockito.when(properties.getProperty("version")).thenReturn("x.x.x");
+ Mockito.when(properties.getProperty("build")).thenReturn("y.y");
+ Mockito.when(properties.getProperty("lock.lease.period")).thenReturn("5000");
+ Mockito.when(properties.getProperty("cadi")).thenReturn("true");
+ Mockito.when(properties.getProperty("keyspace.active")).thenReturn("true");
+ Mockito.when(properties.getProperty("retry.count")).thenReturn("20");
+ Mockito.when(properties.getProperty("transId.header.prefix")).thenReturn("transId");
+ Mockito.when(properties.getProperty("conversation.header.prefix")).thenReturn("conversation");
+ Mockito.when(properties.getProperty("clientId.header.prefix")).thenReturn("clientId");
+ Mockito.when(properties.getProperty("messageId.header.prefix")).thenReturn("messageId");
+ Mockito.when(properties.getProperty("transId.header.required")).thenReturn("true");
+ Mockito.when(properties.getProperty("conversation.header.required")).thenReturn("true");
+ Mockito.when(properties.getProperty("clientId.header.required")).thenReturn("true");
+ Mockito.when(properties.getProperty("messageId.header.required")).thenReturn("true");
+ Mockito.when(properties.getProperty("music.aaf.ns")).thenReturn("ns");
+ Mockito.when(properties.getProperty("cipher.enc.key")).thenReturn("key");
+ CorePropertiesLoader.loadProperties(properties);
+ assertEquals("127.0.0.1", MusicUtil.getMyCassaHost());
+ assertEquals(8007, MusicUtil.getCassandraPort());
+ assertEquals("user", MusicUtil.getCassName());
+ assertEquals("password", MusicUtil.getCassPwd());
+ assertEquals("property", MusicUtil.getMusicPropertiesFilePath());
+ assertEquals(true, MusicUtil.isDebug());
+ assertEquals("x.x.x", MusicUtil.getVersion());
+ assertEquals("y.y", MusicUtil.getBuild());
+ assertEquals(5000L, MusicUtil.getDefaultLockLeasePeriod());
+ assertEquals(true, MusicUtil.getIsCadi());
+ assertEquals(true, MusicUtil.isKeyspaceActive());
+ assertEquals(20, MusicUtil.getRetryCount());
+ assertEquals("transId-", MusicUtil.getTransIdPrefix());
+ assertEquals("conversation-", MusicUtil.getConversationIdPrefix());
+ assertEquals("clientId-", MusicUtil.getClientIdPrefix());
+ assertEquals("messageId-", MusicUtil.getMessageIdPrefix());
+ assertEquals(true, MusicUtil.getTransIdRequired());
+ assertEquals(true, MusicUtil.getConversationIdRequired());
+ assertEquals(true, MusicUtil.getClientIdRequired());
+ assertEquals(true, MusicUtil.getMessageIdRequired());
+ assertEquals("ns", MusicUtil.getMusicAafNs());
+ assertEquals("key", MusicUtil.getCipherEncKey());
+
+ Mockito.when(properties.getProperty("cassandra.connecttimeoutms")).thenReturn("1000");
+ Mockito.when(properties.getProperty("cassandra.readtimeoutms")).thenReturn("1000");
+ Mockito.when(properties.getProperty("cassandra.connectTimeOutMS")).thenReturn("1000");
+ Mockito.when(properties.getProperty("cassandra.readTimeOutMS")).thenReturn("1000");
+ PropertiesLoader.loadProperties(properties);
+ assertEquals("127.0.0.1", MusicUtil.getMyCassaHost());
+ assertEquals(8007, MusicUtil.getCassandraPort());
+ assertEquals("user", MusicUtil.getCassName());
+ assertEquals("password", MusicUtil.getCassPwd());
+ assertEquals(1000, MusicUtil.getCassandraConnectTimeOutMS());
+ assertEquals(1000, MusicUtil.getCassandraReadTimeOutMS());
+ assertEquals("property", MusicUtil.getMusicPropertiesFilePath());
+ assertEquals(true, MusicUtil.isDebug());
+ assertEquals("x.x.x", MusicUtil.getVersion());
+ assertEquals("y.y", MusicUtil.getBuild());
+ assertEquals(5000L, MusicUtil.getDefaultLockLeasePeriod());
+ assertEquals(true, MusicUtil.getIsCadi());
+ assertEquals(true, MusicUtil.isKeyspaceActive());
+ assertEquals(20, MusicUtil.getRetryCount());
+ assertEquals("transId-", MusicUtil.getTransIdPrefix());
+ assertEquals("conversation-", MusicUtil.getConversationIdPrefix());
+ assertEquals("clientId-", MusicUtil.getClientIdPrefix());
+ assertEquals("messageId-", MusicUtil.getMessageIdPrefix());
+ assertEquals(true, MusicUtil.getTransIdRequired());
+ assertEquals(true, MusicUtil.getConversationIdRequired());
+ assertEquals(true, MusicUtil.getClientIdRequired());
+ assertEquals(true, MusicUtil.getMessageIdRequired());
+ assertEquals("ns", MusicUtil.getMusicAafNs());
+ assertEquals("key", MusicUtil.getCipherEncKey());
+
+ propertiesLoader.setProperties();
+ propertiesLoader.loadProperties();
+ assertEquals("127.0.0.1", MusicUtil.getMyCassaHost());
+ assertEquals(8007, MusicUtil.getCassandraPort());
+ assertEquals("user", MusicUtil.getCassName());
+ assertEquals("password", MusicUtil.getCassPwd());
+ assertEquals(1000, MusicUtil.getCassandraConnectTimeOutMS());
+ assertEquals(1000, MusicUtil.getCassandraReadTimeOutMS());
+ assertEquals("property", MusicUtil.getMusicPropertiesFilePath());
+ assertEquals(true, MusicUtil.isDebug());
+ assertEquals("x.x.x", MusicUtil.getVersion());
+ assertEquals("y.y", MusicUtil.getBuild());
+ assertEquals(5000L, MusicUtil.getDefaultLockLeasePeriod());
+ assertEquals(true, MusicUtil.getIsCadi());
+ assertEquals(true, MusicUtil.isKeyspaceActive());
+ assertEquals(20, MusicUtil.getRetryCount());
+ assertEquals("transId-", MusicUtil.getTransIdPrefix());
+ assertEquals("conversation-", MusicUtil.getConversationIdPrefix());
+ assertEquals("clientId-", MusicUtil.getClientIdPrefix());
+ assertEquals("messageId-", MusicUtil.getMessageIdPrefix());
+ assertEquals(true, MusicUtil.getTransIdRequired());
+ assertEquals(true, MusicUtil.getConversationIdRequired());
+ assertEquals(true, MusicUtil.getClientIdRequired());
+ assertEquals(true, MusicUtil.getMessageIdRequired());
+ assertEquals("ns", MusicUtil.getMusicAafNs());
+ assertEquals("key", MusicUtil.getCipherEncKey());
+ }
+}
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/rest/RestMusicTestAPITest.java b/music-rest/src/test/java/org/onap/music/rest/RestMusicTestAPITest.java
new file mode 100644
index 00000000..235367ce
--- /dev/null
+++ b/music-rest/src/test/java/org/onap/music/rest/RestMusicTestAPITest.java
@@ -0,0 +1,66 @@
+/*******************************************************************************
+ * ============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.rest;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.doNothing;
+import java.util.HashMap;
+import java.util.Map;
+import javax.servlet.http.HttpServletResponse;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.music.main.MusicUtil;
+
+public class RestMusicTestAPITest {
+
+ RestMusicTestAPI restMusicTestAPI;
+
+ @Before
+ public void setup() {
+ restMusicTestAPI = new RestMusicTestAPI();
+ }
+
+ @Test
+ public void testSimpleTests() {
+ HttpServletResponse httpServletResponse = Mockito.mock(HttpServletResponse.class);
+ doNothing().when(httpServletResponse).addHeader(Mockito.anyString(), Mockito.anyString());
+ MusicUtil.setVersion("x.x.x");
+ MusicUtil.setBuild("y.y");
+ Map<String, HashMap<String, String>> map = restMusicTestAPI.simpleTests(httpServletResponse);
+
+ Map<String, String> map1 = map.get("0");
+ assertEquals("2", map1.get("1").toString());
+ assertEquals("x.x.x", map1.get("Music Version").toString());
+ assertEquals("y.y", map1.get("Music Build").toString());
+
+ Map<String, String> map2 = map.get("1");
+ assertEquals("3", map2.get("2").toString());
+ assertEquals("x.x.x", map2.get("Music Version").toString());
+ assertEquals("y.y", map2.get("Music Build").toString());
+
+ Map<String, String> map3 = map.get("2");
+ assertEquals("4", map3.get("3").toString());
+ assertEquals("x.x.x", map3.get("Music Version").toString());
+ assertEquals("y.y", map3.get("Music Build").toString());
+ }
+}
diff --git a/music-rest/src/test/java/org/onap/music/rest/RestMusicVersionAPITest.java b/music-rest/src/test/java/org/onap/music/rest/RestMusicVersionAPITest.java
new file mode 100644
index 00000000..6fc433e4
--- /dev/null
+++ b/music-rest/src/test/java/org/onap/music/rest/RestMusicVersionAPITest.java
@@ -0,0 +1,63 @@
+/*******************************************************************************
+ * ============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.rest;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.doNothing;
+import java.util.Map;
+import javax.servlet.http.HttpServletResponse;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.music.main.MusicUtil;
+
+public class RestMusicVersionAPITest {
+
+ RestMusicVersionAPI restMusicVersionAPI;
+
+ @Before
+ public void setup() {
+ restMusicVersionAPI = new RestMusicVersionAPI();
+ }
+
+ @Test
+ public void testVersion() {
+ MusicUtil.setVersion("x.x.x");
+ HttpServletResponse httpServletResponse = Mockito.mock(HttpServletResponse.class);
+ doNothing().when(httpServletResponse).addHeader(Mockito.anyString(), Mockito.anyString());
+ Map<String,Object> map = restMusicVersionAPI.version(httpServletResponse);
+ assertEquals("MUSIC:x.x.x", map.get("version").toString());
+ assertEquals("SUCCESS", map.get("status").toString());
+ }
+
+ @Test
+ public void testBuild() {
+ MusicUtil.setBuild("y.y");
+ MusicUtil.setVersion("x.x.x");
+ HttpServletResponse httpServletResponse = Mockito.mock(HttpServletResponse.class);
+ doNothing().when(httpServletResponse).addHeader(Mockito.anyString(), Mockito.anyString());
+ Map<String,Object> map = restMusicVersionAPI.build(httpServletResponse);
+ assertEquals("MUSIC:x.x.x", map.get("version").toString());
+ assertEquals("SUCCESS", map.get("status").toString());
+ assertEquals("MUSIC:y.y", map.get("build").toString());
+ }
+}
diff --git a/src/test/java/org/onap/music/unittests/CassandraCQL.java b/music-rest/src/test/java/org/onap/music/unittests/CassandraCQL.java
index a4c250c2..7b116bc8 100644
--- a/src/test/java/org/onap/music/unittests/CassandraCQL.java
+++ b/music-rest/src/test/java/org/onap/music/unittests/CassandraCQL.java
@@ -27,7 +27,6 @@ package org.onap.music.unittests;
*
*/
-import java.io.IOException;
import java.math.BigInteger;
import java.net.InetAddress;
import java.net.NetworkInterface;
@@ -35,47 +34,54 @@ import java.net.SocketException;
import java.util.ArrayList;
import java.util.Enumeration;
import java.util.HashMap;
-import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.UUID;
-import com.datastax.driver.core.Cluster;
-import com.datastax.driver.core.Session;
-import com.datastax.driver.core.exceptions.NoHostAvailableException;
-import org.apache.cassandra.exceptions.ConfigurationException;
-import org.apache.thrift.transport.TTransportException;
+
+//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 = "
+ "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 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<text,text>,PRIMARY KEY (empName)) "
+ "CREATE TABLE IF NOT EXISTS testcassa.employees "
+ + "(vector_ts text,empid uuid,empname text,empsalary varint,address Map<text,text>,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 (?,?,?,?); ";
+ "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 (?,?,?,?,?);";
+ "INSERT INTO testcassa.employees (vector_ts,empid,empname,empsalary,address) VALUES (?,?,?,?,?);";
- public static final String selectALL = "SELECT * FROM testCassa.employees;";
+ public static final String selectALL = "SELECT * FROM testcassa.employees;";
public static final String selectSpecific =
- "SELECT * FROM testCassa.employees WHERE empName= ?;";
+ "SELECT * FROM testcassa.employees WHERE empname= ?;";
public static final String updatePreparedQuery =
- "UPDATE testCassa.employees SET vector_ts=?,address= ? WHERE empName= ?;";
+ "UPDATE testcassa.employees SET vector_ts=?,address= ? WHERE empname= ?;";
public static final String deleteFromTable = " ";
@@ -222,35 +228,20 @@ public class CassandraCQL {
return allPossibleIps;
}
- public static MusicDataStore connectToEmbeddedCassandra() {
- Iterator<String> it = getAllPossibleLocalIps().iterator();
+ public static MusicDataStore connectToEmbeddedCassandra() throws Exception {
+ System.setProperty("log4j.configuration", "log4j.properties");
+
String address = "localhost";
- Cluster cluster = null;
- Session session = null;
- while (it.hasNext()) {
- try {
-
- try {
- EmbeddedCassandraServerHelper.startEmbeddedCassandra(80000);
- } catch (ConfigurationException | TTransportException | IOException e) {
-
- System.out.println(e.getMessage());
- }
-
- cluster = new Cluster.Builder().addContactPoint(address).withPort(9142).build();
- cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(20000);
- session = cluster.connect();
-
- break;
- } catch (NoHostAvailableException e) {
- address = it.next();
- System.out.println(e.getMessage());
-
- }
- }
+ EmbeddedCassandraServerHelper.startEmbeddedCassandra();
+ Cluster cluster = new Cluster.Builder().withoutJMXReporting().withoutMetrics().addContactPoint(address).withPort(9142).build();
+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(5000);
+ EnumNameCodec<LockType> lockTypeCodec = new EnumNameCodec<LockType>(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/music-rest/src/test/java/org/onap/music/unittests/JsonResponseTest.java
index 9da10638..6af8c0d9 100644
--- a/src/test/java/org/onap/music/unittests/JsonResponseTest.java
+++ b/music-rest/src/test/java/org/onap/music/unittests/JsonResponseTest.java
@@ -4,6 +4,8 @@
* ===================================================================
* 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
@@ -23,8 +25,13 @@
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;
@@ -80,4 +87,81 @@ public class JsonResponseTest {
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<String, HashMap<String, Object>> 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<String> 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<String, Object> lockMap = (Map<String, Object>) result.toMap().get("lock");
+ // assure that this is string for backwards compatibility
+ assertEquals("lockholder1", lockMap.get("lock-holder"));
+
+ List<String> lockholders = new ArrayList<>();
+ lockholders.add("lockholder1");
+ lockholders.add("lockholder2");
+ result.setLockHolder(lockholders);
+ lockMap = (Map<String, Object>) result.toMap().get("lock");
+ assertEquals(lockMap.get("lock-holder"), lockholders);
+ }
}
diff --git a/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java b/music-rest/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java
index 16d2af02..68e6f3dc 100644
--- a/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java
+++ b/music-rest/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java
@@ -19,6 +19,7 @@
* ============LICENSE_END=============================================
* ====================================================================
*/
+
package org.onap.music.unittests;
import static org.junit.Assert.assertEquals;
@@ -28,11 +29,14 @@ 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;
@@ -41,15 +45,18 @@ import com.datastax.driver.core.ResultSet;
import com.datastax.driver.core.Row;
import com.datastax.driver.core.TableMetadata;
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+@RunWith(SpringJUnit4ClassRunner.class)
+//@ActiveProfiles(profiles = "OrderRepositoryTest")
+@ContextConfiguration
public class MusicDataStoreTest {
static MusicDataStore dataStore;
static PreparedQueryObject testObject;
@BeforeClass
- public static void init() {
+ public static void init()throws Exception {
dataStore = CassandraCQL.connectToEmbeddedCassandra();
+ //CachingUtil.resetStatementBank();
}
@@ -59,13 +66,14 @@ public class MusicDataStoreTest {
testObject = new PreparedQueryObject();
testObject.appendQueryString(CassandraCQL.dropKeyspace);
dataStore.executePut(testObject, "eventual");
- dataStore.close();
-
+ //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");;
@@ -75,7 +83,7 @@ public class MusicDataStoreTest {
assertEquals(true, result);
}
-
+
@Test
public void Test2_ExecutePut_eventual_insert() throws MusicServiceException, MusicQueryException {
testObject = CassandraCQL.setPreparedInsertQueryObject1();
@@ -105,7 +113,7 @@ public class MusicDataStoreTest {
boolean result = false;
int count = 0;
ResultSet output = null;
- output = dataStore.executeEventualGet(testObject);
+ output = dataStore.executeOneConsistencyGet(testObject);
System.out.println(output);
;
for (Row row : output) {
@@ -115,7 +123,7 @@ public class MusicDataStoreTest {
if (count == 2) {
result = true;
}
- assertEquals(true, result);
+ assertEquals(false, result);
}
@Test
@@ -124,7 +132,7 @@ public class MusicDataStoreTest {
boolean result = false;
int count = 0;
ResultSet output = null;
- output = dataStore.executeCriticalGet(testObject);
+ output = dataStore.executeQuorumConsistencyGet(testObject);
System.out.println(output);
;
for (Row row : output) {
@@ -134,7 +142,7 @@ public class MusicDataStoreTest {
if (count == 1) {
result = true;
}
- assertEquals(true, result);
+ assertEquals(false, result);
}
@Test(expected = NullPointerException.class)
diff --git a/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java b/music-rest/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java
index e75835d1..385a4698 100644
--- a/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java
+++ b/music-rest/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java
@@ -1,20 +1,25 @@
/*
- * ============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
+ * ============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
+ * http://www.apache.org/licenses/LICENSE-2.0
*
- * Unless required by applicable law or agreed to in writing, software distributed under the License
- * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express
- * or implied. See the License for the specific language governing permissions and limitations under
- * the License.
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS 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;
@@ -34,10 +39,11 @@ 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.apache.curator.test.TestingServer;
+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;
@@ -45,7 +51,9 @@ import org.mindrot.jbcrypt.BCrypt;
//cjcimport org.mindrot.jbcrypt.BCrypt;
import org.mockito.Mock;
import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
+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;
@@ -55,13 +63,14 @@ 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.lockingservice.MusicLockingService;
+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.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;
@@ -76,19 +85,18 @@ import com.sun.jersey.core.util.MultivaluedMapImpl;
@RunWith(MockitoJUnitRunner.class)
public class TestRestMusicQAPI {
-
- RestMusicAdminAPI admin = new RestMusicAdminAPI();
+
+ //RestMusicAdminAPI admin = new RestMusicAdminAPI();
RestMusicLocksAPI lock = new RestMusicLocksAPI();
RestMusicQAPI qData = new RestMusicQAPI();
static PreparedQueryObject testObject;
- static TestingServer zkServer;
@Mock
static HttpServletResponse http;
@Mock
UriInfo info;
-
+
static String appName = "TestApp";
static String userId = "TestUser";
static String password = "TestPassword";
@@ -122,19 +130,18 @@ public class TestRestMusicQAPI {
@BeforeClass
public static void init() throws Exception {
try {
- System.out.println("before class cassandra");
- MusicCore.mDstoreHandle = CassandraCQL.connectToEmbeddedCassandra();
- System.out.println("before class zoo");
- zkServer = new TestingServer(2181, new File("/tmp/zk"));
- MusicCore.mLockHandle = new MusicLockingService();
- // System.out.println("before class keysp");
+ 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 ");
+ System.out.println("before class exception ");
e.printStackTrace();
}
- // admin keyspace and table
+ // admin keyspace and table
testObject = new PreparedQueryObject();
testObject.appendQueryString("CREATE KEYSPACE admin WITH REPLICATION = "
+ "{'class' : 'SimpleStrategy' , "
@@ -186,7 +193,7 @@ public class TestRestMusicQAPI {
if (rows.size() > 0) {
System.out.println("#######UUID is:" + rows.get(0).getUUID("uuid"));
}
-
+
JsonKeySpace jsonKeyspace = new JsonKeySpace();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, Object> replicationInfo = new HashMap<>();
@@ -212,14 +219,13 @@ public class TestRestMusicQAPI {
testObject = new PreparedQueryObject();
testObject.appendQueryString("DROP KEYSPACE IF EXISTS admin");
MusicCore.eventualPut(testObject);
- MusicCore.mDstoreHandle.close();
- MusicCore.mLockHandle.getzkLockHandle().close();
- MusicCore.mLockHandle.close();
- zkServer.stop();
+ MusicDataStore mds = (MusicDataStore) ReflectionTestUtils.getField(MusicDataStoreHandle.class, "mDstoreHandle");
+ if (mds != null)
+ mds.close();
}
- @Test
+/* @Test
public void Test1_createQ_good() throws Exception {
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
@@ -244,8 +250,8 @@ public class TestRestMusicQAPI {
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();
@@ -264,7 +270,7 @@ public class TestRestMusicQAPI {
jsonTable.setTableName(tableName);
jsonTable.setFields(fields);
//System.out.println("cjc before print version, xLatestVersion="+xLatestVersion);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableName);
@@ -273,7 +279,7 @@ public class TestRestMusicQAPI {
System.out.println("Entity" + response.getEntity());
assertNotEquals(200, response.getStatus());
}
- @Test
+/* @Test
public void Test1_createQ_Clustergood() throws Exception {
String tableNameC="testcjcC";
JsonTable jsonTable = new JsonTable();
@@ -299,9 +305,9 @@ public class TestRestMusicQAPI {
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
assertEquals(200, response.getStatus());
- }
-
- @Test
+ }*/
+
+/* @Test
public void Test1_createQ_ClusterOrderGood1() throws Exception {
String tableNameC="testcjcO";
JsonTable jsonTable = new JsonTable();
@@ -326,9 +332,9 @@ public class TestRestMusicQAPI {
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
assertEquals(200, response.getStatus());
- }
+ } */
- @Test
+/* @Test
public void Test1_createQ_PartitionKeygood() throws Exception {
String tableNameP="testcjcP";
JsonTable jsonTable = new JsonTable();
@@ -353,7 +359,7 @@ public class TestRestMusicQAPI {
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 {
@@ -374,7 +380,7 @@ public class TestRestMusicQAPI {
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());
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
@@ -385,7 +391,7 @@ public class TestRestMusicQAPI {
assertTrue(200 != response.getStatus());
}
- @Test
+/* @Test
public void Test1_createQ_ClusterOrderGood2() throws Exception {
String tableNameC="testcjcO1g";
JsonTable jsonTable = new JsonTable();
@@ -412,9 +418,9 @@ public class TestRestMusicQAPI {
System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
System.out.println("Entity" + response.getEntity());
assertEquals(200, response.getStatus());
- }
+ } */
- @Test
+ /* @Test
public void Test1_createQ_ColPkeyoverridesPrimaryKeyGood() throws Exception {
String tableNameC="testcjcPr";
JsonTable jsonTable = new JsonTable();
@@ -442,7 +448,7 @@ public class TestRestMusicQAPI {
System.out.println("Entity" + response.getEntity());
assertEquals(200, response.getStatus());
//assertTrue(200 != response.getStatus());
- }
+ } */
@Test
public void Test1_createQ_ClusterOrderBad() throws Exception {
@@ -463,7 +469,7 @@ public class TestRestMusicQAPI {
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());
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
@@ -476,7 +482,7 @@ public class TestRestMusicQAPI {
@Test
public void Test3_createQ_0() throws Exception {
- //duplicate testing ...
+ //duplicate testing ...
JsonTable jsonTable = new JsonTable();
Map<String, String> consistencyInfo = new HashMap<>();
Map<String, String> fields = new HashMap<>();
@@ -491,7 +497,7 @@ public class TestRestMusicQAPI {
String tableNameDup=tableName+"X";
jsonTable.setTableName(tableNameDup);
jsonTable.setFields(fields);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ //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);
@@ -512,34 +518,9 @@ public class TestRestMusicQAPI {
//assertNotEquals(200,response0.getStatus());
}
- // Improper Auth
- @Test
- public void Test3_createQ1() throws Exception {
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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.setClusteringKey("uuid");
- jsonTable.setTableName(tableName);
- jsonTable.setClusteringOrder("uuid 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, wrongAuthorization,
- jsonTable, keyspaceName, tableName);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertEquals(401, response.getStatus());
- }
// Improper keyspace
+ @Ignore
@Test
public void Test3_createQ2() throws Exception {
JsonTable jsonTable = new JsonTable();
@@ -557,7 +538,7 @@ public class TestRestMusicQAPI {
jsonTable.setClusteringKey("emp_salary");
jsonTable.setClusteringOrder("emp_salary DESC");
jsonTable.setFields(fields);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ //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);
@@ -568,7 +549,7 @@ public class TestRestMusicQAPI {
- @Test
+/* @Test
public void Test4_insertIntoQ() throws Exception {
JsonInsert jsonInsert = new JsonInsert();
Map<String, String> consistencyInfo = new HashMap<>();
@@ -585,7 +566,7 @@ public class TestRestMusicQAPI {
Response response = qData.insertIntoQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
appName, authorization, jsonInsert, keyspaceName, tableName);
assertEquals(200, response.getStatus());
- }
+ }*/
@Test
@@ -603,13 +584,13 @@ public class TestRestMusicQAPI {
jsonInsert.setKeyspaceName(keyspaceName);
jsonInsert.setTableName(tableName);
jsonInsert.setValues(values);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ //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
+/* @Test
public void Test4_insertIntoQ2() throws Exception {
JsonInsert jsonInsert = new JsonInsert();
Map<String, String> consistencyInfo = new HashMap<>();
@@ -627,51 +608,11 @@ public class TestRestMusicQAPI {
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
jsonInsert, keyspaceName, tableName);
assertEquals(200, response.getStatus());
- }
+ }*/
- // Auth Error
- @Test
- public void Test4_insertIntoQ3() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> 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, wrongAuthorization,
- jsonInsert, keyspaceName, tableName);
- assertEquals(401, response.getStatus());
- }
- // Table wrong
- @Test
- public void Test4_insertIntoQ4() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> 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, "wrong");
- assertEquals(400, response.getStatus());
- }
-
- @Test
+
+/* @Test
public void Test5_updateQ() throws Exception {
JsonUpdate jsonUpdate = new JsonUpdate();
Map<String, String> consistencyInfo = new HashMap<>();
@@ -690,29 +631,29 @@ public class TestRestMusicQAPI {
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<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> 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 Test5_updateQEmptyValues() throws Exception {
+ JsonUpdate jsonUpdate = new JsonUpdate();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ MultivaluedMap<String, String> row = new MultivaluedMapImpl();
+ Map<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
@@ -728,9 +669,9 @@ public class TestRestMusicQAPI {
HashMap<String,HashMap<String,Object>> map = (HashMap<String, HashMap<String, Object>>) response.getEntity();
HashMap<String, Object> result = map.get("result");
assertEquals("2500", ((HashMap<String,Object>) result.get("row 0")).get("emp_salary").toString());
- }
+ }*/
- @Test
+/* @Test
public void Test6_peekQ() throws Exception { //select
JsonSelect jsonSelect = new JsonSelect();
Map<String, String> consistencyInfo = new HashMap<>();
@@ -747,8 +688,8 @@ public class TestRestMusicQAPI {
if (result.isEmpty() ) assertTrue(true);
else assertFalse(false);
//assertEquals("2500", ((HashMap<String,Object>) result.get("row 0")).get("emp_salary").toString());
- }
-
+ }*/
+/*
@Test
public void Test6_peekQ_empty() throws Exception { //select
// row is not needed in thhis test
@@ -760,7 +701,7 @@ public class TestRestMusicQAPI {
jsonSelect.setConsistencyInfo(consistencyInfo);
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
UriInfo infoe= mockUriInfo("/peek?");//empty queryParam: cause exception
- // infoe.setQueryParameters("");
+ // 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",
@@ -770,9 +711,9 @@ public class TestRestMusicQAPI {
if (result.isEmpty() ) assertTrue(true);
else assertFalse(false);
//assertEquals("2500", ((HashMap<String,Object>) result.get("row 0")).get("emp_salary").toString());
- }
+ }*/
- @Test
+/* @Test
public void Test6_deleteFromQ1() throws Exception {
JsonDelete jsonDelete = new JsonDelete();
Map<String, String> consistencyInfo = new HashMap<>();
@@ -786,21 +727,22 @@ public class TestRestMusicQAPI {
"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<String, String> consistencyInfo = new HashMap<>();
MultivaluedMap<String, String> row = new MultivaluedMapImpl();
consistencyInfo.put("type", "atomic");
jsonDelete.setConsistencyInfo(consistencyInfo);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ //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);
+ "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
+ jsonDelete, keyspaceName, tableName, info);
assertEquals(400, response.getStatus());
}
@@ -813,14 +755,14 @@ public class TestRestMusicQAPI {
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);
+ //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();
@@ -830,17 +772,17 @@ public class TestRestMusicQAPI {
Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.dropQ(majorV, minorV,patchV,
"abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- keyspaceName, tableName);
+ 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;
- }
+ 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
@@ -856,7 +798,7 @@ public class TestRestMusicQAPI {
jsonTable.setClusteringKey("emp_id");
jsonTable.setClusteringOrder("emp_id DESC");
jsonTable.setTableName(tableNameC);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
@@ -883,7 +825,7 @@ public class TestRestMusicQAPI {
jsonTable.setClusteringOrder("emp_id DESC");
jsonTable.setTableName(tableNameC);
jsonTable.setFields(fields);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
@@ -892,7 +834,7 @@ public class TestRestMusicQAPI {
assertEquals(400, response.getStatus());
}
- //Clustering key null
+ //Clustering key null
@Test
public void Test8_createQ_ClusteringKey_empty() throws Exception {
String tableNameC="testcjcC";
@@ -910,7 +852,7 @@ public class TestRestMusicQAPI {
jsonTable.setClusteringOrder("emp_id DESC");
jsonTable.setTableName(tableNameC);
jsonTable.setFields(fields);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
@@ -937,7 +879,7 @@ public class TestRestMusicQAPI {
jsonTable.setClusteringKey("emp_id");
jsonTable.setTableName(tableNameC);
jsonTable.setFields(fields);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
@@ -946,7 +888,7 @@ public class TestRestMusicQAPI {
assertEquals(400, response.getStatus());
}
- //Invalid primary key
+ //Invalid primary key
@Test
public void Test8_createQ_primaryKey_invalid() throws Exception {
String tableNameC="testcjcC";
@@ -965,7 +907,7 @@ public class TestRestMusicQAPI {
jsonTable.setClusteringOrder("emp_id ASC");
jsonTable.setTableName(tableNameC);
jsonTable.setFields(fields);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
@@ -992,13 +934,14 @@ public class TestRestMusicQAPI {
jsonTable.setTableName(tableNameC);
jsonTable.setFields(fields);
jsonTable.setClusteringOrder("emp_id ASC");
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ //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
@@ -1019,7 +962,8 @@ public class TestRestMusicQAPI {
jsonTable.setTableName(tableNameC);
jsonTable.setFields(fields);
jsonTable.setClusteringOrder("emp_id ASC");
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
Response response = qData.createQ(majorV, minorV,patchV,
aid, appName, authorization,
jsonTable, keyspaceName, tableNameC);
@@ -1028,4 +972,4 @@ public class TestRestMusicQAPI {
assertEquals(400, response.getStatus());
}
-} \ No newline at end of file
+}
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<Row> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> values = new HashMap<>();
+ values.put("id", "test_id");
+ consistencyInfo.put("type", "eventual");
+ HashMap<String, Object> cascadeData = new HashMap<>();
+ HashMap<String, String> cascadeValue = new HashMap<>();
+ cascadeValue.put("created", "hello");
+ cascadeValue.put("updated", "world");
+ cascadeData.put("key", "p1");
+ cascadeData.put("value", cascadeValue);
+ HashMap<String, Map<String, String>> condition = new HashMap<>();
+ HashMap<String, String> exists = new HashMap<>();
+ exists.put("status", "parked");
+ HashMap<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ * Map<String, Object> 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<String, String> consistencyInfo = new HashMap<>(); Map<String, Object> 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<String, String> consistencyInfo = new HashMap<>(); Map<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
+ consistencyInfo.put("type", "eventual");
+
+ JsonConditional jsonCond = new JsonConditional();
+ Map<String, Object> values = new HashMap<>();
+ values.put("id", "test_id");
+ HashMap<String, Object> cascadeData = new HashMap<>();
+ HashMap<String, String> 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<String,
+ * String> consistencyInfo = new HashMap<>(); MultivaluedMap<String, String> row = new MultivaluedMapImpl();
+ * Map<String, Object> 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<String, Object> 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<String, String> consistencyInfo = new HashMap<>(); MultivaluedMap<String, String> row = new
+ * MultivaluedMapImpl(); Map<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
+ * MultivaluedMap<String, String> row = new MultivaluedMapImpl(); Map<String, Object> 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<String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> fields = new HashMap<>();
+ fields.put("id", "text");
+ fields.put("plans", "map<text,text>");
+ 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<String, String> consistencyInfo = new HashMap<>();
+ consistencyInfo.put("type", "eventual");
+ JsonConditional jsonCond = new JsonConditional();
+ Map<String, Object> values = new HashMap<>();
+ values.put("id", "test_id");
+ HashMap<String, Object> cascadeData = new HashMap<>();
+ HashMap<String, String> cascadeValue = new HashMap<>();
+ cascadeValue.put("created", "hello");
+ cascadeValue.put("updated", "world");
+ cascadeData.put("key", "p1");
+ cascadeData.put("value", cascadeValue);
+ HashMap<String, Map<String, String>> condition = new HashMap<>();
+ HashMap<String, String> exists = new HashMap<>();
+ exists.put("status", "parked");
+ HashMap<String, String> 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..ea3fb54e
--- /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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<String, String> respMap = (Map<String, String>) 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<String, String> respMap = (Map<String, String>) response.getEntity();
+ assertEquals(ResultType.SUCCESS, respMap.get("status"));
+
+ response = data.dropKeySpace("1", "1", "1", null, authorization, appName, keyspaceToCreate);
+ assertEquals(200, response.getStatus());
+ respMap = (Map<String, String>) 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> 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<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> 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<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> 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<String, String> respMap = (Map<String, String>) response2.getEntity();
+ assertEquals(ResultType.FAILURE, respMap.get("status"));
+ assertEquals("Already Exists Exception: 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> 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<String, String> queryParametersMap = new HashMap<String, String>();
+
+ queryParametersMap.put("index_name", "inxuuid");
+ Mockito.when(info.getQueryParameters()).thenReturn(new MultivaluedHashMap<String, String>(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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> 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<String, String> queryParametersMap = new HashMap<String, String>();
+
+ 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<String, String> 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<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
+ MultivaluedMap<String, String> row = new MultivaluedMapImpl();
+ Map<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
+ MultivaluedMap<String, String> row = new MultivaluedMapImpl();
+ Map<String, Object> 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<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
+ MultivaluedMap<String, String> 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<String,HashMap<String,Object>> map = (HashMap<String, HashMap<String, Object>>) response.getEntity();
+ HashMap<String, Object> result = map.get("result");
+ System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
+
+ Map<String, String> row0 = (Map<String, String>) 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<String, String> 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<String,HashMap<String,Object>> map = (HashMap<String, HashMap<String, Object>>) response.getEntity();
+ HashMap<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
+ MultivaluedMap<String, String> 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<String,HashMap<String,Object>> map = (HashMap<String, HashMap<String, Object>>) response.getEntity();
+ HashMap<String, Object> 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<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ MultivaluedMap<String, String> 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<String, HashMap<String, Object>> map = (HashMap<String, HashMap<String, Object>>) response.getEntity();
+ HashMap<String, Object> result = map.get("result");
+ System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
+
+ Map<String, String> row0 = (Map<String, String>) 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<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ MultivaluedMap<String, String> 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<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ MultivaluedMap<String, String> 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<String, String> 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<String, String> 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<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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..91781a34
--- /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<String, Object> respMap = (Map<String, Object>) response.getEntity();
+ System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
+
+ assertEquals(200, response.getStatus());
+ assertTrue(respMap.containsKey("lock"));
+ assertTrue(((Map<String, String>) 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<String, Object> respMap = (Map<String, Object>) 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<String, Object> respMap = (Map<String, Object>) response.getEntity();
+ System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
+
+ assertEquals(200, response.getStatus());
+ assertTrue(respMap.containsKey("lock"));
+ assertTrue(((Map<String, String>) 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<String, Object> respMap = (Map<String, Object>) response.getEntity();
+ System.out.println("Status: " + response.getStatus() + ". Entity " + response.getEntity());
+
+ assertEquals(200, response.getStatus());
+ assertTrue(respMap.containsKey("lock"));
+ assertTrue(((Map<String, String>) 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<String, String> 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<String, Object> respMap = (Map<String, Object>) response.getEntity();
+ assertEquals(lockRef, ((Map<String, String>) 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<String, Object> respMap = (Map<String, Object>) response.getEntity();
+ assertEquals(lockRef, ((Map<String, List>) 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<String,Object> respMap = (Map<String, Object>) response.getEntity();
+ assertEquals(lockRef, ((Map<String,String>) 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<String, Object> respMapCreate1 = (Map<String, Object>) responseCreate1.getEntity();
+ String lockRefCreate1 = ((Map<String, String>) 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<String, Object> respMapCreate2 = (Map<String, Object>) responseCreate2.getEntity();
+ String lockRefCreate2 = ((Map<String, String>) 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<String, Object> respMapCreate4 = (Map<String, Object>) 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<String, Object> respMapCreate1 = (Map<String, Object>) responseCreate1.getEntity();
+ String lockRefCreate1 = ((Map<String, String>) 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<String, Object> respMapCreate1 = (Map<String, Object>) responseCreate1.getEntity();
+ String lockRefCreate1 = ((Map<String, String>) 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<String, Object> respMapCreate2 = (Map<String, Object>) responseCreate2.getEntity();
+ String lockRefCreate2 = ((Map<String, String>) 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<String, Object> respMapCreate2 = (Map<String, Object>) responseCreate2.getEntity();
+ String lockRefCreate2 = ((Map<String, String>) 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<String, Object> respMapCreate1 = (Map<String, Object>) responseCreate1.getEntity();
+ String lockRefCreate1 = ((Map<String, String>) 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<String, Object> respMapCreate1 = (Map<String, Object>) responseCreate1.getEntity();
+ String lockRefCreate1 = ((Map<String, String>) respMapCreate1.get("lock")).get("lock");
+
+ Response responseCreate2 = lock.createLockReference(lockName, "1", "1", authorization,
+ "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockRead, "process1", appName);
+ Map<String, Object> respMapCreate2 = (Map<String, Object>) responseCreate1.getEntity();
+ String lockRefCreate2 = ((Map<String, String>) 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<String, Object> respMapCreate1 = (Map<String, Object>) responseCreate1.getEntity();
+ String lockRefCreate1 = ((Map<String, String>) respMapCreate1.get("lock")).get("lock");
+
+ Response responseCreate2 = lock.createLockReference(lockName, "1", "1", authorization,
+ "abcde001-d857-4e90-b1e5-df98a3d40ce6", jsonLockRead, "process1", appName);
+ Map<String, Object> respMapCreate2 = (Map<String, Object>) responseCreate2.getEntity();
+ String lockRefCreate2 = ((Map<String, String>) 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<String, Object> respMap = (Map<String, Object>) response.getEntity();
+ return ((Map<String, String>) 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<String, Object> respMap = (Map<String, Object>) response.getEntity();
+ return ((Map<String, String>) 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<String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<String, String> consistencyInfo = new HashMap<>();
+ Map<String, Object> 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<Permission> permList = new ArrayList<Permission>();
+ Permission perm1 = Mockito.mock(AAFPermission.class);
+ permList.add(perm1);
+ Mockito.when(cw.getPermissions(Mockito.any())).thenReturn(permList);
+
+ List<AAFPermission> 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<Permission> permList = new ArrayList<Permission>();
+ 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/java/org/onap/music/unittests/authentication/CadiAuthFilterTest.java b/music-rest/src/test/java/org/onap/music/unittests/authentication/CadiAuthFilterTest.java
new file mode 100644
index 00000000..eb6dde39
--- /dev/null
+++ b/music-rest/src/test/java/org/onap/music/unittests/authentication/CadiAuthFilterTest.java
@@ -0,0 +1,63 @@
+/*
+ * ============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.authentication;
+
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Mockito.mock;
+
+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 org.junit.Test;
+import org.mockito.Mockito;
+import org.onap.aaf.cadi.PropAccess;
+import org.onap.music.authentication.CadiAuthFilter;
+import org.springframework.mock.web.MockFilterConfig;
+import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.mock.web.MockHttpServletResponse;
+
+import javax.servlet.FilterConfig;
+
+public class CadiAuthFilterTest {
+
+ @Test
+ public void Test1() throws ServletException
+ {
+ PropAccess props=new PropAccess();
+ CadiAuthFilter c=new CadiAuthFilter(props);
+ }
+
+
+ @Test
+ public void Test2() throws ServletException
+ {
+ CadiAuthFilter c=new CadiAuthFilter();
+ }
+
+ }
+
+
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 @@
+<!--
+ ============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=============================================
+ ====================================================================
+-->
+<configuration scan="true" scanPeriod="3 seconds">
+ <!--<jmxConfigurator /> -->
+ <!-- directory path for all other type logs -->
+ <property name="logDir" value="/opt/app/music/logs" />
+
+ <!-- directory path for debugging type logs -->
+ <property name="debugDir" value="debug-logs" />
+
+ <!-- specify the component name -->
+ <!-- <property name="componentName" value="EELF"></property> -->
+ <property name="componentName" value="MUSIC"></property>
+
+ <!-- log file names -->
+ <property name="generalLogName" value="music" />
+ <property name="securityLogName" value="security" />
+ <property name="errorLogName" value="error" />
+ <property name="metricsLogName" value="metrics" />
+ <property name="auditLogName" value="audit" />
+ <property name="debugLogName" value="debug" />
+ <property name="defaultPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n" />
+ <!-- <property name="applicationLoggerPattern" value="%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %msg%n" /> -->
+ <property name="applicationLoggerPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5level %X{keyspace} - %msg%n" />
+ <property name="auditLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
+ <property name="metricsLoggerPattern" value="%X{BeginTimestamp}|%X{EndTimestamp}|%X{RequestId}|%X{ServiceInstanceId}|%thread|%X{VirtualServerName}|%X{ServiceName}|%X{PartnerName}|%X{TargetEntity}|%X{TargetServiceName}|%X{StatusCode}|%X{ResponseCode}|%X{ResponseDescription}|%X{InstanceUUID}|%.-5level|%X{AlertSeverity}|%X{ServerIPAddress}|%X{ElapsedTime}|%X{ServerFQDN}|%X{RemoteHost}|%X{ClassName}|%X{Unused}|%X{ProcessKey}|%X{TargetVirtualEntity}|%X{CustomField1}|%X{CustomField2}|%X{CustomField3}|%X{CustomField4}| %msg%n" />
+ <!-- <property name="errorLoggerPattern" value= "%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %msg%n " /> -->
+ <property name="errorLoggerPattern" value="%d{yyyy-MM-dd HH:mm:ss} %-5level %X{keyspace} - %msg%n" />
+ <property name="debugLoggerPattern" value="%date{ISO8601,UTC}|%X{RequestId}| %msg%n" ></property>
+ <property name="logDirectory" value="${logDir}/${componentName}" />
+ <property name="debugLogDirectory" value="${debugDir}/${componentName}" />
+ <!-- Example evaluator filter applied against console appender -->
+ <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
+ <!-- <encoder>
+ <pattern>${defaultPattern}</pattern>
+ </encoder> -->
+ <layout class="">
+ <pattern>
+ %d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n
+ </pattern>
+ </layout>
+ </appender>
+
+ <!-- ============================================================================ -->
+ <!-- EELF Appenders -->
+ <!-- ============================================================================ -->
+<!-- <appender name="EELF"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${generalLogName}.log</file>
+ <rollingPolicy
+ class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${generalLogName}.%i.log.zip
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>100MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${applicationLoggerPattern}</pattern>
+ </encoder>
+ </appender> -->
+
+ <!-- <appender name="EELF" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${generalLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
+ daily rollover
+ <fileNamePattern>${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
+ <maxFileSize>1GB</maxFileSize>
+ <maxHistory>5</maxHistory>
+ <totalSizeCap>5GB</totalSizeCap>
+ </rollingPolicy>
+ <encoder>
+ <pattern>${applicationLoggerPattern}</pattern>
+ </encoder>
+ </appender> -->
+
+
+ <appender name="EELF" class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${generalLogName}.log</file>
+ <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
+ <!-- daily rollover -->
+ <fileNamePattern>${logDirectory}/${generalLogName}.%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
+ <maxFileSize>1GB</maxFileSize>
+ <maxHistory>5</maxHistory>
+ <totalSizeCap>5GB</totalSizeCap>
+ </rollingPolicy>
+ <encoder>
+ <pattern>${applicationLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELF" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <includeCallerData>true</includeCallerData>
+ <appender-ref ref="EELF" />
+ </appender>
+
+ <!-- EELF Security Appender. This appender is used to record security events
+ to the security log file. Security events are separate from other loggers
+ in EELF so that security log records can be captured and managed in a secure
+ way separate from the other logs. This appender is set to never discard any
+ events. -->
+ <appender name="EELFSecurity"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${securityLogName}.log</file>
+ <rollingPolicy
+ class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${securityLogName}.%i.log.zip
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>%d{yyyy-MM-dd HH:mm:ss} [%thread] %-5level %logger{36} - %msg%n </pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFSecurity" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <discardingThreshold>0</discardingThreshold>
+ <appender-ref ref="EELFSecurity" />
+ </appender>
+
+
+
+
+ <!-- EELF Audit Appender. This appender is used to record audit engine
+ related logging events. The audit logger and appender are specializations
+ of the EELF application root logger and appender. This can be used to segregate
+ Policy engine events from other components, or it can be eliminated to record
+ these events as part of the application root log. -->
+
+ <appender name="EELFAudit"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${auditLogName}.log</file>
+ <rollingPolicy
+ class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${auditLogName}.%i.log.zip
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${auditLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+ <appender name="asyncEELFAudit" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFAudit" />
+ </appender>
+
+<appender name="EELFMetrics"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${metricsLogName}.log</file>
+ <rollingPolicy
+ class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${metricsLogName}.%i.log.zip
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <!-- <pattern>"%d{HH:mm:ss.SSS} [%thread] %-5level %logger{1024} -
+ %msg%n"</pattern> -->
+ <pattern>${metricsLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+
+
+ <appender name="asyncEELFMetrics" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFMetrics"/>
+ </appender>
+
+ <appender name="EELFError"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${logDirectory}/${errorLogName}.log</file>
+ <rollingPolicy
+ class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${logDirectory}/${errorLogName}.%i.log.zip
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${errorLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFError" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFError"/>
+ </appender>
+
+ <appender name="EELFDebug"
+ class="ch.qos.logback.core.rolling.RollingFileAppender">
+ <file>${debugLogDirectory}/${debugLogName}.log</file>
+ <rollingPolicy
+ class="ch.qos.logback.core.rolling.FixedWindowRollingPolicy">
+ <fileNamePattern>${debugLogDirectory}/${debugLogName}.%i.log.zip
+ </fileNamePattern>
+ <minIndex>1</minIndex>
+ <maxIndex>9</maxIndex>
+ </rollingPolicy>
+ <triggeringPolicy
+ class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
+ <maxFileSize>5MB</maxFileSize>
+ </triggeringPolicy>
+ <encoder>
+ <pattern>${debugLoggerPattern}</pattern>
+ </encoder>
+ </appender>
+
+ <appender name="asyncEELFDebug" class="ch.qos.logback.classic.AsyncAppender">
+ <queueSize>256</queueSize>
+ <appender-ref ref="EELFDebug" />
+ <includeCallerData>true</includeCallerData>
+ </appender>
+
+
+ <!-- ============================================================================ -->
+ <!-- EELF loggers -->
+ <!-- ============================================================================ -->
+ <logger name="com.att.eelf" level="info" additivity="false">
+ <appender-ref ref="asyncEELF" />
+
+ </logger>
+ <logger name="com.att.eelf.security" level="info" additivity="false">
+ <appender-ref ref="asyncEELFSecurity" />
+
+ </logger>
+
+
+ <logger name="com.att.eelf.audit" level="info" additivity="false">
+ <appender-ref ref="asyncEELFAudit" />
+
+ </logger>
+
+ <logger name="com.att.eelf.metrics" level="info" additivity="false">
+ <appender-ref ref="asyncEELFMetrics" />
+
+ </logger>
+
+
+ <logger name="com.att.eelf.error" level="error" additivity="false">
+ <appender-ref ref="asyncEELFError" />
+
+ </logger>
+
+ <logger name="com.att.eelf.debug" level="debug" additivity="false">
+ <appender-ref ref="asyncEELFDebug" />
+
+ </logger>
+
+ <root level="INFO">
+ <appender-ref ref="asyncEELF" />
+ <!-- <appender-ref ref="STDOUT" /> -->
+ </root>
+
+ <!-- Conductor Specific additions to squash WARNING and INFO -->
+ <logger name="com.datastax.driver.core.Cluster" level="ERROR"/>
+ <logger name="org.onap.music.main.MusicCore" level="ERROR"/>
+
+</configuration>
diff --git a/musictrigger/assembly.xml b/musictrigger/assembly.xml
deleted file mode 100644
index 90178d8f..00000000
--- a/musictrigger/assembly.xml
+++ /dev/null
@@ -1,22 +0,0 @@
-<assembly xmlns="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0"
- xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/plugins/maven-assembly-plugin/assembly/1.1.0 http://maven.apache.org/xsd/assembly-1.1.0.xsd">
- <id>v1</id>
- <formats>
- <format>jar</format>
- </formats>
- <includeBaseDirectory>false</includeBaseDirectory>
- <dependencySets>
- <dependencySet>
- <unpack>false</unpack>
- <scope>runtime</scope>
- <useProjectArtifact>false</useProjectArtifact>
- </dependencySet>
- </dependencySets>
- <fileSets>
- <fileSet>
- <directory>${project.build.outputDirectory}</directory>
- <outputDirectory>.</outputDirectory>
- </fileSet>
- </fileSets>
-</assembly>
diff --git a/musictrigger/pom.xml b/musictrigger/pom.xml
deleted file mode 100644
index 13dcbcf3..00000000
--- a/musictrigger/pom.xml
+++ /dev/null
@@ -1,62 +0,0 @@
-<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <groupId>org.onap.music</groupId>
- <artifactId>musictrigger</artifactId>
- <packaging>jar</packaging>
- <version>0.1.0</version>
- <build>
- <sourceDirectory>src</sourceDirectory>
- <plugins>
- <plugin>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>3.6.1</version>
- <configuration>
- <source>1.8</source>
- <target>1.8</target>
- </configuration>
- </plugin>
- <plugin>
- <artifactId>maven-assembly-plugin</artifactId>
- <configuration>
- <archive>
- <manifest>
- <mainClass>fully.qualified.MainClass</mainClass>
- </manifest>
- </archive>
- <descriptorRefs>
- <descriptorRef>jar-with-dependencies</descriptorRef>
- </descriptorRefs>
- </configuration>
- </plugin>
- </plugins>
- </build>
-
- <dependencies>
- <dependency>
- <groupId>com.owlike</groupId>
- <artifactId>genson</artifactId>
- <version>0.99</version>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-client</artifactId>
- <version>1.17</version>
- </dependency>
- <dependency>
- <groupId>com.datastax.cassandra</groupId>
- <artifactId>cassandra-driver-core</artifactId>
- <version>3.0.0</version>
- </dependency>
- <dependency>
- <groupId>org.cassandraunit</groupId>
- <artifactId>cassandra-unit</artifactId>
- <version>3.3.0.1</version>
- </dependency>
- <dependency>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
- <version>1.11</version>
- </dependency>
- </dependencies>
-</project>
diff --git a/musictrigger/src/MusicTrigger.java b/musictrigger/src/MusicTrigger.java
deleted file mode 100755
index b5894da1..00000000
--- a/musictrigger/src/MusicTrigger.java
+++ /dev/null
@@ -1,221 +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=============================================
- * ====================================================================
- */
-
-import java.util.Arrays;
-import java.util.Collection;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.nio.ByteBuffer;
-import java.nio.charset.Charset;
-import java.nio.charset.StandardCharsets;
-import java.util.ArrayList;
-import java.util.Map;
-
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-
-import org.apache.cassandra.config.ColumnDefinition;
-import org.apache.cassandra.db.Clustering;
-import org.apache.cassandra.db.Mutation;
-import org.apache.cassandra.db.partitions.Partition;
-import org.apache.cassandra.db.rows.Cell;
-import org.apache.cassandra.db.rows.Row;
-import org.apache.cassandra.db.rows.Unfiltered;
-import org.apache.cassandra.db.rows.UnfilteredRowIterator;
-import org.apache.cassandra.triggers.ITrigger;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.WebResource;
-
-public class MusicTrigger implements ITrigger {
-
- private static final Logger logger = LoggerFactory.getLogger(MusicTrigger.class);
-
-
- public Collection<Mutation> augment(Partition partition)
- {
- boolean isDelete = false;
- logger.info("Step 1: "+partition.partitionLevelDeletion().isLive());
- if(partition.partitionLevelDeletion().isLive()) {
-
- } else {
- // Partition Level Deletion
- isDelete = true;
- }
- logger.info("MusicTrigger isDelete: " + isDelete);
- String ksName = partition.metadata().ksName;
- String tableName = partition.metadata().cfName;
- logger.info("MusicTrigger Table: " + tableName);
- boolean isInsert = checkQueryType(partition);
- org.json.simple.JSONObject obj = new org.json.simple.JSONObject();
-
- String operation = null;
- if(isDelete)
- operation = "delete";
- else if(isInsert)
- operation = "insert";
- else
- operation = "update";
- Map<String, Object> changeMap = new HashMap<>();
-
- obj.put("operation", operation);
- obj.put("keyspace", ksName);
- obj.put("table_name", tableName);
- obj.put("full_table", ksName+"."+tableName);
- obj.put("primary_key", partition.metadata().getKeyValidator().getString(partition.partitionKey().getKey()));
- List<String> updateList = new ArrayList<>();
- //obj.put("message_id", partition.metadata().getKeyValidator().getString(partition.partitionKey().getKey()));
- if("update".equals(operation)) {
- try {
- UnfilteredRowIterator it = partition.unfilteredIterator();
- while (it.hasNext()) {
- Unfiltered un = it.next();
- Clustering clt = (Clustering) un.clustering();
- Iterator<Cell> cells = partition.getRow(clt).cells().iterator();
- Iterator<ColumnDefinition> columns = partition.getRow(clt).columns().iterator();
-
- while(columns.hasNext()){
- ColumnDefinition columnDef = columns.next();
- Cell cell = cells.next();
-
- String data = null;
- if(cell.column().type.toString().equals("org.apache.cassandra.db.marshal.UTF8Type")) {
- logger.info(">> type is String");
- data = new String(cell.value().array()); // If cell type is text
- } else if(cell.column().type.toString().equals("org.apache.cassandra.db.marshal.Int32Type")) {
- //ByteBuffer wrapped = ByteBuffer.wrap(cell.value()); // big-endian by default
- int num = fromByteArray(cell.value().array());
- logger.info(">> type is Integer1 :: "+num);
- data = String.valueOf(num);
- }
-
- logger.info("Inside triggers loop: "+columnDef.name+" : "+data);
- //changeMap.put(ksName+"."+tableName+"."+columnDef.name,data);
- updateList.add(ksName+"."+tableName+":"+columnDef.name+":"+data);
- changeMap.put("field_value",ksName+"."+tableName+":"+columnDef.name+":"+data);
-
- }
- }
- } catch (Exception e) {
-
- }
- obj.put("updateList", updateList);
- } else {
- changeMap.put("field_value", ksName+"."+tableName);
- }
-
- obj.put("changeValue", changeMap);
- logger.info("Sending response: "+obj.toString());
- try {
- notifyMusic(obj.toString());
- } catch(Exception e) {
- e.printStackTrace();
- logger.error("Notification failed..."+e.getMessage());
- }
- return Collections.emptyList();
- }
-
- private int fromByteArray(byte[] bytes) {
- return bytes[0] << 24 | (bytes[1] & 0xFF) << 16 | (bytes[2] & 0xFF) << 8 | (bytes[3] & 0xFF);
- }
-
- private boolean checkQueryType(Partition partition) {
- UnfilteredRowIterator it = partition.unfilteredIterator();
- while (it.hasNext()) {
- Unfiltered unfiltered = it.next();
- Row row = (Row) unfiltered;
- if (isInsert(row)) {
- return true;
- }
- }
- return false;
- }
-
- private boolean isInsert(Row row) {
- return row.primaryKeyLivenessInfo().timestamp() != Long.MIN_VALUE;
- }
-
- private void notifyMusic(String request) {
- System.out.println("notifyMusic...");
- Client client = Client.create();
- WebResource webResource = client.resource("http://localhost:8080/MUSIC/rest/v2/admin/callbackOps");
-
- JSONObject data = new JSONObject();
- data.setData(request);
-
- ClientResponse response = webResource.accept("application/json").type("application/json")
- .post(ClientResponse.class, data);
-
- if(response.getStatus() != 200){
- System.out.println("Exception while notifying MUSIC...");
- }
- /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE, Arrays.asList(MediaType.APPLICATION_JSON));
- response.bufferEntity();
- String x = response.getEntity(String.class);
- System.out.println("Response: "+x);*/
-
- }
-
- /*public Collection<Mutation> augment(Partition partition) {
-
- String tableName = partition.metadata().cfName;
- System.out.println("Table: " + tableName);
-
- JSONObject obj = new JSONObject();
- obj.put("message_id", partition.metadata().getKeyValidator().getString(partition.partitionKey().getKey()));
-
-
- try {
- UnfilteredRowIterator it = partition.unfilteredIterator();
- while (it.hasNext()) {
- Unfiltered un = it.next();
- Clustering clt = (Clustering) un.clustering();
- Iterator<Cell> cls = partition.getRow(clt).cells().iterator();
- Iterator<ColumnDefinition> columns = partition.getRow(clt).columns().iterator();
-
- while(cls.hasNext()){
- Cell cell = cls.next();
- String data = new String(cell.value().array()); // If cell type is text
- System.out.println(cell + " : " +data);
-
- }
- while(columns.hasNext()){
- ColumnDefinition columnDef = columns.next();
- Cell cell = cls.next();
- String data = new String(cell.value().array()); // If cell type is text
- obj.put(columnDef.toString(), data);
- }
- }
- } catch (Exception e) {
- }
-
- System.out.println(obj.toString());
-
- return Collections.emptyList();
- }*/
-
-} \ No newline at end of file
diff --git a/pom.xml b/pom.xml
index d370856d..05bdaefb 100755
--- a/pom.xml
+++ b/pom.xml
@@ -1,10 +1,12 @@
-<?xml version="1.0"?>
-<!--
+<?xml version="1.0" encoding="UTF-8"?>
+<!--
============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
@@ -16,7 +18,7 @@
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
-
+
============LICENSE_END=============================================
====================================================================
-->
@@ -24,31 +26,27 @@
<modelVersion>4.0.0</modelVersion>
<groupId>org.onap.music</groupId>
<artifactId>MUSIC</artifactId>
- <packaging>war</packaging>
- <version>3.0.19-SNAPSHOT</version>
+ <packaging>pom</packaging>
+ <version>3.2.40-SNAPSHOT</version>
<description>
- This is the MUSIC REST interface, packaged as a war file.
+ This is the MUSIC project.
</description>
- <parent>
+ <parent>
<groupId>org.onap.oparent</groupId>
<artifactId>oparent</artifactId>
- <version>1.2.0</version>
+ <version>2.0.0</version>
<relativePath/>
</parent>
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <jersey1.version>1.19</jersey1.version>
- <jersey2.version>2.25.1</jersey2.version>
- <jaxrs.version>2.0.1</jaxrs.version>
- <cassandra.version>3.6.0</cassandra.version>
- <zookeeper.version>3.4.11</zookeeper.version>
-
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
<project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
+ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
+ <java.version>1.8</java.version>
<!--nexus -->
<nexusproxy>https://nexus.onap.org</nexusproxy>
+ <onap.nexus.url>https://nexus.onap.org</onap.nexus.url>
<snapshotNexusPath>/content/repositories/snapshots/</snapshotNexusPath>
<releaseNexusPath>/content/repositories/releases/</releaseNexusPath>
<stagingNexusPath>/content/repositories/staging/</stagingNexusPath>
@@ -56,295 +54,51 @@
<!--maven -->
<timestamp>${maven.build.timestamp}</timestamp>
<maven.build.timestamp.format>yyyy.MM.dd.HH.mm</maven.build.timestamp.format>
+ <!--skip checkstyle -->
+ <maven.check.skip>false</maven.check.skip>
<!--docker -->
<docker.tag>${project.version}-${timestamp}</docker.tag>
<docker.latest.tag>${project.version}-latest</docker.latest.tag>
+ <maven.compiler.source>1.8</maven.compiler.source>
+ <maven.compiler.target>1.8</maven.compiler.target>
+ <!-- Default Sonar configuration -->
+ <sonar.coverage.jacoco.xmlReportPaths>${project.reporting.outputDirectory}/jacoco-ut/jacoco.xml,${project.reporting.outputDirectory}/jacoco-it/jacoco.xml</sonar.coverage.jacoco.xmlReportPaths>
</properties>
- <repositories>
- <repository>
- <id>ecomp-releases</id>
- <name>ECOMP Release Repository</name>
- <url>${onap.nexus.url}/${releaseNexusPath}</url>
- </repository>
- <repository>
- <id>ecomp-snapshots</id>
- <name>Snapshot Repository</name>
- <url>${nexusproxy}/${snapshotNexusPath}</url>
- </repository>
- <repository>
- <id>ecomp-staging</id>
- <name>Staging Repository</name>
- <url>${nexusproxy}/${stagingNexusPath}</url>
- </repository>
- </repositories>
-
- <build>
- <finalName>MUSIC</finalName>
- <sourceDirectory>src/main/java</sourceDirectory>
- <outputDirectory>src/main/webapp/WEB-INF/classes</outputDirectory>
- <testSourceDirectory>src/test/java</testSourceDirectory>
- <testOutputDirectory>target/test-classes</testOutputDirectory>
- <defaultGoal>validate</defaultGoal>
- <resources>
- <resource>
- <directory>src/main/resources</directory>
- <filtering>true</filtering>
- </resource>
- </resources>
- <plugins>
- <plugin>
- <artifactId>maven-eclipse-plugin</artifactId>
- <version>2.9</version>
- <configuration>
- <additionalProjectnatures>
- <projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
- </additionalProjectnatures>
- <additionalBuildcommands>
- <buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
- </additionalBuildcommands>
- <downloadSources>true</downloadSources>
- <downloadJavadocs>true</downloadJavadocs>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-compiler-plugin</artifactId>
- <version>3.5.1</version>
- <configuration>
- <source>1.7</source>
- <target>1.7</target>
- <excludes>
- <exclude>jar/**</exclude>
- </excludes>
- </configuration>
- </plugin>
- <plugin>
- <artifactId>maven-war-plugin</artifactId>
- <version>2.4</version>
- <configuration>
- <warSourceDirectory>WebContent</warSourceDirectory>
- </configuration>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-jar-plugin</artifactId>
- <version>2.4</version>
- <executions>
- <execution>
- <id>make-a-jar</id>
- <phase>compile</phase>
- <goals>
- <goal>jar</goal>
- </goals>
- <configuration>
- <excludes>
- <exclude>**/*.xml</exclude>
- <exclude>**/*.properties</exclude>
- <exclude>**/Sample*</exclude>
- </excludes>
- </configuration>
- </execution>
- </executions>
- </plugin>
- <plugin>
- <groupId>org.apache.maven.plugins</groupId>
- <artifactId>maven-install-plugin</artifactId>
- <version>2.4</version>
- <executions>
- <execution>
- <phase>install</phase>
- <goals>
- <goal>install-file</goal>
- </goals>
- <configuration>
- <packaging>jar</packaging>
- <artifactId>${project.artifactId}</artifactId>
- <groupId>${project.groupId}</groupId>
- <version>${project.version}</version>
- <file>${project.build.directory}/${project.artifactId}.jar</file>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
-
<dependencies>
<!-- Development -->
<dependency>
<groupId>javax.servlet</groupId>
- <artifactId>servlet-api</artifactId>
- <version>2.4</version>
- <scope>provided</scope>
- </dependency>
- <dependency>
- <groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
- <version>3.0.1</version>
+ <version>4.0.1</version>
<scope>provided</scope>
</dependency>
- <!-- /Development -->
- <!-- <dependency>
- <groupId>com.hazelcast</groupId>
- <artifactId>hazelcast-client</artifactId>
- <version>3.7.1</version>
- </dependency> -->
- <!-- Logging -->
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-core</artifactId>
- <version>1.2.3</version>
- <exclusions>
- <exclusion>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>ch.qos.logback</groupId>
- <artifactId>logback-classic</artifactId>
- <version>1.2.3</version>
- <exclusions>
- <exclusion>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <dependency>
- <groupId>com.att.eelf</groupId>
- <artifactId>eelf-core</artifactId>
- <version>1.0.1-oss</version>
- </dependency>
- <!-- End Logging -->
- <!-- Cassandra -->
- <dependency>
- <groupId>com.datastax.cassandra</groupId>
- <artifactId>cassandra-driver-core</artifactId>
- <version>${cassandra.version}</version>
- </dependency>
- <!-- /Cassandra -->
- <!-- Zookeeper -->
- <dependency>
- <groupId>org.apache.zookeeper</groupId>
- <artifactId>zookeeper</artifactId>
- <version>${zookeeper.version}</version>
- <exclusions>
- <exclusion>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- </exclusion>
- </exclusions>
- </dependency>
- <!-- /Zookeeper -->
- <!-- Jersey -->
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-client</artifactId>
- <version>${jersey1.version}</version>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-server</artifactId>
- <version>${jersey1.version}</version>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-json</artifactId>
- <version>${jersey1.version}</version>
- </dependency>
- <dependency>
- <groupId>com.sun.jersey</groupId>
- <artifactId>jersey-servlet</artifactId>
- <version>${jersey1.version}</version>
- </dependency>
- <!-- /Jersey -->
+ <!-- Springboot -->
+ </dependencies>
- <dependency>
- <groupId>org.apache.commons</groupId>
- <artifactId>commons-jcs-core</artifactId>
- <version>2.2</version>
- </dependency>
- <dependency>
- <groupId>commons-codec</groupId>
- <artifactId>commons-codec</artifactId>
- <version>1.11</version>
- </dependency>
- <!-- Testing -->
- <dependency>
- <groupId>junit</groupId>
- <artifactId>junit</artifactId>
- <version>4.12</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.cassandraunit</groupId>
- <artifactId>cassandra-unit</artifactId>
- <version>3.3.0.2</version>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.apache.curator</groupId>
- <artifactId>curator-test</artifactId>
- <version>2.3.0</version>
- <exclusions>
- <exclusion>
- <groupId>org.apache.zookeeper</groupId>
- <artifactId>zookeeper</artifactId>
- </exclusion>
- <exclusion>
- <groupId>org.slf4j</groupId>
- <artifactId>slf4j-log4j12</artifactId>
- </exclusion>
- </exclusions>
- <scope>test</scope>
- </dependency>
- <dependency>
- <groupId>org.mockito</groupId>
- <artifactId>mockito-all</artifactId>
- <version>1.9.0</version>
- <scope>test</scope>
- </dependency>
- <!-- /Testing -->
- <dependency>
- <groupId>io.netty</groupId>
- <artifactId>netty-handler</artifactId>
- <version>4.0.56.Final</version>
- </dependency>
- <dependency>
- <groupId>com.fasterxml.jackson.core</groupId>
- <artifactId>jackson-databind</artifactId>
- <version>2.9.4</version>
- </dependency>
- <dependency>
- <groupId>org.apache.httpcomponents</groupId>
- <artifactId>httpclient</artifactId>
- <version>4.5.3</version>
- </dependency>
- <dependency>
- <groupId>io.swagger</groupId>
- <artifactId>swagger-jersey-jaxrs</artifactId>
- <version>1.5.18</version>
- </dependency>
- <dependency>
- <groupId>com.google.guava</groupId>
- <artifactId>guava</artifactId>
- </dependency>
- <dependency>
- <groupId>org.mindrot</groupId>
- <artifactId>jbcrypt</artifactId>
- <version>0.4</version>
- </dependency>
- <dependency>
- <groupId>com.owlike</groupId>
- <artifactId>genson</artifactId>
- <version>1.3</version>
- </dependency>
-
- </dependencies>
+ <repositories>
+ <repository>
+ <id>onap-releases</id>
+ <name>ONAP - Release Repository</name>
+ <url>${nexusproxy}/${releaseNexusPath}</url>
+ </repository>
+ <repository>
+ <id>onap-staging</id>
+ <name>ONAP - Staging Repository</name>
+ <url>${nexusproxy}/${stagingNexusPath}</url>
+ </repository>
+ <repository>
+ <id>onap-snapshots</id>
+ <name>ONAP - Snapshot Repository</name>
+ <url>${nexusproxy}/${snapshotNexusPath}</url>
+ </repository>
+ <repository>
+ <id>onap-public</id>
+ <name>ONAP public Repository</name>
+ <url>${nexusproxy}/content/groups/public</url>
+ </repository>
+ </repositories>
<reporting>
<plugins>
@@ -363,112 +117,17 @@
</links>
</configuration>
</plugin>
+ <plugin>
+ <groupId>org.apache.maven.plugins</groupId>
+ <artifactId>maven-compiler-plugin</artifactId>
+ <configuration>
+ <source>1.8</source>
+ <target>1.8</target>
+ </configuration>
+ </plugin>
</plugins>
</reporting>
- <profiles>
- <profile>
- <id>docker</id>
- <build>
- <plugins>
- <plugin>
- <groupId>io.fabric8</groupId>
- <artifactId>docker-maven-plugin</artifactId>
- <version>0.19.1</version>
- <configuration>
- <verbose>true</verbose>
- <apiVersion>1.23</apiVersion>
- <registry>nexus3.onap.org:10003</registry>
- <images>
- <!-- MUSIC War -->
- <image>
- <name>onap/music/music</name>
- <alias>docker_music</alias>
- <build>
- <cleanup>true</cleanup>
- <tags>
- <tag>${docker.tag}</tag>
- <tag>${docker.latest.tag}</tag>
- </tags>
- <dockerFileDir>${project.basedir}</dockerFileDir>
- <assembly>
- <descriptorRef>artifact</descriptorRef>
- </assembly>
- </build>
- </image>
- <!-- Cassandra -->
- <image>
- <name>onap/music/cassandra_3_11</name>
- <alias>docker_cassandra_sec</alias>
- <build>
- <cleanup>true</cleanup>
- <tags>
- <tag>${docker.tag}</tag>
- <tag>${docker.latest.tag}</tag>
- </tags>
- <dockerFileDir>${project.basedir}/distribution/cassandra</dockerFileDir>
- </build>
- </image>
- <!-- Cassandra Job -->
- <image>
- <name>onap/music/cassandra_job</name>
- <alias>docker_cassandra_job</alias>
- <build>
- <cleanup>true</cleanup>
- <tags>
- <tag>${docker.tag}</tag>
- <tag>${docker.latest.tag}</tag>
- </tags>
- <dockerFileDir>${project.basedir}/distribution/cassandra_job</dockerFileDir>
- </build>
- </image>
- <!-- Zookeeper -->
- <!-- <image> <name>onap/music/zookeeper_music</name>
- <alias>docker_zookeeper</alias> <build> <cleanup>true</cleanup> <tags> <tag>3.4-${timestamp}</tag>
- <tag>3.4-latest</tag> </tags> <dockerFileDir>${project.basedir}/distribution/zookeeper</dockerFileDir>
- </build> </image> -->
- <!-- tomcat 8.5 -->
- <!-- <image> <name>onap/music/tomcat_music</name>
- <alias>docker_tomcat</alias> <build> <cleanup>true</cleanup> <tags> <tag>8.5-${timestamp}</tag>
- <tag>8.5-latest</tag> </tags> <dockerFileDir>${project.basedir}/distribution/tomcat</dockerFileDir>
- </build> </image>\ -->
- </images>
- </configuration>
- <executions>
- <execution>
- <id>clean-images</id>
- <phase>pre-clean</phase>
- <goals>
- <goal>remove</goal>
- </goals>
- <configuration>
- <removeAll>true</removeAll>
- <image>music</image>
- </configuration>
- </execution>
- <execution>
- <id>generate-images</id>
- <phase>package</phase>
- <goals>
- <goal>build</goal>
- </goals>
- </execution>
- <execution>
- <id>push-images</id>
- <phase>deploy</phase>
- <goals>
- <goal>push</goal>
- </goals>
- <configuration>
- <image>onap/music/music</image>
- </configuration>
- </execution>
- </executions>
- </plugin>
- </plugins>
- </build>
- </profile>
- </profiles>
<distributionManagement>
<repository>
<id>ecomp-releases</id>
@@ -486,4 +145,8 @@
<url>dav:${nexusproxy}${sitePath}</url>
</site>
</distributionManagement>
+ <modules>
+ <module>music-core</module>
+ <module>music-rest</module>
+ </modules>
</project>
diff --git a/postman/MusicLocal.postman_collection.json b/postman/MusicLocal.postman_collection.json
index 0fef0bb9..19597e15 100644
--- a/postman/MusicLocal.postman_collection.json
+++ b/postman/MusicLocal.postman_collection.json
@@ -1,695 +1,695 @@
{
- "id": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "name": "MusicLocal",
- "description": "",
- "order": [
- "cde8166d-a97c-c173-c00a-7584cb8d24ea",
- "9a8091d5-1207-d121-e723-1c927253d986",
- "6309194d-0855-d97c-5d92-5c91860cfa9f",
- "695ae5ac-9db1-873d-0733-49885c060605",
- "59a33710-2189-ee04-66f1-630920300fdf",
- "272e9995-c6cd-a456-57a5-f41ca424a2a0",
- "b7e1120b-0c82-2e73-b3a8-c3c9d9662c7f",
- "eff968ca-84d1-54a2-ce26-0f9c95bf965d",
- "fc561465-a6d2-1fd8-ecb5-3c88738fd219",
- "fe7680e6-8407-e2e1-f89c-763c255b3538",
- "b5ecf9b0-9bac-3099-e292-541a7d814a91",
- "6a6dc6ca-c413-a8da-5f9d-31ea88da7767",
- "517e24a4-db48-8a36-6387-ae71478b5e1c",
- "c2416eb6-8ba5-3d5b-6585-0e070cf032fc",
- "f096757d-ebe6-6126-633a-99a684a0e705",
- "f9212734-54e2-4fe5-09c0-c67bed88770a",
- "d7c46575-d1a2-7b85-aad2-f43728a077f0",
- "21667ae7-0272-5acc-cc54-dd1221f2fece",
- "feed66c2-797e-c469-3c8a-f555b92d22d4",
- "9cc7f611-8c6f-f564-ef9a-53aecaaf0837",
- "04cba481-f6bf-6d53-ef8c-543b9541ff1a",
- "b667b219-8eec-2267-1994-7f0fb97b77ce",
- "28dd3c51-1c0c-65c0-4037-bda04c6a05b7",
- "d3d7de68-3af7-1d52-1575-3e579949e484",
- "f895d276-f717-afc8-7bea-6ae881c74aeb",
- "89d85877-b30e-dc5a-7bee-90e375a2ff78",
- "200b3cae-32cb-fabe-a86b-f8f1bfdec9e0",
- "6954fd5e-8f5e-5f46-c11c-2aa209ee98d1",
- "4c425caa-f06b-8978-f7af-676d0e28073b",
- "b33314ff-f0df-7f98-a594-c0b2a60902e1",
- "4c652cee-d1b1-613d-3b14-4c8a52c3c2dd",
- "ada66950-0758-54c9-17fe-1dae95c7f67a",
- "5eb909b0-6c7d-972e-b601-f26a0b990ba1"
- ],
- "folders": [],
- "timestamp": 1443818487905,
- "owner": 0,
- "remoteLink": "",
- "public": false,
- "requests": [
- {
- "id": "04cba481-f6bf-6d53-ef8c-543b9541ff1a",
- "headers": "Content-Type: application/json\n",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/projects",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "DELETE",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1455129844265,
- "name": "Drop table projects (atomic)",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": "{\n \"consistencyInfo\": {\n \"type\": \"atomic\",\n \"lockId\":\"$testks.projects$x-95351186188533762-0000000000\"\n } \n}"
- },
- {
- "id": "200b3cae-32cb-fabe-a86b-f8f1bfdec9e0",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/locks/release/$testks.projects$x-95351186188533762-0000000000",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "DELETE",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1455130135037,
- "name": "Release \"testks.projects\"",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": ""
- },
- {
- "id": "21667ae7-0272-5acc-cc54-dd1221f2fece",
- "headers": "Content-Type: application/json\n",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows?emp_name=joe",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "DELETE",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454945571791,
- "name": "Delete column value (eventual) ",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": "{\n \"columns\": [\"emp_salary\", \"address\"],\n \"consistencyInfo\": {\n \"type\": \"eventual\"\n }\n}"
- },
- {
- "id": "272e9995-c6cd-a456-57a5-f41ca424a2a0",
- "headers": "Content-Type: application/json\n",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "POST",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454944181424,
- "name": "Create new table \"testks.employees\" (eventual)",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": "{\n \"fields\": {\n \"emp_id\": \"uuid\",\n \"emp_name\": \"text\",\n \"emp_salary\": \"varint\",\n \"address\": \"Map<text,text>\",\n \"PRIMARY KEY\":\"(emp_name)\"\n },\n \"properties\": {\n \"comment\": \"Financial Info of employees\",\n \"compression\":{ \"sstable_compression\" : \"DeflateCompressor\", \"chunk_length_kb\" : 64 },\n \"compaction\": { \"class\" : \"SizeTieredCompactionStrategy\", \"min_threshold\" : 6 }\n }, \n \"consistencyInfo\": {\n \"type\": \"eventual\"\n } \n}"
- },
- {
- "id": "28dd3c51-1c0c-65c0-4037-bda04c6a05b7",
- "headers": "Content-Type: application/json\n",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testmusic",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "DELETE",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1455129913345,
- "name": "Drop keyspace (atomic)",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": "{\n \"consistencyInfo\": {\n \"type\": \"atomic\",\n \"lockId\": \"$testmusic$x-95351186188533762-0000000000\"\n } \n}"
- },
- {
- "id": "4c425caa-f06b-8978-f7af-676d0e28073b",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/locks/release/$testks.projects$x-95351186188533761-0000000000",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "DELETE",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454945804464,
- "name": "Release \"testks.employees.bharath\"",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": ""
- },
- {
- "id": "4c652cee-d1b1-613d-3b14-4c8a52c3c2dd",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/locks/delete/testks.projects",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "DELETE",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454957689347,
- "name": "Delete lock \"testks.projects\"",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": ""
- },
- {
- "id": "517e24a4-db48-8a36-6387-ae71478b5e1c",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/locks/create/testks.employees.bharath",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "POST",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454945175277,
- "name": "Create and acquire lock \"testks.employees.bharath\"",
- "description": "the lock name should be keyspacename.tablename.keyname",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": ""
- },
- {
- "id": "59a33710-2189-ee04-66f1-630920300fdf",
- "headers": "Content-Type: application/json\n",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testmusic",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "POST",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1455129706478,
- "name": "Create new keyspace \"testmusic\" (atomic)",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": "{\n \"replicationInfo\": {\n \"class\": \"SimpleStrategy\",\n \"replication_factor\": 1\n },\n \"durabilityOfWrites\":\"true\",\n \"consistencyInfo\": {\n \"type\": \"atomic\",\n \"lockId\": \"$testmusic$x-95351186188533761-0000000000\"\n } \n}"
- },
- {
- "id": "5eb909b0-6c7d-972e-b601-f26a0b990ba1",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/locks/delete/testks.employees.bharath",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "DELETE",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454957709344,
- "name": "Delete lock \"testks.employees.bharath\"",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": ""
- },
- {
- "id": "6309194d-0855-d97c-5d92-5c91860cfa9f",
- "headers": "Content-Type: application/json\n",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "POST",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454935383882,
- "name": "Create new keyspace \"testks\" (eventual)",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": "{\n \"replicationInfo\": {\n \"class\": \"SimpleStrategy\",\n \"replication_factor\": 1\n },\n \"durabilityOfWrites\":\"true\",\n \"consistencyInfo\": {\n \"type\": \"eventual\"\n } \n}"
- },
- {
- "id": "6954fd5e-8f5e-5f46-c11c-2aa209ee98d1",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/locks/release/$testks.projects$x-95351186188533761-0000000000",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "DELETE",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454945804464,
- "name": "Release \"testks.employees\"",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": ""
- },
- {
- "id": "695ae5ac-9db1-873d-0733-49885c060605",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/locks/create/testmusic",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "POST",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454944173069,
- "name": "Create and acquire lock named \"testmusic\"",
- "description": "the lock name should be the exact same name as the keyspace being created. ",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": ""
- },
- {
- "id": "6a6dc6ca-c413-a8da-5f9d-31ea88da7767",
- "headers": "Content-Type: application/json\n",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows?emp_name=joe",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "PUT",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454945126893,
- "name": "Update column for joe (eventual)",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": "{\n \"values\": {\n \"address\":{ \"street\" : \"thomas street\", \"city\" : \"nyc\" }\n },\n \"consistencyInfo\": {\n \"type\": \"eventual\"\n }\n}"
- },
- {
- "id": "89d85877-b30e-dc5a-7bee-90e375a2ff78",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/locks/release/$testmusic$x-95351186188533762-0000000000",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "DELETE",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1455130112211,
- "name": "Release \"testmusic\"",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": ""
- },
- {
- "id": "9a8091d5-1207-d121-e723-1c927253d986",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/test",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "GET",
- "data": [],
- "dataMode": "params",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1450912270089,
- "name": "random tests",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6"
- },
- {
- "id": "9cc7f611-8c6f-f564-ef9a-53aecaaf0837",
- "headers": "Content-Type: application/json\n",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/tesks/tables/employees",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "DELETE",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454945626279,
- "name": "Drop table employees (eventual) ",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": "{\n \"consistencyInfo\": {\n \"type\": \"eventual\"\n } \n}"
- },
- {
- "id": "ada66950-0758-54c9-17fe-1dae95c7f67a",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/locks/delete/testks.employees",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "DELETE",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454957696653,
- "name": "Delete lock \"testks.employees\"",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": ""
- },
- {
- "id": "b33314ff-f0df-7f98-a594-c0b2a60902e1",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/locks/delete/testmusic",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "DELETE",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454957679029,
- "name": "Delete lock \"testmusic\"",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": ""
- },
- {
- "id": "b5ecf9b0-9bac-3099-e292-541a7d814a91",
- "headers": "Content-Type: application/json\n",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "POST",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1455129742447,
- "name": "Insert (bharath) into \"tesks.employees\" table (atomic)",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": "{\n \"values\": {\n \"emp_id\": \"cfd66ccc-d857-4e90-b1e5-df98a3d40cd6\",\n \"emp_name\": \"bharath\",\n \"emp_salary\": 50,\n \"address\":{ \"street\" : \"att way\", \"city\" : \"bedminster\" }\n },\n \"consistencyInfo\": {\n \"type\": \"atomic\",\n \"lockId\": \"$testks.employees$x-95351186188533762-0000000000\"\n }\n}"
- },
- {
- "id": "b667b219-8eec-2267-1994-7f0fb97b77ce",
- "headers": "Content-Type: application/json\n",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "DELETE",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454945685594,
- "name": "Drop keyspace (eventual)",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": "{\n \"consistencyInfo\": {\n \"type\": \"eventual\"\n } \n}"
- },
- {
- "id": "b7e1120b-0c82-2e73-b3a8-c3c9d9662c7f",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/locks/create/testks.projects",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "POST",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454944356576,
- "name": "Create and acquire lock \"testks.projects\"",
- "description": "the lock name should be keyspacename.tablename",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": ""
- },
- {
- "id": "c2416eb6-8ba5-3d5b-6585-0e070cf032fc",
- "headers": "Content-Type: application/json\n",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows?emp_name=bharath",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "PUT",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1455129766385,
- "name": "Update column for bharath (atomic)",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": "{\n \"values\": {\n \"emp_salary\": 1000\n },\n \"consistencyInfo\": {\n \"type\": \"atomic\",\n \"lockId\": \"$testks.employees.bharath$x-95351186188533762-0000000000\"\n }\n}"
- },
- {
- "id": "cde8166d-a97c-c173-c00a-7584cb8d24ea",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/version",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "GET",
- "data": [],
- "dataMode": "params",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454933904557,
- "name": "Version Test",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6"
- },
- {
- "id": "d3d7de68-3af7-1d52-1575-3e579949e484",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/locks/acquire/$testmusic$x-95351186188533762-0000000000",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "GET",
- "data": [],
- "dataMode": "params",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1455129929805,
- "name": "Test if you have lock",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": []
- },
- {
- "id": "d7c46575-d1a2-7b85-aad2-f43728a077f0",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "GET",
- "data": [],
- "dataMode": "params",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454945233493,
- "name": "Select all from table ",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6"
- },
- {
- "id": "eff968ca-84d1-54a2-ce26-0f9c95bf965d",
- "headers": "Content-Type: application/json\n",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/projects",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "POST",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1455129724221,
- "name": "Create new table \"testks.projects\" (atomic) ",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": "{\n \"fields\": {\n \"project_name\": \"text\",\n \"project_desc\": \"text\",\n \"PRIMARY KEY\":\"(project_name)\"\n },\n \"consistencyInfo\": {\n \"type\": \"atomic\",\n \"lockId\": \"$testks.projects$x-95351186188533762-0000000000\"\n } \n}"
- },
- {
- "id": "f096757d-ebe6-6126-633a-99a684a0e705",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows?emp_name=bharath",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "GET",
- "data": [],
- "dataMode": "params",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454945205888,
- "name": "Select (bharath) from table",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6"
- },
- {
- "id": "f895d276-f717-afc8-7bea-6ae881c74aeb",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/locks/enquire/testmusic",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "GET",
- "data": [],
- "dataMode": "params",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1455130102304,
- "name": "Enquire about lock",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": []
- },
- {
- "id": "f9212734-54e2-4fe5-09c0-c67bed88770a",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows?emp_name=joe",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "GET",
- "data": [],
- "dataMode": "params",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454945215385,
- "name": "Select (joe) from table ",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6"
- },
- {
- "id": "fc561465-a6d2-1fd8-ecb5-3c88738fd219",
- "headers": "Content-Type: application/json\n",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "POST",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454944527955,
- "name": "Insert (joe) into \"testks.employees\" table (eventual)",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": "{\n \"values\": {\n \"emp_id\": \"abc66ccc-d857-4e90-b1e5-df98a3d40cd6\",\n \"emp_name\": \"joe\",\n \"emp_salary\": 30\n },\n \"consistencyInfo\": {\n \"type\": \"eventual\"\n } \n}"
- },
- {
- "id": "fe7680e6-8407-e2e1-f89c-763c255b3538",
- "headers": "",
- "url": "http://localhost:8080/MUSIC/rest/v2/locks/create/testks.employees",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "POST",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1454944949245,
- "name": "Create and acquire lock \"testks.employees\"",
- "description": "the lock name should be keyspacename.tablename",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": ""
- },
- {
- "id": "feed66c2-797e-c469-3c8a-f555b92d22d4",
- "headers": "Content-Type: application/json\n",
- "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows?emp_name=bharath",
- "preRequestScript": "",
- "pathVariables": {},
- "method": "DELETE",
- "data": [],
- "dataMode": "raw",
- "version": 2,
- "tests": "",
- "currentHelper": "normal",
- "helperAttributes": {},
- "time": 1455129806221,
- "name": "Delete column value (atomic)",
- "description": "",
- "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
- "responses": [],
- "rawModeData": "{\n \"columns\": [\"emp_salary\", \"address\"],\n \"consistencyInfo\": {\n \"type\": \"atomic\",\n \"lockId\": \"$testks.employees.bharath$x-95351186188533762-0000000000\"\n }\n}"
- }
- ]
+ "id": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "name": "MusicLocal",
+ "description": "",
+ "order": [
+ "cde8166d-a97c-c173-c00a-7584cb8d24ea",
+ "9a8091d5-1207-d121-e723-1c927253d986",
+ "6309194d-0855-d97c-5d92-5c91860cfa9f",
+ "695ae5ac-9db1-873d-0733-49885c060605",
+ "59a33710-2189-ee04-66f1-630920300fdf",
+ "272e9995-c6cd-a456-57a5-f41ca424a2a0",
+ "b7e1120b-0c82-2e73-b3a8-c3c9d9662c7f",
+ "eff968ca-84d1-54a2-ce26-0f9c95bf965d",
+ "fc561465-a6d2-1fd8-ecb5-3c88738fd219",
+ "fe7680e6-8407-e2e1-f89c-763c255b3538",
+ "b5ecf9b0-9bac-3099-e292-541a7d814a91",
+ "6a6dc6ca-c413-a8da-5f9d-31ea88da7767",
+ "517e24a4-db48-8a36-6387-ae71478b5e1c",
+ "c2416eb6-8ba5-3d5b-6585-0e070cf032fc",
+ "f096757d-ebe6-6126-633a-99a684a0e705",
+ "f9212734-54e2-4fe5-09c0-c67bed88770a",
+ "d7c46575-d1a2-7b85-aad2-f43728a077f0",
+ "21667ae7-0272-5acc-cc54-dd1221f2fece",
+ "feed66c2-797e-c469-3c8a-f555b92d22d4",
+ "9cc7f611-8c6f-f564-ef9a-53aecaaf0837",
+ "04cba481-f6bf-6d53-ef8c-543b9541ff1a",
+ "b667b219-8eec-2267-1994-7f0fb97b77ce",
+ "28dd3c51-1c0c-65c0-4037-bda04c6a05b7",
+ "d3d7de68-3af7-1d52-1575-3e579949e484",
+ "f895d276-f717-afc8-7bea-6ae881c74aeb",
+ "89d85877-b30e-dc5a-7bee-90e375a2ff78",
+ "200b3cae-32cb-fabe-a86b-f8f1bfdec9e0",
+ "6954fd5e-8f5e-5f46-c11c-2aa209ee98d1",
+ "4c425caa-f06b-8978-f7af-676d0e28073b",
+ "b33314ff-f0df-7f98-a594-c0b2a60902e1",
+ "4c652cee-d1b1-613d-3b14-4c8a52c3c2dd",
+ "ada66950-0758-54c9-17fe-1dae95c7f67a",
+ "5eb909b0-6c7d-972e-b601-f26a0b990ba1"
+ ],
+ "folders": [],
+ "timestamp": 1443818487905,
+ "owner": 0,
+ "remoteLink": "",
+ "public": false,
+ "requests": [
+ {
+ "id": "04cba481-f6bf-6d53-ef8c-543b9541ff1a",
+ "headers": "Content-Type: application/json\n",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/projects",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "DELETE",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1455129844265,
+ "name": "Drop table projects (atomic)",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": "{\n \"consistencyInfo\": {\n \"type\": \"atomic\",\n \"lockId\":\"$testks.projects$x-95351186188533762-0000000000\"\n } \n}"
+ },
+ {
+ "id": "200b3cae-32cb-fabe-a86b-f8f1bfdec9e0",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/locks/release/$testks.projects$x-95351186188533762-0000000000",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "DELETE",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1455130135037,
+ "name": "Release \"testks.projects\"",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": ""
+ },
+ {
+ "id": "21667ae7-0272-5acc-cc54-dd1221f2fece",
+ "headers": "Content-Type: application/json\n",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows?emp_name=joe",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "DELETE",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454945571791,
+ "name": "Delete column value (eventual) ",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": "{\n \"columns\": [\"emp_salary\", \"address\"],\n \"consistencyInfo\": {\n \"type\": \"eventual\"\n }\n}"
+ },
+ {
+ "id": "272e9995-c6cd-a456-57a5-f41ca424a2a0",
+ "headers": "Content-Type: application/json\n",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "POST",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454944181424,
+ "name": "Create new table \"testks.employees\" (eventual)",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": "{\n \"fields\": {\n \"emp_id\": \"uuid\",\n \"emp_name\": \"text\",\n \"emp_salary\": \"varint\",\n \"address\": \"Map<text,text>\",\n \"PRIMARY KEY\":\"(emp_name)\"\n },\n \"properties\": {\n \"comment\": \"Financial Info of employees\",\n \"compression\":{ \"sstable_compression\" : \"DeflateCompressor\", \"chunk_length_kb\" : 64 },\n \"compaction\": { \"class\" : \"SizeTieredCompactionStrategy\", \"min_threshold\" : 6 }\n }, \n \"consistencyInfo\": {\n \"type\": \"eventual\"\n } \n}"
+ },
+ {
+ "id": "28dd3c51-1c0c-65c0-4037-bda04c6a05b7",
+ "headers": "Content-Type: application/json\n",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testmusic",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "DELETE",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1455129913345,
+ "name": "Drop keyspace (atomic)",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": "{\n \"consistencyInfo\": {\n \"type\": \"atomic\",\n \"lockId\": \"$testmusic$x-95351186188533762-0000000000\"\n } \n}"
+ },
+ {
+ "id": "4c425caa-f06b-8978-f7af-676d0e28073b",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/locks/release/$testks.projects$x-95351186188533761-0000000000",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "DELETE",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454945804464,
+ "name": "Release \"testks.employees.bharath\"",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": ""
+ },
+ {
+ "id": "4c652cee-d1b1-613d-3b14-4c8a52c3c2dd",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/locks/delete/testks.projects",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "DELETE",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454957689347,
+ "name": "Delete lock \"testks.projects\"",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": ""
+ },
+ {
+ "id": "517e24a4-db48-8a36-6387-ae71478b5e1c",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/locks/create/testks.employees.bharath",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "POST",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454945175277,
+ "name": "Create and acquire lock \"testks.employees.bharath\"",
+ "description": "the lock name should be keyspacename.tablename.keyname",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": ""
+ },
+ {
+ "id": "59a33710-2189-ee04-66f1-630920300fdf",
+ "headers": "Content-Type: application/json\n",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testmusic",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "POST",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1455129706478,
+ "name": "Create new keyspace \"testmusic\" (atomic)",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": "{\n \"replicationInfo\": {\n \"class\": \"SimpleStrategy\",\n \"replication_factor\": 1\n },\n \"durabilityOfWrites\":\"true\",\n \"consistencyInfo\": {\n \"type\": \"atomic\",\n \"lockId\": \"$testmusic$x-95351186188533761-0000000000\"\n } \n}"
+ },
+ {
+ "id": "5eb909b0-6c7d-972e-b601-f26a0b990ba1",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/locks/delete/testks.employees.bharath",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "DELETE",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454957709344,
+ "name": "Delete lock \"testks.employees.bharath\"",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": ""
+ },
+ {
+ "id": "6309194d-0855-d97c-5d92-5c91860cfa9f",
+ "headers": "Content-Type: application/json\n",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "POST",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454935383882,
+ "name": "Create new keyspace \"testks\" (eventual)",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": "{\n \"replicationInfo\": {\n \"class\": \"SimpleStrategy\",\n \"replication_factor\": 1\n },\n \"durabilityOfWrites\":\"true\",\n \"consistencyInfo\": {\n \"type\": \"eventual\"\n } \n}"
+ },
+ {
+ "id": "6954fd5e-8f5e-5f46-c11c-2aa209ee98d1",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/locks/release/$testks.projects$x-95351186188533761-0000000000",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "DELETE",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454945804464,
+ "name": "Release \"testks.employees\"",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": ""
+ },
+ {
+ "id": "695ae5ac-9db1-873d-0733-49885c060605",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/locks/create/testmusic",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "POST",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454944173069,
+ "name": "Create and acquire lock named \"testmusic\"",
+ "description": "the lock name should be the exact same name as the keyspace being created. ",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": ""
+ },
+ {
+ "id": "6a6dc6ca-c413-a8da-5f9d-31ea88da7767",
+ "headers": "Content-Type: application/json\n",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows?emp_name=joe",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "PUT",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454945126893,
+ "name": "Update column for joe (eventual)",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": "{\n \"values\": {\n \"address\":{ \"street\" : \"thomas street\", \"city\" : \"nyc\" }\n },\n \"consistencyInfo\": {\n \"type\": \"eventual\"\n }\n}"
+ },
+ {
+ "id": "89d85877-b30e-dc5a-7bee-90e375a2ff78",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/locks/release/$testmusic$x-95351186188533762-0000000000",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "DELETE",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1455130112211,
+ "name": "Release \"testmusic\"",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": ""
+ },
+ {
+ "id": "9a8091d5-1207-d121-e723-1c927253d986",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/test",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "GET",
+ "data": [],
+ "dataMode": "params",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1450912270089,
+ "name": "random tests",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6"
+ },
+ {
+ "id": "9cc7f611-8c6f-f564-ef9a-53aecaaf0837",
+ "headers": "Content-Type: application/json\n",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/tesks/tables/employees",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "DELETE",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454945626279,
+ "name": "Drop table employees (eventual) ",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": "{\n \"consistencyInfo\": {\n \"type\": \"eventual\"\n } \n}"
+ },
+ {
+ "id": "ada66950-0758-54c9-17fe-1dae95c7f67a",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/locks/delete/testks.employees",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "DELETE",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454957696653,
+ "name": "Delete lock \"testks.employees\"",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": ""
+ },
+ {
+ "id": "b33314ff-f0df-7f98-a594-c0b2a60902e1",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/locks/delete/testmusic",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "DELETE",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454957679029,
+ "name": "Delete lock \"testmusic\"",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": ""
+ },
+ {
+ "id": "b5ecf9b0-9bac-3099-e292-541a7d814a91",
+ "headers": "Content-Type: application/json\n",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "POST",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1455129742447,
+ "name": "Insert (bharath) into \"tesks.employees\" table (atomic)",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": "{\n \"values\": {\n \"emp_id\": \"cfd66ccc-d857-4e90-b1e5-df98a3d40cd6\",\n \"emp_name\": \"bharath\",\n \"emp_salary\": 50,\n \"address\":{ \"street\" : \"Smith Way\", \"city\" : \"Bedminster\" }\n },\n \"consistencyInfo\": {\n \"type\": \"atomic\",\n \"lockId\": \"$testks.employees$x-95351186188533762-0000000000\"\n }\n}"
+ },
+ {
+ "id": "b667b219-8eec-2267-1994-7f0fb97b77ce",
+ "headers": "Content-Type: application/json\n",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "DELETE",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454945685594,
+ "name": "Drop keyspace (eventual)",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": "{\n \"consistencyInfo\": {\n \"type\": \"eventual\"\n } \n}"
+ },
+ {
+ "id": "b7e1120b-0c82-2e73-b3a8-c3c9d9662c7f",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/locks/create/testks.projects",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "POST",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454944356576,
+ "name": "Create and acquire lock \"testks.projects\"",
+ "description": "the lock name should be keyspacename.tablename",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": ""
+ },
+ {
+ "id": "c2416eb6-8ba5-3d5b-6585-0e070cf032fc",
+ "headers": "Content-Type: application/json\n",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows?emp_name=bharath",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "PUT",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1455129766385,
+ "name": "Update column for bharath (atomic)",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": "{\n \"values\": {\n \"emp_salary\": 1000\n },\n \"consistencyInfo\": {\n \"type\": \"atomic\",\n \"lockId\": \"$testks.employees.bharath$x-95351186188533762-0000000000\"\n }\n}"
+ },
+ {
+ "id": "cde8166d-a97c-c173-c00a-7584cb8d24ea",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/version",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "GET",
+ "data": [],
+ "dataMode": "params",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454933904557,
+ "name": "Version Test",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6"
+ },
+ {
+ "id": "d3d7de68-3af7-1d52-1575-3e579949e484",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/locks/acquire/$testmusic$x-95351186188533762-0000000000",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "GET",
+ "data": [],
+ "dataMode": "params",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1455129929805,
+ "name": "Test if you have lock",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": []
+ },
+ {
+ "id": "d7c46575-d1a2-7b85-aad2-f43728a077f0",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "GET",
+ "data": [],
+ "dataMode": "params",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454945233493,
+ "name": "Select all from table ",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6"
+ },
+ {
+ "id": "eff968ca-84d1-54a2-ce26-0f9c95bf965d",
+ "headers": "Content-Type: application/json\n",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/projects",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "POST",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1455129724221,
+ "name": "Create new table \"testks.projects\" (atomic) ",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": "{\n \"fields\": {\n \"project_name\": \"text\",\n \"project_desc\": \"text\",\n \"PRIMARY KEY\":\"(project_name)\"\n },\n \"consistencyInfo\": {\n \"type\": \"atomic\",\n \"lockId\": \"$testks.projects$x-95351186188533762-0000000000\"\n } \n}"
+ },
+ {
+ "id": "f096757d-ebe6-6126-633a-99a684a0e705",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows?emp_name=bharath",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "GET",
+ "data": [],
+ "dataMode": "params",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454945205888,
+ "name": "Select (bharath) from table",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6"
+ },
+ {
+ "id": "f895d276-f717-afc8-7bea-6ae881c74aeb",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/locks/enquire/testmusic",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "GET",
+ "data": [],
+ "dataMode": "params",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1455130102304,
+ "name": "Enquire about lock",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": []
+ },
+ {
+ "id": "f9212734-54e2-4fe5-09c0-c67bed88770a",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows?emp_name=joe",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "GET",
+ "data": [],
+ "dataMode": "params",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454945215385,
+ "name": "Select (joe) from table ",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6"
+ },
+ {
+ "id": "fc561465-a6d2-1fd8-ecb5-3c88738fd219",
+ "headers": "Content-Type: application/json\n",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "POST",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454944527955,
+ "name": "Insert (joe) into \"testks.employees\" table (eventual)",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": "{\n \"values\": {\n \"emp_id\": \"abc66ccc-d857-4e90-b1e5-df98a3d40cd6\",\n \"emp_name\": \"joe\",\n \"emp_salary\": 30\n },\n \"consistencyInfo\": {\n \"type\": \"eventual\"\n } \n}"
+ },
+ {
+ "id": "fe7680e6-8407-e2e1-f89c-763c255b3538",
+ "headers": "",
+ "url": "http://localhost:8080/MUSIC/rest/v2/locks/create/testks.employees",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "POST",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1454944949245,
+ "name": "Create and acquire lock \"testks.employees\"",
+ "description": "the lock name should be keyspacename.tablename",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": ""
+ },
+ {
+ "id": "feed66c2-797e-c469-3c8a-f555b92d22d4",
+ "headers": "Content-Type: application/json\n",
+ "url": "http://localhost:8080/MUSIC/rest/v2/keyspaces/testks/tables/employees/rows?emp_name=bharath",
+ "preRequestScript": "",
+ "pathVariables": {},
+ "method": "DELETE",
+ "data": [],
+ "dataMode": "raw",
+ "version": 2,
+ "tests": "",
+ "currentHelper": "normal",
+ "helperAttributes": {},
+ "time": 1455129806221,
+ "name": "Delete column value (atomic)",
+ "description": "",
+ "collectionId": "a7ff2cf7-0a5a-1b0b-a393-829a672c80d6",
+ "responses": [],
+ "rawModeData": "{\n \"columns\": [\"emp_salary\", \"address\"],\n \"consistencyInfo\": {\n \"type\": \"atomic\",\n \"lockId\": \"$testks.employees.bharath$x-95351186188533762-0000000000\"\n }\n}"
+ }
+ ]
} \ No newline at end of file
diff --git a/releases/3.2.34.yaml b/releases/3.2.34.yaml
new file mode 100644
index 00000000..572f8a2f
--- /dev/null
+++ b/releases/3.2.34.yaml
@@ -0,0 +1,5 @@
+---
+distribution_type: 'maven'
+version: '3.2.34'
+project: 'music'
+log_dir: 'music-maven-stage-master/103/'
diff --git a/releases/3.2.35.yaml b/releases/3.2.35.yaml
new file mode 100644
index 00000000..012d8245
--- /dev/null
+++ b/releases/3.2.35.yaml
@@ -0,0 +1,5 @@
+---
+distribution_type: 'maven'
+version: '3.2.35'
+project: 'music'
+log_dir: 'music-maven-stage-master/140/'
diff --git a/releases/3.2.38-container.yaml b/releases/3.2.38-container.yaml
new file mode 100644
index 00000000..d745f053
--- /dev/null
+++ b/releases/3.2.38-container.yaml
@@ -0,0 +1,8 @@
+distribution_type: 'container'
+container_release_tag: '3.2.38'
+project: 'music'
+log_dir: 'music-maven-docker-stage-master/336'
+ref: fd5224f4aaf68e6ae186ef8a163edd7f5b2966f7
+containers:
+ - name: 'music/music_sb'
+ version: '3.2.38-latest'
diff --git a/releases/3.2.38.yaml b/releases/3.2.38.yaml
new file mode 100644
index 00000000..086fc3a0
--- /dev/null
+++ b/releases/3.2.38.yaml
@@ -0,0 +1,5 @@
+---
+distribution_type: 'maven'
+version: '3.2.38'
+project: 'music'
+log_dir: 'music-maven-stage-master/353/'
diff --git a/releases/3.2.39-container.yaml b/releases/3.2.39-container.yaml
new file mode 100644
index 00000000..51731116
--- /dev/null
+++ b/releases/3.2.39-container.yaml
@@ -0,0 +1,8 @@
+distribution_type: 'container'
+container_release_tag: '3.2.39'
+project: 'music'
+log_dir: 'music-maven-docker-stage-master/338'
+ref: 99f396136789182931fbded1127856247593d91b
+containers:
+ - name: 'music/music_sb'
+ version: '3.2.39-latest'
diff --git a/releases/3.2.39.yaml b/releases/3.2.39.yaml
new file mode 100644
index 00000000..8d0abaa0
--- /dev/null
+++ b/releases/3.2.39.yaml
@@ -0,0 +1,5 @@
+---
+distribution_type: 'maven'
+version: '3.2.39'
+project: 'music'
+log_dir: 'music-maven-stage-master/354/'
diff --git a/releases/3.2.40-container.yaml b/releases/3.2.40-container.yaml
new file mode 100644
index 00000000..5353ecfb
--- /dev/null
+++ b/releases/3.2.40-container.yaml
@@ -0,0 +1,8 @@
+distribution_type: 'container'
+container_release_tag: '3.2.40'
+project: 'music'
+log_dir: 'music-maven-docker-stage-master/340'
+ref: 0c173cdf44af313e376f1e8ae4fd6e6973c6c20b
+containers:
+ - name: 'music/music_sb'
+ version: '3.2.40-latest'
diff --git a/releases/3.2.40.yaml b/releases/3.2.40.yaml
new file mode 100644
index 00000000..1fc4307c
--- /dev/null
+++ b/releases/3.2.40.yaml
@@ -0,0 +1,5 @@
+---
+distribution_type: 'maven'
+version: '3.2.40'
+project: 'music'
+log_dir: 'music-maven-stage-master/357/'
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 8cacc369..00000000
--- a/src/main/java/org/onap/music/conductor/conditionals/JsonConditional.java
+++ /dev/null
@@ -1,89 +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 transient Map<String,Object> tableValues;
- private transient Map<String,Object> casscadeColumnData;
- private Map<String,Map<String,String>> conditions;
-
- public Map<String, Object> getTableValues() {
- return tableValues;
- }
- public void setTableValues(Map<String, Object> tableValues) {
- this.tableValues = tableValues;
- }
-
- public String getPrimaryKey() {
- return primaryKey;
- }
- public String getPrimaryKeyValue() {
- return primaryKeyValue;
- }
- public String getCasscadeColumnName() {
- return casscadeColumnName;
- }
-
- public Map<String, Object> getCasscadeColumnData() {
- return casscadeColumnData;
- }
-
-
-
- public void setPrimaryKey(String primaryKey) {
- this.primaryKey = primaryKey;
- }
- public void setPrimaryKeyValue(String primaryKeyValue) {
- this.primaryKeyValue = primaryKeyValue;
- }
- public Map<String, Map<String, String>> getConditions() {
- return conditions;
- }
- public void setConditions(Map<String, Map<String, String>> conditions) {
- this.conditions = conditions;
- }
- public void setCasscadeColumnName(String casscadeColumnName) {
- this.casscadeColumnName = casscadeColumnName;
- }
-
- public void setCasscadeColumnData(Map<String, Object> 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 d5e9e4d5..00000000
--- a/src/main/java/org/onap/music/conductor/conditionals/MusicConditional.java
+++ /dev/null
@@ -1,358 +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.PrintWriter;
-import java.io.StringWriter;
-import java.util.HashMap;
-import java.util.Map;
-
-import org.codehaus.jettison.json.JSONObject;
-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.lockingservice.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.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);
- private static final String CRITICAL = "critical";
-
- public static ReturnType conditionalInsert(String keyspace, String tablename, String casscadeColumnName,
- Map<String, Object> casscadeColumnData, String primaryKey, Map<String, Object> valuesMap,
- Map<String, String> status) throws Exception {
-
- Map<String, PreparedQueryObject> queryBank = new HashMap<>();
- TableMetadata tableInfo = null;
- tableInfo = MusicCore.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();
- Map<String, String> updateColumnvalues = new HashMap<>(); //casscade column values
- 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);
-
-
- Map<String, String> insertColumnvalues = new HashMap<>();//casscade column values
- 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 = MusicCore.createLockReference(key);
- 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.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED);
- MusicCore.destroyLockRef(lockId);
- return new ReturnType(ResultType.FAILURE, e.getMessage());
- }
-
- }
-
- public static ReturnType conditionalInsertAtomic(String lockId, String keyspace, String tableName,
- String primaryKey, Map<String, PreparedQueryObject> queryBank) {
-
- ResultSet results = null;
-
- try {
-
- MusicLockState mls = MusicCore.getLockingServiceHandle()
- .getLockState(keyspace + "." + tableName + "." + primaryKey);
- if (mls.getLockHolder().equals(lockId)) {
- try {
- results = MusicCore.getDSHandle().executeCriticalGet(queryBank.get(MusicUtil.SELECT));
- } catch (Exception e) {
- return new ReturnType(ResultType.FAILURE, e.getMessage());
- }
- if (results.all().isEmpty()) {
- MusicCore.getDSHandle().executePut(queryBank.get(MusicUtil.INSERT), CRITICAL);
- return new ReturnType(ResultType.SUCCESS, "insert");
- } else {
- MusicCore.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));
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- String exceptionAsString = sw.toString();
- return new ReturnType(ResultType.FAILURE,
- "Exception thrown while doing the critical put, check sanctity of the row/conditions:\n"
- + exceptionAsString);
- }
-
- }
-
- public static ReturnType update(Map<String,PreparedQueryObject> queryBank, String keyspace, String tableName, String primaryKey,String primaryKeyValue,String planId,String cascadeColumnName,Map<String,String> cascadeColumnValues) {
-
- String key = keyspace + "." + tableName + "." + primaryKeyValue;
- String lockId = MusicCore.createLockReference(key);
- long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
- ReturnType lockAcqResult = MusicCore.acquireLockWithLease(key, lockId, leasePeriod);
-
- try {
-
- if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
- return updateAtomic(lockId, keyspace, tableName, primaryKey,primaryKeyValue, queryBank,planId,cascadeColumnValues,cascadeColumnName);
-
- } else {
- MusicCore.destroyLockRef(lockId);
- return lockAcqResult;
- }
-
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- MusicCore.destroyLockRef(lockId);
- return new ReturnType(ResultType.FAILURE, e.getMessage());
-
- }
- }
-
- public static ReturnType updateAtomic(String lockId, String keyspace, String tableName, String primaryKey,String primaryKeyValue,
- Map<String,PreparedQueryObject> queryBank,String planId,Map<String,String> cascadeColumnValues,String casscadeColumnName) {
- try {
-
- MusicLockState mls = MusicCore.getLockingServiceHandle()
- .getLockState(keyspace + "." + tableName + "." + primaryKeyValue);
- if (mls.getLockHolder().equals(lockId)) {
- Row row = MusicCore.getDSHandle().executeCriticalGet(queryBank.get(MusicUtil.SELECT)).one();
-
- if(row != null) {
- Map<String, String> updatedValues = cascadeColumnUpdateSpecific(row, cascadeColumnValues, casscadeColumnName, planId);
- JSONObject json = new JSONObject(updatedValues);
- PreparedQueryObject update = new PreparedQueryObject();
- String vector_ts = String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
- update.appendQueryString("UPDATE " + keyspace + "." + tableName + " SET " + casscadeColumnName + "['" + planId
- + "'] = ?, vector_ts = ? WHERE " + primaryKey + " = ?");
- update.addValue(MusicUtil.convertToActualDataType(DataType.text(), json.toString()));
- update.addValue(MusicUtil.convertToActualDataType(DataType.text(), vector_ts));
- update.addValue(MusicUtil.convertToActualDataType(DataType.text(), primaryKeyValue));
- try {
- MusicCore.getDSHandle().executePut(update, CRITICAL);
- } catch (Exception ex) {
- return new ReturnType(ResultType.FAILURE, ex.getMessage());
- }
- }else {
- return new ReturnType(ResultType.FAILURE,"Cannot find data related to key: "+primaryKey);
- }
- MusicCore.getDSHandle().executePut(queryBank.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) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- StringWriter sw = new StringWriter();
- e.printStackTrace(new PrintWriter(sw));
- String exceptionAsString = sw.toString();
- 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<String, String> getValues(boolean isExists, Map<String, Object> casscadeColumnData,
- Map<String, String> status) {
-
- Map<String, String> value = new HashMap<>();
- Map<String, String> returnMap = new HashMap<>();
- Object key = casscadeColumnData.get("key");
- String setStatus = "";
- value = (Map<String, String>) 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<String, Object> 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());
- queryObject.addValue(vector);
- if(casscadeColumn!=null && casscadeColumnValues!=null) {
- fieldsString.append("" +casscadeColumn+" ," );
- valueString.append("?,");
- queryObject.addValue(casscadeColumnValues);
- }
-
- int counter = 0;
- for (Map.Entry<String, Object> 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);
-
- }
-
- Object formattedValue = null;
- try {
- formattedValue = MusicUtil.convertToActualDataType(colType, valueObj);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
- }
-
- 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<String, String> cascadeColumnUpdateSpecific(Row row, Map<String, String> changeOfStatus,
- String cascadeColumnName, String planId) {
-
- ColumnDefinitions colInfo = row.getColumnDefinitions();
- DataType colType = colInfo.getType(cascadeColumnName);
- Map<String, String> values = new HashMap<>();
- Object columnValue = getColValue(row, cascadeColumnName, colType);
-
- Map<String, String> finalValues = new HashMap<>();
- values = (Map<String, String>) 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 eb466754..00000000
--- a/src/main/java/org/onap/music/conductor/conditionals/RestMusicConditionalAPI.java
+++ /dev/null
@@ -1,220 +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.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.codehaus.jettison.json.JSONObject;
-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.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 org.onap.music.rest.RestMusicAdminAPI;
-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(RestMusicAdminAPI.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 = "Major Version", required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Major Version", 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<String, Object> tableValues = jsonObj.getTableValues();
- Map<String, Object> casscadeColumnData = jsonObj.getCasscadeColumnData();
- Map<String, Map<String, String>> 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<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
-
- Map<String, Object> authMap = null;
- try {
- authMap = MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "insertIntoTable");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
- ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
- }
- if (authMap.containsKey("aid"))
- authMap.remove("aid");
- if (!authMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
- ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED).entity(
- new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap())
- .build();
- }
-
- Map<String, Object> valuesMap = new LinkedHashMap<>();
- for (Map.Entry<String, Object> entry : tableValues.entrySet()) {
- valuesMap.put(entry.getKey(), entry.getValue());
- }
-
- Map<String, String> status = new HashMap<>();
- status.put("exists", conditions.get("exists").get("status").toString());
- status.put("nonexists", conditions.get("nonexists").get("status").toString());
- 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<String, Object> casscadeColumnData = upObj.getCasscadeColumnData();
- Map<String, Object> 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<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
-
- Map<String, Object> authMap = null;
- try {
- authMap = MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "updateTable");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
- ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED)
- .entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
- }
- if (authMap.containsKey("aid"))
- authMap.remove("aid");
- if (!authMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO, ErrorSeverity.CRITICAL,
- ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED).entity(
- new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Exception"))).toMap())
- .build();
- }
-
- String planId = casscadeColumnData.get("key").toString();
- Map<String,String> casscadeColumnValueMap = (Map<String, String>) casscadeColumnData.get("value");
- TableMetadata tableInfo = null;
- tableInfo = MusicCore.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<String,PreparedQueryObject> queryBank = new HashMap<>();
- queryBank.put(MusicUtil.SELECT, select);
- queryBank.put(MusicUtil.UPSERT, upsert);
- ReturnType result = MusicConditional.update(queryBank, keyspace, tablename, primaryKey,primaryKeyValue,planId,casscadeColumnName,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/datastore/MusicDataStore.java b/src/main/java/org/onap/music/datastore/MusicDataStore.java
deleted file mode 100644
index 21b0053f..00000000
--- a/src/main/java/org/onap/music/datastore/MusicDataStore.java
+++ /dev/null
@@ -1,483 +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.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.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.PreparedStatement;
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.Row;
-import com.datastax.driver.core.Session;
-import com.datastax.driver.core.TableMetadata;
-import com.datastax.driver.core.exceptions.AlreadyExistsException;
-import com.datastax.driver.core.exceptions.InvalidQueryException;
-import com.datastax.driver.core.exceptions.NoHostAvailableException;
-import com.sun.jersey.core.util.Base64;
-
-/**
- * @author nelson24
- *
- */
-public class MusicDataStore {
-
- 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;
- }
-
-
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicDataStore.class);
-
- /**
- *
- */
- public MusicDataStore() {
- connectToCassaCluster();
- }
-
-
- /**
- * @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());
- }
- }
-
- /**
- *
- * @return
- */
- private ArrayList<String> getAllPossibleLocalIps() {
- ArrayList<String> allPossibleIps = new ArrayList<String>();
- try {
- Enumeration<NetworkInterface> en = NetworkInterface.getNetworkInterfaces();
- while (en.hasMoreElements()) {
- NetworkInterface ni = (NetworkInterface) en.nextElement();
- Enumeration<InetAddress> ee = ni.getInetAddresses();
- while (ee.hasMoreElements()) {
- InetAddress ia = (InetAddress) ee.nextElement();
- allPossibleIps.add(ia.getHostAddress());
- }
- }
- } catch (SocketException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.CONNCECTIVITYERROR, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
- }catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
- }
- return allPossibleIps;
- }
-
- /**
- * This method iterates through all available IP addresses and connects to multiple cassandra
- * clusters.
- */
- private void connectToCassaCluster() {
- Iterator<String> it = getAllPossibleLocalIps().iterator();
- String address = "localhost";
- String[] addresses = null;
- address = MusicUtil.getMyCassaHost();
- addresses = address.split(",");
-
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Connecting to cassa cluster: Iterating through possible ips:"
- + getAllPossibleLocalIps());
- PoolingOptions poolingOptions = new PoolingOptions();
- poolingOptions
- .setConnectionsPerHost(HostDistance.LOCAL, 4, 10)
- .setConnectionsPerHost(HostDistance.REMOTE, 2, 4);
- while (it.hasNext()) {
- try {
- if(MusicUtil.getCassName() != null && MusicUtil.getCassPwd() != null) {
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Building with credentials "+MusicUtil.getCassName()+" & "+MusicUtil.getCassPwd());
- cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort())
- .withCredentials(MusicUtil.getCassName(), MusicUtil.getCassPwd())
- //.withLoadBalancingPolicy(new RoundRobinPolicy())
- .withPoolingOptions(poolingOptions)
- .addContactPoints(addresses).build();
- }
- else
- cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort())
- //.withLoadBalancingPolicy(new RoundRobinPolicy())
- .addContactPoints(addresses).build();
-
- Metadata metadata = cluster.getMetadata();
- logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster "
- + metadata.getClusterName() + " at " + address);
- session = cluster.connect();
-
- break;
- } catch (NoHostAvailableException e) {
- address = it.next();
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.HOSTUNAVAILABLE, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
- }
- }
- }
-
- /**
- *
- */
- 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) {
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Building with credentials "+MusicUtil.getCassName()+" & "+MusicUtil.getCassPwd());
- cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort())
- .withCredentials(MusicUtil.getCassName(), MusicUtil.getCassPwd())
- //.withLoadBalancingPolicy(new RoundRobinPolicy())
- .withPoolingOptions(poolingOptions)
- .addContactPoints(addresses).build();
- }
- else {
- cluster = Cluster.builder().withPort(MusicUtil.getCassandraPort())
- //.withLoadBalancingPolicy(new RoundRobinPolicy())
- .withPoolingOptions(poolingOptions)
- .addContactPoints(addresses).build();
- }
- Metadata metadata = cluster.getMetadata();
- logger.info(EELFLoggerDelegate.applicationLogger, "Connected to cassa cluster "
- + metadata.getClusterName() + " at " + address);
- try {
- session = cluster.connect();
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.CASSANDRACONNECTIVITY, ErrorSeverity.ERROR, ErrorTypes.SERVICEUNAVAILABLE);
- 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);
- }
-
-
- /**
- * 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);
- byte[] data = bb.array();
- return data;
- }
-
- public boolean doesRowSatisfyCondition(Row row, Map<String, Object> condition) throws Exception {
- ColumnDefinitions colInfo = row.getColumnDefinitions();
-
- for (Map.Entry<String, Object> 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))
- return false;
- }
- return true;
- }
-
- /**
- * Utility function to store ResultSet values in to a MAP for output.
- *
- * @param results
- * @return MAP
- */
- public Map<String, HashMap<String, Object>> marshalData(ResultSet results) {
- Map<String, HashMap<String, Object>> resultMap =
- new HashMap<String, HashMap<String, Object>>();
- int counter = 0;
- for (Row row : results) {
- ColumnDefinitions colInfo = row.getColumnDefinitions();
- HashMap<String, Object> resultOutput = new HashMap<String, Object>();
- for (Definition definition : colInfo) {
- if (!definition.getName().equals("vector_ts")) {
- 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
- /**
- * 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)
- throws MusicServiceException, MusicQueryException {
-
- boolean result = false;
-
- 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.info(EELFLoggerDelegate.applicationLogger,
- "In preprared Execute Put: the actual insert query:"
- + queryObject.getQuery() + "; the values"
- + queryObject.getValues());
- PreparedStatement preparedInsert = null;
- try {
-
- preparedInsert = session.prepare(queryObject.getQuery());
-
- } catch(InvalidQueryException iqe) {
- logger.error(EELFLoggerDelegate.errorLogger, iqe.getMessage(),AppMessages.QUERYERROR, ErrorSeverity.CRITICAL, ErrorTypes.QUERYERROR);
- throw new MusicQueryException(iqe.getMessage());
- }catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.QUERYERROR, ErrorSeverity.CRITICAL, ErrorTypes.QUERYERROR);
- throw new MusicQueryException(e.getMessage());
- }
-
- try {
- 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");
- preparedInsert.setConsistencyLevel(ConsistencyLevel.ONE);
- }
-
- ResultSet rs = session.execute(preparedInsert.bind(queryObject.getValues().toArray()));
- result = rs.wasApplied();
-
- }
- catch (AlreadyExistsException ae) {
- logger.error(EELFLoggerDelegate.errorLogger, ae.getMessage(),AppMessages.SESSIONFAILED+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicServiceException(ae.getMessage());
- }
- catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.SESSIONFAILED+ " [" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicQueryException("Executing Session Failure for Request = " + "["
- + queryObject.getQuery() + "]" + " Reason = " + e.getMessage());
- }
-
-
- 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 {
-
- 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 {
- PreparedStatement preparedEventualGet = session.prepare(queryObject.getQuery());
- preparedEventualGet.setConsistencyLevel(ConsistencyLevel.ONE);
- results = session.execute(preparedEventualGet.bind(queryObject.getValues().toArray()));
-
- } catch (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(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR+ "[" + queryObject.getQuery() + "]", ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- throw new MusicServiceException(ex.getMessage());
- }
- return results;
-
- }
-
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JSONCallbackResponse.java b/src/main/java/org/onap/music/datastore/jsonobjects/JSONCallbackResponse.java
deleted file mode 100755
index f869c342..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JSONCallbackResponse.java
+++ /dev/null
@@ -1,89 +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 java.util.List;
-import java.util.Map;
-
-public class JSONCallbackResponse {
-
- private String full_table;
- private String keyspace;
- private Map<String, String> changeValue;
- private String operation;
- private String table_name;
- private String primary_key;
- private Object miscObjects;
- private List<String> updateList;
-
- public String getFull_table() {
- return full_table;
- }
- public void setFull_table(String full_table) {
- this.full_table = full_table;
- }
- public String getKeyspace() {
- return keyspace;
- }
- public void setKeyspace(String keyspace) {
- this.keyspace = keyspace;
- }
- public String getOperation() {
- return operation;
- }
- public void setOperation(String operation) {
- this.operation = operation;
- }
- public String getTable_name() {
- return table_name;
- }
- public void setTable_name(String table_name) {
- this.table_name = table_name;
- }
- public String getPrimary_key() {
- return primary_key;
- }
- public void setPrimary_key(String primary_key) {
- this.primary_key = primary_key;
- }
- public Object getMiscObjects() {
- return miscObjects;
- }
- public void setMiscObjects(Object miscObjects) {
- this.miscObjects = miscObjects;
- }
- public void setChangeValue(Map<String, String> changeValue) {
- this.changeValue = changeValue;
- }
- public Map<String, String> getChangeValue() {
- return changeValue;
- }
- public List<String> getUpdateList() {
- return updateList;
- }
- public void setUpdateList(List<String> updateList) {
- this.updateList = updateList;
- }
-
-
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonCallback.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonCallback.java
deleted file mode 100755
index 4a865320..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonCallback.java
+++ /dev/null
@@ -1,135 +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 java.io.Serializable;
-import java.util.Map;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-import io.swagger.annotations.ApiModel;
-import io.swagger.annotations.ApiModelProperty;
-
-@ApiModel(value = "JsonCallback", description = "Json model for callback")
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class JsonCallback implements Serializable {
- private String applicationName;
- private String applicationUsername;
- private String applicationPassword;
- private String applicationNotificationEndpoint;
- private String notifyOn;
- private String notifyWhenChangeIn;
- private String notifyWhenInsertsIn;
- private String notifyWhenDeletesIn;
- private Map<String, String> responseBody;
-
- private String uuid;
-
- public String getUuid() {
- return uuid;
- }
-
- public void setUuid(String uuid) {
- this.uuid = uuid;
- }
-
- @ApiModelProperty(value = "application name")
- public String getApplicationName() {
- return applicationName;
- }
-
- public void setApplicationName(String applicationName) {
- this.applicationName = applicationName;
- }
-
- @ApiModelProperty(value = "notify On")
- public String getNotifyOn() {
- return notifyOn;
- }
-
- public void setNotifyOn(String notifyOn) {
- this.notifyOn = notifyOn;
- }
-
- @ApiModelProperty(value = "application User name")
- public String getApplicationUsername() {
- return applicationUsername;
- }
-
- public void setApplicationUsername(String applicationUsername) {
- this.applicationUsername = applicationUsername;
- }
-
- @ApiModelProperty(value = "application password")
- public String getApplicationPassword() {
- return applicationPassword;
- }
-
- public void setApplicationPassword(String applicationPassword) {
- this.applicationPassword = applicationPassword;
- }
-
- @ApiModelProperty(value = "application notification endpoint")
- public String getApplicationNotificationEndpoint() {
- return applicationNotificationEndpoint;
- }
-
- public void setApplicationNotificationEndpoint(String applicationNotificationEndpoint) {
- this.applicationNotificationEndpoint = applicationNotificationEndpoint;
- }
-
- @ApiModelProperty(value = "notify when updates")
- public String getNotifyWhenChangeIn() {
- return notifyWhenChangeIn;
- }
-
- public void setNotifyWhenChangeIn(String notifyWhenChangeIn) {
- this.notifyWhenChangeIn = notifyWhenChangeIn;
- }
-
- @ApiModelProperty(value = "notify when inserts")
- public String getNotifyWhenInsertsIn() {
- return notifyWhenInsertsIn;
- }
-
- public void setNotifyWhenInsertsIn(String notifyWhenInsertsIn) {
- this.notifyWhenInsertsIn = notifyWhenInsertsIn;
- }
-
- @ApiModelProperty(value = "notify when deletes")
- public String getNotifyWhenDeletesIn() {
- return notifyWhenDeletesIn;
- }
-
- public void setNotifyWhenDeletesIn(String notifyWhenDeletesIn) {
- this.notifyWhenDeletesIn = notifyWhenDeletesIn;
- }
-
- public Map<String, String> getResponseBody() {
- return responseBody;
- }
-
- public void setResponseBody(Map<String, String> responseBody) {
- this.responseBody = responseBody;
- }
-
-}
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 ce7f509b..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonDelete.java
+++ /dev/null
@@ -1,89 +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 java.util.ArrayList;
-import java.util.Map;
-
-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 ArrayList<String> columns = null;
- private Map<String, String> consistencyInfo;
- private Map<String, Object> conditions;
- String ttl;
- String timestamp;
-
-
- @ApiModelProperty(value = "Conditions")
- public Map<String, Object> getConditions() {
- return conditions;
- }
-
- public void setConditions(Map<String, Object> conditions) {
- this.conditions = conditions;
- }
-
- @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic")
- public Map<String, String> getConsistencyInfo() {
- return consistencyInfo;
- }
-
- public void setConsistencyInfo(Map<String, String> consistencyInfo) {
- this.consistencyInfo = consistencyInfo;
- }
-
- @ApiModelProperty(value = "Column values")
- public ArrayList<String> getColumns() {
- return columns;
- }
-
- public void setColumns(ArrayList<String> 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;
- }
-}
-
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 c79ba9b7..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonInsert.java
+++ /dev/null
@@ -1,132 +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 java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.Map;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-import io.swagger.annotations.ApiModel;
-import io.swagger.annotations.ApiModelProperty;
-
-@ApiModel(value = "JsonTable", description = "Json model for table vlaues insert")
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class JsonInsert implements Serializable {
- private String keyspaceName;
- private String tableName;
- private transient Map<String, Object> values;
- private String ttl;
- private String timestamp;
- private transient Map<String, Object> row_specification;
- private Map<String, String> consistencyInfo;
- private Map<String, byte[]> objectMap;
-
- @ApiModelProperty(value = "objectMap")
- public Map<String, byte[]> getObjectMap() {
- return objectMap;
- }
-
- public void setObjectMap(Map<String, byte[]> 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<String, String> getConsistencyInfo() {
- return consistencyInfo;
- }
-
- public void setConsistencyInfo(Map<String, String> consistencyInfo) {
- this.consistencyInfo = consistencyInfo;
- }
-
- @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;
- }
-
- @ApiModelProperty(value = "values returned")
- public Map<String, Object> getValues() {
- return values;
- }
-
- public void setValues(Map<String, Object> values) {
- this.values = values;
- }
-
- @ApiModelProperty(value = "Information for selecting specific rows for insert")
- public Map<String, Object> getRow_specification() {
- return row_specification;
- }
-
- public void setRow_specification(Map<String, Object> row_specification) {
- this.row_specification = row_specification;
- }
-
- public byte[] serialize() {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ObjectOutput out = null;
- try {
- out = new ObjectOutputStream(bos);
- out.writeObject(this);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return bos.toByteArray();
- }
-
-}
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 54de02fd..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonKeySpace.java
+++ /dev/null
@@ -1,77 +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 java.util.Map;
-
-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 String keyspaceName;
- private Map<String, Object> replicationInfo;
- private String durabilityOfWrites;
- private Map<String, String> consistencyInfo;
-
- @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic")
- public Map<String, String> getConsistencyInfo() {
- return consistencyInfo;
- }
-
- public void setConsistencyInfo(Map<String, String> consistencyInfo) {
- this.consistencyInfo = consistencyInfo;
- }
-
- @ApiModelProperty(value = "Replication information")
- public Map<String, Object> getReplicationInfo() {
- return replicationInfo;
- }
-
- public void setReplicationInfo(Map<String, Object> 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;
- }
-
-
-
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonNotification.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonNotification.java
deleted file mode 100755
index ce244e2c..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonNotification.java
+++ /dev/null
@@ -1,119 +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 java.io.Serializable;
-import java.util.Map;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-import com.fasterxml.jackson.annotation.JsonInclude;
-import com.fasterxml.jackson.annotation.JsonInclude.Include;
-
-import io.swagger.annotations.ApiModel;
-
-@ApiModel(value = "JsonNotification", description = "Json model for callback")
-@JsonIgnoreProperties(ignoreUnknown = true)
-@JsonInclude(Include.NON_NULL)
-public class JsonNotification implements Serializable {
-
- private String notify_field;
- private String endpoint;
- private String username;
- private String password;
- private String notify_change;
- private String notify_insert;
- private String notify_delete;
- private String operation_type;
- private String triggerName;
- private Map<String, String> response_body;
-
- public String getNotify_field() {
- return notify_field;
- }
- public void setNotify_field(String notify_field) {
- this.notify_field = notify_field;
- }
- public String getEndpoint() {
- return endpoint;
- }
- public void setEndpoint(String endpoint) {
- this.endpoint = endpoint;
- }
- 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 Map<String, String> getResponse_body() {
- return response_body;
- }
- public void setResponse_body(Map<String, String> response_body) {
- this.response_body = response_body;
- }
- public String getNotify_change() {
- return notify_change;
- }
- public void setNotify_change(String notify_change) {
- this.notify_change = notify_change;
- }
- public String getNotify_insert() {
- return notify_insert;
- }
- public void setNotify_insert(String notify_insert) {
- this.notify_insert = notify_insert;
- }
- public String getNotify_delete() {
- return notify_delete;
- }
- public void setNotify_delete(String notify_delete) {
- this.notify_delete = notify_delete;
- }
- public String getOperation_type() {
- return operation_type;
- }
- public void setOperation_type(String operation_type) {
- this.operation_type = operation_type;
- }
- public String getTriggerName() {
- return triggerName;
- }
- public void setTriggerName(String triggerName) {
- this.triggerName = triggerName;
- }
- @Override
- public String toString() {
- try {
- return new com.fasterxml.jackson.databind.ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);
- } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
- return notify_field+ " : "+endpoint+ " : "+username+ " : "+password+ " : "+response_body;
- }
-
- }
-
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonNotifyClientResponse.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonNotifyClientResponse.java
deleted file mode 100644
index 963352d0..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonNotifyClientResponse.java
+++ /dev/null
@@ -1,59 +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 java.io.Serializable;
-
-import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
-
-import io.swagger.annotations.ApiModel;
-
-@ApiModel(value = "JsonNotifyClientResponse", description = "Json model for callback")
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class JsonNotifyClientResponse implements Serializable {
- private String message;
- private String status;
-
- public String getMessage() {
- return message;
- }
- public void setMessage(String message) {
- this.message = message;
- }
- public String getStatus() {
- return status;
- }
- public void setStatus(String status) {
- this.status = status;
- }
-
- @Override
- public String toString() {
- try {
- return new com.fasterxml.jackson.databind.ObjectMapper().writerWithDefaultPrettyPrinter().writeValueAsString(this);
- } catch (com.fasterxml.jackson.core.JsonProcessingException e) {
- return message+ " : "+status;
- }
-
- }
-
-}
diff --git a/src/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java b/src/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java
deleted file mode 100755
index 0bac1e31..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonOnboard.java
+++ /dev/null
@@ -1,83 +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 = "JsonOnboard", description = "Defines the Json for Onboarding an application.")
-@JsonIgnoreProperties(ignoreUnknown = true)
-public class JsonOnboard {
- private String appname;
- private String userId;
- private String password;
- private String isAAF;
- private String aid;
-
- @ApiModelProperty(value = "Application Password")
- public String getPassword() {
- return password;
- }
-
- public void setPassword(String password) {
- this.password = password;
- }
-
- @ApiModelProperty(value = "Application UUID")
- public String getAid() {
- return aid;
- }
-
- public void setAid(String aid) {
- this.aid = aid;
- }
-
- @ApiModelProperty(value = "Application name")
- public String getAppname() {
- return appname;
- }
-
- public void setAppname(String appname) {
- this.appname = appname;
- }
-
- @ApiModelProperty(value = "User Id")
- public String getUserId() {
- return userId;
- }
-
- public void setUserId(String userId) {
- this.userId = userId;
- }
-
- @ApiModelProperty(value = "Is AAF Application", allowableValues = "true, false")
- public String getIsAAF() {
- return isAAF;
- }
-
- public void setIsAAF(String isAAF) {
- this.isAAF = isAAF;
- }
-
-}
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 2e0a5ded..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonTable.java
+++ /dev/null
@@ -1,144 +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 java.util.Map;
-
-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 String keyspaceName;
- private String tableName;
-
- private Map<String, String> fields;
- private Map<String, Object> properties;
- private String primaryKey;
- private String sortingKey;
- private String partitionKey;
- private String clusteringKey;
- private String filteringKey;
- private String clusteringOrder;
- private Map<String, String> consistencyInfo;
-
- @ApiModelProperty(value = "Consistency level", allowableValues = "eventual,critical,atomic")
- public Map<String, String> getConsistencyInfo() {
- return consistencyInfo;
- }
-
- public void setConsistencyInfo(Map<String, String> consistencyInfo) {
- this.consistencyInfo = consistencyInfo;
- }
-
- @ApiModelProperty(value = "Properties")
- public Map<String, Object> getProperties() {
- return properties;
- }
-
- public void setProperties(Map<String, Object> properties) {
- this.properties = properties;
- }
-
- @ApiModelProperty(value = "Fields")
- public Map<String, String> getFields() {
- return fields;
- }
-
- public void setFields(Map<String, String> 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 = "Sorting Key")
- public String getSortingKey() {
- return sortingKey;
- }
-
- public void setSortingKey(String sortingKey) {
- this.sortingKey = sortingKey;
- }
-
- @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;
- }
-
-
-}
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 c1a56819..00000000
--- a/src/main/java/org/onap/music/datastore/jsonobjects/JsonUpdate.java
+++ /dev/null
@@ -1,133 +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 java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.ObjectOutput;
-import java.io.ObjectOutputStream;
-import java.io.Serializable;
-import java.util.Map;
-
-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<String, Object> values;
- private String ttl;
- private String timestamp;
- private Map<String, String> consistencyInfo;
- private transient Map<String, Object> conditions;
- private transient Map<String, Object> row_specification;
-
- @ApiModelProperty(value = "Conditions")
- public Map<String, Object> getConditions() {
- return conditions;
- }
-
- public void setConditions(Map<String, Object> conditions) {
- this.conditions = conditions;
- }
-
- @ApiModelProperty(value = "Information for selecting sepcific rows")
- public Map<String, Object> getRow_specification() {
- return row_specification;
- }
-
- public void setRow_specification(Map<String, Object> row_specification) {
- this.row_specification = row_specification;
- }
-
-
- @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<String, String> getConsistencyInfo() {
- return consistencyInfo;
- }
-
- public void setConsistencyInfo(Map<String, String> 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<String, Object> getValues() {
- return values;
- }
-
- public void setValues(Map<String, Object> values) {
- this.values = values;
- }
-
- public byte[] serialize() {
- ByteArrayOutputStream bos = new ByteArrayOutputStream();
- ObjectOutput out = null;
- try {
- out = new ObjectOutputStream(bos);
- out.writeObject(this);
- } catch (IOException e) {
- e.printStackTrace();
- }
- return bos.toByteArray();
- }
-
-}
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 af6e6151..00000000
--- a/src/main/java/org/onap/music/eelf/healthcheck/MusicHealthCheck.java
+++ /dev/null
@@ -1,151 +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.healthcheck;
-
-import java.util.UUID;
-
-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.MusicServiceException;
-import org.onap.music.lockingservice.MusicLockingService;
-import org.onap.music.main.MusicCore;
-import org.onap.music.main.MusicUtil;
-import org.onap.music.main.ResultType;
-
-import com.datastax.driver.core.ConsistencyLevel;
-
-/**
- * @author inam
- *
- */
-public class MusicHealthCheck {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
-
- private String cassandrHost;
- private String zookeeperHost;
-
- public String getCassandraStatus(String consistency) {
- logger.info(EELFLoggerDelegate.applicationLogger, "Getting Status for Cassandra");
-
- boolean result = false;
- try {
- result = getAdminKeySpace(consistency);
- } catch(Exception e) {
- if(e.getMessage().toLowerCase().contains("unconfigured table healthcheck")) {
- logger.error("Error", e);
- logger.debug("Creating table....");
- boolean ksresult = createKeyspace();
- if(ksresult)
- try {
- result = getAdminKeySpace(consistency);
- } catch (MusicServiceException e1) {
- // TODO Auto-generated catch block
- logger.error("Error", e);
- e1.printStackTrace();
- }
- } else {
- logger.error("Error", e);
- return "One or more nodes are down or not responding.";
- }
- }
- if (result) {
- return "ACTIVE";
- } else {
- logger.info(EELFLoggerDelegate.applicationLogger, "Cassandra Service is not responding");
- return "INACTIVE";
- }
- }
-
- private Boolean getAdminKeySpace(String consistency) throws MusicServiceException {
-
-
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString("insert into admin.healthcheck (id) values (?)");
- pQuery.addValue(UUID.randomUUID());
- ResultType rs = MusicCore.nonKeyRelatedPut(pQuery, consistency);
- System.out.println(rs);
- if (rs != null) {
- return Boolean.TRUE;
- } else {
- return Boolean.FALSE;
- }
-
-
- }
-
- private boolean createKeyspace() {
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString("CREATE TABLE admin.healthcheck (id uuid PRIMARY KEY)");
- ResultType rs = null ;
- try {
- rs = MusicCore.nonKeyRelatedPut(pQuery, ConsistencyLevel.ONE.toString());
- } catch (MusicServiceException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- logger.error("Error", e);
- }
- if(rs != null && rs.getResult().toLowerCase().contains("success"))
- return true;
- else
- return false;
- }
-
- public String getZookeeperStatus() {
-
- String host = MusicUtil.getMyZkHost();
- logger.info(EELFLoggerDelegate.applicationLogger, "Getting Status for Zookeeper Host: " + host);
- try {
- MusicLockingService lockingService = MusicCore.getLockingServiceHandle();
- // additionally need to call the ZK to create,aquire and delete lock
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.LOCKINGERROR,
- ErrorTypes.CONNECTIONERROR, ErrorSeverity.CRITICAL);
- return "INACTIVE";
- }
-
- logger.info(EELFLoggerDelegate.applicationLogger, "Zookeeper is Active and Running");
- return "ACTIVE";
-
- }
-
- public String getCassandrHost() {
- return cassandrHost;
- }
-
- public void setCassandrHost(String cassandrHost) {
- this.cassandrHost = cassandrHost;
- }
-
- public String getZookeeperHost() {
- return zookeeperHost;
- }
-
- public void setZookeeperHost(String zookeeperHost) {
- this.zookeeperHost = zookeeperHost;
- }
-
-}
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 2c7952b2..00000000
--- a/src/main/java/org/onap/music/eelf/logging/format/AppMessages.java
+++ /dev/null
@@ -1,183 +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 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 - 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 ZK 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
- *
- */
-
-
-
-
- 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"),
- KEEPERERROR("[ERR502E]"," Zookeeper error has occured","","Please check zookeeper details"),
- 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");
-
-
-
- ErrorTypes eType;
- ErrorSeverity alarmSeverity;
- ErrorSeverity errorSeverity;
- String errorCode;
- String errorDescription;
- String details;
- String resolution;
-
-
- AppMessages(String errorCode, String errorDescription, String details,String resolution) {
-
- this.errorCode = errorCode;
- this.errorDescription = errorDescription;
- this.details = details;
- this.resolution = resolution;
- }
-
-
-
-
- AppMessages(ErrorTypes eType, ErrorSeverity alarmSeverity,
- ErrorSeverity errorSeverity, String errorCode, String errorDescription, String details,
- String resolution) {
-
- this.eType = eType;
- this.alarmSeverity = alarmSeverity;
- this.errorSeverity = errorSeverity;
- this.errorCode = errorCode;
- this.errorDescription = errorDescription;
- this.details = details;
- this.resolution = resolution;
- }
-
- public String getDetails() {
- return this.details;
- }
-
- public String getResolution() {
- return this.resolution;
- }
-
- public String getErrorCode() {
- return this.errorCode;
- }
-
- 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 b18c1771..00000000
--- a/src/main/java/org/onap/music/eelf/logging/format/ErrorCodes.java
+++ /dev/null
@@ -1,106 +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 ZK 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/lockingservice/MusicLockingService.java b/src/main/java/org/onap/music/lockingservice/MusicLockingService.java
deleted file mode 100644
index f9c09338..00000000
--- a/src/main/java/org/onap/music/lockingservice/MusicLockingService.java
+++ /dev/null
@@ -1,168 +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.lockingservice;
-
-
-import java.io.IOException;
-import java.util.StringTokenizer;
-import java.util.concurrent.CountDownLatch;
-
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.WatchedEvent;
-import org.apache.zookeeper.Watcher;
-import org.apache.zookeeper.Watcher.Event.KeeperState;
-import org.apache.zookeeper.ZooKeeper;
-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.MusicServiceException;
-import org.onap.music.main.CachingUtil;
-import org.onap.music.main.MusicUtil;
-
-
-public class MusicLockingService implements Watcher {
-
-
- private static final int SESSION_TIMEOUT = 180000;
- ZkStatelessLockService zkLockHandle = null;
- private CountDownLatch connectedSignal = new CountDownLatch(1);
- private static EELFLoggerDelegate logger =
- EELFLoggerDelegate.getLogger(MusicLockingService.class);
-
- public MusicLockingService() throws MusicServiceException {
- try {
- ZooKeeper zk = new ZooKeeper(MusicUtil.getMyZkHost(), SESSION_TIMEOUT, this);
- connectedSignal.await();
- zkLockHandle = new ZkStatelessLockService(zk);
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
- throw new MusicServiceException("IO Error has occured" + e.getMessage());
- } catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- throw new MusicServiceException("Exception Occured " + e.getMessage());
- }
- }
-
- public ZkStatelessLockService getzkLockHandle() {
- return zkLockHandle;
- }
-
- public MusicLockingService(String lockServer) {
- try {
- ZooKeeper zk = new ZooKeeper(lockServer, SESSION_TIMEOUT, this);
- connectedSignal.await();
- zkLockHandle = new ZkStatelessLockService(zk);
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.IOERROR, ErrorSeverity.ERROR, ErrorTypes.CONNECTIONERROR);
- }catch( InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }
- }
-
- public void createLockaIfItDoesNotExist(String lockName) {
- if (!zkLockHandle.checkIfLockExists(lockName)) {
- String lockHolder = null;
- MusicLockState ml = new MusicLockState(MusicLockState.LockStatus.UNLOCKED, lockHolder);
- byte[] data = ml.serialize();
- zkLockHandle.createLock(lockName, data);
- }
- }
-
- public void setLockState(String lockName, MusicLockState mls) {
- byte[] data = mls.serialize();
- zkLockHandle.setNodeData(lockName, data);
- }
-
- public MusicLockState getLockState(String lockName) throws MusicLockingException {
-
- byte[] data = null;
- try{
- data = zkLockHandle.getNodeData(lockName);
- }catch (Exception ex){
- logger.error(EELFLoggerDelegate.errorLogger, ex.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }
- if(data !=null)
- return MusicLockState.deSerialize(data);
- else {
- logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.INVALIDLOCK, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- throw new MusicLockingException("Invalid lock or acquire failed");
- }
- }
-
- public String createLockId(String lockName) {
- String lockIdWithSlash = zkLockHandle.createLockId(lockName);
- return lockIdWithSlash.replace('/', '$');
- }
-
- public boolean isMyTurn(String lockIdWithDollar) {
- String lockId = lockIdWithDollar.replace('$', '/');
- StringTokenizer st = new StringTokenizer(lockId);
- String lockName = "/" + st.nextToken("/");
- try {
- return zkLockHandle.lock(lockName, lockId);
- } catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.LOCKINGERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }catch( InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }catch(Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }
- return false;
- }
-
- public void unlockAndDeleteId(String lockIdWithDollar) throws KeeperException.NoNodeException {
- String lockId = lockIdWithDollar.replace('$', '/');
- zkLockHandle.unlock(lockId);
- CachingUtil.deleteKeysFromDB("'"+lockId+"'");
- }
-
- public void deleteLock(String lockName) throws MusicLockingException {
- if(lockIdExists(lockName))
- zkLockHandle.deleteLock(lockName);
- else{
- throw new MusicLockingException("Lock does not exist.Please check the lock: " + lockName + " and try again");
- }
- }
-
- public String whoseTurnIsIt(String lockName) {
- String lockHolder = zkLockHandle.currentLockHolder(lockName);
- return lockHolder.replace('/', '$');
-
- }
-
- public void process(WatchedEvent event) { // Watcher interface
- if (event.getState() == KeeperState.SyncConnected) {
- connectedSignal.countDown();
- }
- }
-
-
- public void close() {
- zkLockHandle.close();
- }
-
- public boolean lockIdExists(String lockIdWithDollar) {
- String lockId = lockIdWithDollar.replace('$', '/');
- return zkLockHandle.checkIfLockExists(lockId);
- }
-
-}
diff --git a/src/main/java/org/onap/music/lockingservice/ProtocolSupport.java b/src/main/java/org/onap/music/lockingservice/ProtocolSupport.java
deleted file mode 100644
index 19f49beb..00000000
--- a/src/main/java/org/onap/music/lockingservice/ProtocolSupport.java
+++ /dev/null
@@ -1,210 +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.lockingservice;
-
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.data.ACL;
-import org.apache.zookeeper.data.Stat;
-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.lockingservice.ZooKeeperOperation;
-import java.util.List;
-import java.util.concurrent.atomic.AtomicBoolean;
-
-/**
- * A base class for protocol implementations which provides a number of higher level helper methods
- * for working with ZooKeeper along with retrying synchronous operations if the connection to
- * ZooKeeper closes such as {@link #retryOperation(ZooKeeperOperation)}
- *
- */
-class ProtocolSupport {
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ProtocolSupport.class);
-
- protected ZooKeeper zookeeper;
- private AtomicBoolean closed = new AtomicBoolean(false);
- private long retryDelay = 500L;
- private int retryCount = 10;
- private List<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;
-
- /**
- * Closes this strategy and releases any ZooKeeper resources; but keeps the ZooKeeper instance
- * open
- */
- public void close() {
- if (closed.compareAndSet(false, true)) {
- doClose();
- }
- }
-
- /**
- * return zookeeper client instance
- *
- * @return zookeeper client instance
- */
- public ZooKeeper getZookeeper() {
- return zookeeper;
- }
-
- /**
- * return the acl its using
- *
- * @return the acl.
- */
- public List<ACL> getAcl() {
- return acl;
- }
-
- /**
- * set the acl
- *
- * @param acl the acl to set to
- */
- public void setAcl(List<ACL> acl) {
- this.acl = acl;
- }
-
- /**
- * get the retry delay in milliseconds
- *
- * @return the retry delay
- */
- public long getRetryDelay() {
- return retryDelay;
- }
-
- /**
- * Sets the time waited between retry delays
- *
- * @param retryDelay the retry delay
- */
- public void setRetryDelay(long retryDelay) {
- this.retryDelay = retryDelay;
- }
-
- /**
- * Allow derived classes to perform some custom closing operations to release resources
- */
- protected void doClose() {
- throw new UnsupportedOperationException();
- }
-
-
- /**
- * Perform the given operation, retrying if the connection fails
- *
- * @return object. it needs to be cast to the callee's expected return type.
- * @param operation FILL IN
- * @throws KeeperException FILL IN
- * @throws InterruptedException FILL IN
- */
- protected Object retryOperation(ZooKeeperOperation operation)
- throws KeeperException, InterruptedException {
- KeeperException exception = null;
- for (int i = 0; i < retryCount; i++) {
- try {
- return operation.execute();
- } catch (KeeperException.SessionExpiredException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.SESSIONEXPIRED+" for: " + zookeeper + " so reconnecting due to: " + e, ErrorSeverity.ERROR, ErrorTypes.SESSIONEXPIRED);
- throw e;
- } catch (KeeperException.ConnectionLossException e) {
- if (exception == null) {
- exception = e;
- }
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.CONNCECTIVITYERROR, ErrorSeverity.ERROR, ErrorTypes.SESSIONEXPIRED);
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Attempt " + i + " failed with connection loss so attempting to reconnect: " + e);
-
- retryDelay(i);
- }
- }
- throw exception;
- }
-
- /**
- * Ensures that the given path exists with no data, the current ACL and no flags
- *
- * @param path the lock path
- */
- protected void ensurePathExists(String path) {
- ensureExists(path, null, acl, CreateMode.PERSISTENT);
- }
-
- /**
- * Ensures that the given path exists with the given data, ACL and flags
- *
- * @param path the lock path
- * @param data the data
- * @param acl list of ACLs applying to the path
- * @param flags create mode flags
- */
- protected void ensureExists(final String path, final byte[] data, final List<ACL> acl,
- final CreateMode flags) {
- try {
- retryOperation(new ZooKeeperOperation() {
- public boolean execute() throws KeeperException, InterruptedException {
- Stat stat = zookeeper.exists(path, false);
- if (stat != null) {
- return true;
- }
- zookeeper.create(path, data, acl, flags);
- return true;
- }
- });
- } catch (KeeperException e) {
- logger.error("Error", e);
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- } catch (InterruptedException e) {
- logger.error("Error", e);
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }
- }
-
- /**
- * Returns true if this protocol has been closed
- *
- * @return true if this protocol is closed
- */
- protected boolean isClosed() {
- return closed.get();
- }
-
- /**
- * Performs a retry delay if this is not the first attempt
- *
- * @param attemptCount the number of the attempts performed so far
- */
- protected void retryDelay(int attemptCount) {
- if (attemptCount > 0) {
- try {
- Thread.sleep(attemptCount * retryDelay);
- } catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Thread failed to sleep: " + e);
- Thread.currentThread().interrupt();
- }
- }
- }
-}
diff --git a/src/main/java/org/onap/music/lockingservice/ZNodeName.java b/src/main/java/org/onap/music/lockingservice/ZNodeName.java
deleted file mode 100644
index 0c190f14..00000000
--- a/src/main/java/org/onap/music/lockingservice/ZNodeName.java
+++ /dev/null
@@ -1,118 +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.lockingservice;
-
-import org.onap.music.eelf.logging.EELFLoggerDelegate;
-import org.onap.music.eelf.logging.format.ErrorSeverity;
-import org.onap.music.eelf.logging.format.ErrorTypes;
-
-/**
- * Represents an ephemeral znode name which has an ordered sequence number and can be sorted in
- * order
- *
- */
-class ZNodeName implements Comparable<ZNodeName> {
- private final String name;
- private String prefix;
- private int sequence = -1;
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(ZNodeName.class);
-
- public ZNodeName(String name) {
- if (name == null) {
- throw new NullPointerException("id cannot be null");
- }
- this.name = name;
- this.prefix = name;
- int idx = name.lastIndexOf('-');
- if (idx >= 0) {
- this.prefix = name.substring(0, idx);
- try {
- this.sequence = Integer.parseInt(name.substring(idx + 1));
- // If an exception occurred we misdetected a sequence suffix,
- // so return -1.
- } catch (NumberFormatException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Number format exception "+idx, ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
- } catch (ArrayIndexOutOfBoundsException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Array out of bounds for "+idx, ErrorSeverity.ERROR, ErrorTypes.GENERALSERVICEERROR);
- }
- }
- }
-
- @Override
- public String toString() {
- return name.toString();
- }
-
- @Override
- public boolean equals(Object o) {
- if (this == o)
- return true;
- if (o == null || getClass() != o.getClass())
- return false;
-
- ZNodeName sequence = (ZNodeName) o;
-
- if (!name.equals(sequence.name))
- return false;
-
- return true;
- }
-
- @Override
- public int hashCode() {
- return name.hashCode() + 37;
- }
-
- public int compareTo(ZNodeName that) {
- int answer = this.prefix.compareTo(that.prefix);
- if (answer == 0) {
- int s1 = this.sequence;
- int s2 = that.sequence;
- if (s1 == -1 && s2 == -1) {
- return this.name.compareTo(that.name);
- }
- answer = s1 == -1 ? 1 : s2 == -1 ? -1 : s1 - s2;
- }
- return answer;
- }
-
- /**
- * Returns the name of the znode
- */
- public String getName() {
- return name;
- }
-
- /**
- * Returns the sequence number
- */
- public int getZNodeName() {
- return sequence;
- }
-
- /**
- * Returns the text prefix before the sequence number
- */
- public String getPrefix() {
- return prefix;
- }
-}
diff --git a/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java b/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java
deleted file mode 100644
index b09668b7..00000000
--- a/src/main/java/org/onap/music/lockingservice/ZkStatelessLockService.java
+++ /dev/null
@@ -1,363 +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.lockingservice;
-
-
-import java.util.List;
-import java.util.SortedSet;
-import java.util.TreeSet;
-import org.apache.zookeeper.CreateMode;
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.KeeperException.NoNodeException;
-import org.apache.zookeeper.ZooDefs;
-import org.apache.zookeeper.ZooKeeper;
-import org.apache.zookeeper.data.ACL;
-import org.apache.zookeeper.data.Stat;
-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.MusicCore;
-import org.onap.music.main.MusicUtil;
-
-import com.datastax.driver.core.DataType;
-
-/**
- * A <a href="package.html">protocol to implement an exclusive write lock or to elect a leader</a>.
- * <p/>
- * You invoke {@link #lock()} to start the process of grabbing the lock; you may get the lock then
- * or it may be some time later.
- * <p/>
- * You can register a listener so that you are invoked when you get the lock; otherwise you can ask
- * if you have the lock by calling {@link #isOwner()}
- *
- */
-public class ZkStatelessLockService extends ProtocolSupport {
- public ZkStatelessLockService(ZooKeeper zk) {
- zookeeper = zk;
- }
-
- private static EELFLoggerDelegate logger =
- EELFLoggerDelegate.getLogger(ZkStatelessLockService.class);
-
- protected void createLock(final String path, final byte[] data) {
- final List<ACL> acl = ZooDefs.Ids.OPEN_ACL_UNSAFE;
- try {
- retryOperation(new ZooKeeperOperation() {
- public boolean execute() throws KeeperException, InterruptedException {
- zookeeper.create(path, data, acl, CreateMode.PERSISTENT);
- return true;
- }
- });
- }catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }
- }
-
- public void close() {
- try {
- zookeeper.close();
- }catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }
- }
-
- public void setNodeData(final String lockName, final byte[] data) {
- try {
- retryOperation(new ZooKeeperOperation() {
- public boolean execute() throws KeeperException, InterruptedException {
- zookeeper.getSessionId();
- zookeeper.setData("/" + lockName, data, -1);
- return true;
- }
- });
- }catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }
-
- }
-
- public byte[] getNodeData(final String lockName) {
- try {
- if (zookeeper.exists("/" + lockName, null) != null)
- return zookeeper.getData("/" + lockName, false, null);
- else
- return null;
-
- }catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }
- return null;
- }
-
- public boolean checkIfLockExists(String lockName) {
- boolean result = false;
- try {
- Stat stat = zookeeper.exists(lockName, false);
- if (stat != null) {
- result = true;
- }
- }catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }
- return result;
- }
-
- public void createNode(String nodeName) {
- ensurePathExists(nodeName);
- }
-
- public String createLockId(String dir) {
- ensurePathExists(dir);
- LockZooKeeperOperation zop = new LockZooKeeperOperation(dir);
- try {
- retryOperation(zop);
- }catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- }
- return zop.getId();
- }
-
- /**
- * Attempts to acquire the exclusive write lock returning whether or not it was acquired. Note
- * that the exclusive lock may be acquired some time later after this method has been invoked
- * due to the current lock owner going away.
- */
- public synchronized boolean lock(String dir, String lockId)
- throws KeeperException, InterruptedException {
- if (isClosed()) {
- return false;
- }
- LockZooKeeperOperation zop = new LockZooKeeperOperation(dir, lockId);
- return (Boolean) retryOperation(zop);
- }
-
- /**
- * Removes the lock or associated znode if you no longer require the lock. this also removes
- * your request in the queue for locking in case you do not already hold the lock.
- *
- * @throws RuntimeException throws a runtime exception if it cannot connect to zookeeper.
- * @throws NoNodeException
- */
- public synchronized void unlock(String lockId) throws RuntimeException, KeeperException.NoNodeException {
- final String id = lockId;
- if (!isClosed() && id != null) {
- try {
- ZooKeeperOperation zopdel = new ZooKeeperOperation() {
- public boolean execute() throws KeeperException, InterruptedException {
- zookeeper.delete(id, -1);
- return Boolean.TRUE;
- }
- };
- zopdel.execute();
- } catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- // set that we have been interrupted.
- Thread.currentThread().interrupt();
- } catch (KeeperException.NoNodeException e) {
- // do nothing
- throw new KeeperException.NoNodeException("Lock doesn't exists. Release lock operation failed.");
- } catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- throw (RuntimeException) new RuntimeException(e.getMessage()).initCause(e);
- }
- }
- }
-
- public synchronized String currentLockHolder(String mainLock) {
- final String id = mainLock;
- if (!isClosed() && id != null) {
- List<String> names;
- try {
- names = zookeeper.getChildren(id, false);
- if (names.isEmpty())
- return "";
- SortedSet<ZNodeName> sortedNames = new TreeSet<ZNodeName>();
- for (String name : names) {
- sortedNames.add(new ZNodeName(id + "/" + name));
- }
- return sortedNames.first().getName();
- } catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- // set that we have been interrupted.
- Thread.currentThread().interrupt();
- } catch (KeeperException.NoNodeException e) {
- // do nothing
- } catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- throw (RuntimeException) new RuntimeException(e.getMessage()).initCause(e);
- }
- }
- return "No lock holder!";
- }
-
- public synchronized void deleteLock(String mainLock) {
- final String id = mainLock;
- if (!isClosed() && id != null) {
- try {
- ZooKeeperOperation zopdel = new ZooKeeperOperation() {
- public boolean execute() throws KeeperException, InterruptedException {
- List<String> names = zookeeper.getChildren(id, false);
- for (String name : names) {
- zookeeper.delete(id + "/" + name, -1);
- }
- zookeeper.delete(id, -1);
- return Boolean.TRUE;
- }
- };
- zopdel.execute();
- } catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.EXECUTIONINTERRUPTED, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- // set that we have been interrupted.
- Thread.currentThread().interrupt();
- } catch (KeeperException.NoNodeException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- // do nothing
- } catch (KeeperException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.KEEPERERROR, ErrorSeverity.ERROR, ErrorTypes.LOCKINGERROR);
- throw (RuntimeException) new RuntimeException(e.getMessage()).initCause(e);
- }
- }
-
- }
-
- /**
- * a zoookeeper operation that is mainly responsible for all the magic required for locking.
- */
- private class LockZooKeeperOperation implements ZooKeeperOperation {
-
- /**
- * find if we have been created earlier if not create our node
- *
- * @param prefix the prefix node
- * @param zookeeper the zookeeper client
- * @param dir the dir parent
- * @throws KeeperException
- * @throws InterruptedException
- */
- private String dir;
- private String id = null;
-
- public String getId() {
- return id;
- }
-
- public LockZooKeeperOperation(String dir) {
- this.dir = dir;
- }
-
- public LockZooKeeperOperation(String dir, String id) {
- this.dir = dir;
- this.id = id;
- }
-
- /**
- * the command that is run and retried for actually obtaining the lock
- *
- * @return if the command was successful or not
- */
- public boolean execute() throws KeeperException, InterruptedException {
- do {
- if (id == null) {
- String prefix = "x-";
- byte[] data = {0x12, 0x34};
- id = zookeeper.create(dir + "/" + prefix, data, getAcl(),
- CreateMode.PERSISTENT_SEQUENTIAL);
-
- if (logger.isDebugEnabled()) {
- logger.debug(EELFLoggerDelegate.debugLogger, "Created id: " + id);
- }
- if (id != null) {
- Stat stat = null;
- try {
- stat = zookeeper.exists(id, false);
- } catch (KeeperException | InterruptedException e1) {
- logger.error(EELFLoggerDelegate.errorLogger, "Error in execute: " + e1);
- }
- Long ctime = stat.getCtime();
- MusicUtil.zkNodeMap.put(id, ctime);
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "INSERT INTO admin.locks(lock_id, ctime) VALUES (?,?)");
- try {
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), id));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), ctime));
- MusicCore.eventualPut(pQuery);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, "Error in execute: " + e);
- }
- break;
- }
- }
- if (id != null) {
- List<String> names = zookeeper.getChildren(dir, false);
- if (names.isEmpty()) {
- logger.info(EELFLoggerDelegate.applicationLogger, "No children in: " + dir
- + " when we've just " + "created one! Lets recreate it...");
- // lets force the recreation of the id
- id = null;
- return Boolean.FALSE;
-
- } else {
- // lets sort them explicitly (though they do seem to come back in order
- // ususally :)
- ZNodeName idName = new ZNodeName(id);
- SortedSet<ZNodeName> sortedNames = new TreeSet<ZNodeName>();
- for (String name : names) {
- sortedNames.add(new ZNodeName(dir + "/" + name));
- }
- if (!sortedNames.contains(idName))
- return Boolean.FALSE;
-
- SortedSet<ZNodeName> lessThanMe = sortedNames.headSet(idName);
- if (!lessThanMe.isEmpty()) {
- ZNodeName lastChildName = lessThanMe.last();
- String lastChildId = lastChildName.getName();
- if (logger.isDebugEnabled()) {
- logger.debug(EELFLoggerDelegate.debugLogger, "watching less than me node: " + lastChildId);
- }
- Stat stat = zookeeper.exists(lastChildId, false);
- if (stat != null) {
- return Boolean.FALSE;
- } else {
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Could not find the" + " stats for less than me: "
- + lastChildName.getName());
- }
- } else
- return Boolean.TRUE;
- }
- }
- } while (id == null);
- return Boolean.FALSE;
- }
- }
-
-}
-
diff --git a/src/main/java/org/onap/music/lockingservice/ZooKeeperOperation.java b/src/main/java/org/onap/music/lockingservice/ZooKeeperOperation.java
deleted file mode 100644
index 7020d14d..00000000
--- a/src/main/java/org/onap/music/lockingservice/ZooKeeperOperation.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.lockingservice;
-
-import org.apache.zookeeper.KeeperException;
-
-/**
- * A callback object which can be used for implementing retry-able operations in the
- * {@link org.onap.music.lockingservice.ProtocolSupport} class
- *
- */
-public interface ZooKeeperOperation {
-
- /**
- * Performs the operation - which may be involved multiple times if the connection
- * to ZooKeeper closes during this operation
- *
- * @return the result of the operation or null
- * @throws KeeperException FILL IN
- * @throws InterruptedException FILL IN
- */
- public boolean execute() throws KeeperException, InterruptedException;
-}
diff --git a/src/main/java/org/onap/music/main/CachingUtil.java b/src/main/java/org/onap/music/main/CachingUtil.java
deleted file mode 100755
index a81887a0..00000000
--- a/src/main/java/org/onap/music/main/CachingUtil.java
+++ /dev/null
@@ -1,441 +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.Calendar;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import javax.ws.rs.core.MediaType;
-import org.apache.commons.codec.binary.Base64;
-import org.apache.commons.jcs.JCS;
-import org.apache.commons.jcs.access.CacheAccess;
-import org.mindrot.jbcrypt.BCrypt;
-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.MusicServiceException;
-import org.onap.music.datastore.jsonobjects.JsonCallback;
-import com.datastax.driver.core.DataType;
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.Row;
-import com.datastax.driver.core.exceptions.InvalidQueryException;
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.WebResource;
-
-/**
- * All Caching related logic is handled by this class and a schedule cron runs to update cache.
- *
- * @author Vikram
- *
- */
-public class CachingUtil implements Runnable {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CachingUtil.class);
-
- private static CacheAccess<String, String> musicCache = JCS.getInstance("musicCache");
- private static CacheAccess<String, Map<String, String>> aafCache = JCS.getInstance("aafCache");
- private static CacheAccess<String, String> appNameCache = JCS.getInstance("appNameCache");
- private static CacheAccess<String, Map<String, String>> musicValidateCache = JCS.getInstance("musicValidateCache");
- private static CacheAccess<String, JsonCallback> callBackCache = JCS.getInstance("callBackCache");
- private static CacheAccess<String, List<String>> callbackNotifyList = JCS.getInstance("callbackNotifyList");
- private static Map<String, Number> userAttempts = new HashMap<>();
- private static Map<String, Calendar> lastFailedTime = new HashMap<>();
-
- public boolean isCacheRefreshNeeded() {
- if (aafCache.get("initBlankMap") == null)
- return true;
- return false;
- }
-
- public static void updateCallBackCache(String appName, JsonCallback jsonCallBack) {
- logger.info("updateCallBackCache: updating cache.....");
- callBackCache.put(appName, jsonCallBack);
- }
-
- public static JsonCallback getCallBackCache(String appName) {
- return callBackCache.get(appName);
- }
-
- public static void updateCallbackNotifyList(List<String> notifyList) {
- logger.info("callbackNotifyList: updating cache.....");
- callbackNotifyList.put("callbackNotify", notifyList);
- }
-
- public static List<String> getCallbackNotifyList() {
- return callbackNotifyList.get("callbackNotify");
- }
-
- public void initializeMusicCache() {
- logger.info(EELFLoggerDelegate.applicationLogger,"Initializing Music Cache...");
- musicCache.put("isInitialized", "true");
- }
-
- public void initializeAafCache() throws MusicServiceException {
- logger.info(EELFLoggerDelegate.applicationLogger,"Resetting and initializing AAF Cache...");
-
- String query = "SELECT uuid, application_name, keyspace_name, username, password FROM admin.keyspace_master WHERE is_api = ? allow filtering";
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(query);
- try {
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), false));
- } catch (Exception e1) {
- logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),AppMessages.CACHEERROR, ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- }
- ResultSet rs = MusicCore.get(pQuery);
- Iterator<Row> it = rs.iterator();
- Map<String, String> map = null;
- while (it.hasNext()) {
- Row row = it.next();
- String nameSpace = row.getString("keyspace_name");
- String userId = row.getString("username");
- String password = row.getString("password");
- String keySpace = row.getString("application_name");
- try {
- userAttempts.put(nameSpace, 0);
- boolean responseObj = triggerAAF(nameSpace, userId, password);
- if (responseObj) {
- map = new HashMap<>();
- map.put(userId, password);
- aafCache.put(nameSpace, map);
- musicCache.put(keySpace, nameSpace);
- logger.debug("Cronjob: Cache Updated with AAF response for namespace "
- + nameSpace);
- }
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),"Something at AAF was changed for ns: " + nameSpace+" So not updating Cache for the namespace. ");
- }
- }
-
- }
-
- @Override
- public void run() {
- logger.info(EELFLoggerDelegate.applicationLogger,"Scheduled task invoked. Refreshing Cache...");
- try {
- initializeAafCache();
- } catch (MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),AppMessages.UNKNOWNERROR, ErrorSeverity.INFO, ErrorTypes.GENERALSERVICEERROR);
- }
- }
-
- public static boolean authenticateAAFUser(String nameSpace, String userId, String password,
- String keySpace) throws Exception {
-
- if (aafCache.get(nameSpace) != null && musicCache.get(keySpace)!=null) {
- if (keySpace != null && !musicCache.get(keySpace).equals(nameSpace)) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Create new application for the same namespace.");
- } else if (aafCache.get(nameSpace).get(userId).equals(password)) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Authenticated with cache value..");
- // reset invalid attempts to 0
- userAttempts.put(nameSpace, 0);
- return true;
- } else {
- // call AAF update cache with new password
- if (userAttempts.get(nameSpace) == null)
- userAttempts.put(nameSpace, 0);
- if ((Integer) userAttempts.get(nameSpace) >= 3) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Reached max attempts. Checking if time out..");
- logger.info(EELFLoggerDelegate.applicationLogger,"Failed time: "+lastFailedTime.get(nameSpace).getTime());
- Calendar calendar = Calendar.getInstance();
- long delayTime = (calendar.getTimeInMillis()-lastFailedTime.get(nameSpace).getTimeInMillis());
- logger.info(EELFLoggerDelegate.applicationLogger,"Delayed time: "+delayTime);
- if( delayTime > 120000) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Resetting failed attempt.");
- userAttempts.put(nameSpace, 0);
- } else {
- logger.info(EELFLoggerDelegate.applicationLogger,"No more attempts allowed. Please wait for atleast 2 min.");
- throw new Exception("No more attempts allowed. Please wait for atleast 2 min.");
- }
- }
- logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.CACHEAUTHENTICATION,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- logger.info(EELFLoggerDelegate.applicationLogger,"Check AAF again...");
- }
- }
-
- boolean responseObj = triggerAAF(nameSpace, userId, password);
- if (responseObj) {
- //if (responseObj.getNs().get(0).getAdmin().contains(userId)) {
- Map<String, String> map = new HashMap<>();
- map.put(userId, password);
- aafCache.put(nameSpace, map);
- CachingUtil.updateMusicCache(keySpace, nameSpace);
- return true;
- //}
- }
- logger.info(EELFLoggerDelegate.applicationLogger,"Invalid user. Cache not updated");
- return false;
- }
-
- private static boolean triggerAAF(String nameSpace, String userId, String password)
- throws Exception {
- if (MusicUtil.getAafEndpointUrl() == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"",AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- throw new Exception("AAF endpoint is not set. Please specify in the properties file.");
- }
- Client client = Client.create();
- // WebResource webResource =
- // client.resource("https://aaftest.test.att.com:8095/proxy/authz/nss/"+nameSpace);
- WebResource webResource = client.resource(MusicUtil.getAafEndpointUrl().concat(nameSpace));
- String plainCreds = userId + ":" + password;
- byte[] plainCredsBytes = plainCreds.getBytes();
- byte[] base64CredsBytes = Base64.encodeBase64(plainCredsBytes);
- String base64Creds = new String(base64CredsBytes);
-
- ClientResponse response = webResource.accept(MediaType.APPLICATION_JSON)
- .header("Authorization", "Basic " + base64Creds)
- .header("content-type", "application/json").get(ClientResponse.class);
- if (response.getStatus() != 200) {
- if (userAttempts.get(nameSpace) == null)
- userAttempts.put(nameSpace, 0);
- if ((Integer) userAttempts.get(nameSpace) >= 2) {
- lastFailedTime.put(nameSpace, Calendar.getInstance());
- userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
- throw new Exception(
- "Reached max invalid attempts. Please contact admin and retry with valid credentials.");
- }
- userAttempts.put(nameSpace, ((Integer) userAttempts.get(nameSpace) + 1));
- throw new Exception(
- "Unable to authenticate. Please check the AAF credentials against namespace.");
- // TODO Allow for 2-3 times and forbid any attempt to trigger AAF with invalid values
- // for specific time.
- }
- /*response.getHeaders().put(HttpHeaders.CONTENT_TYPE,
- Arrays.asList(MediaType.APPLICATION_JSON));
- // AAFResponse output = response.getEntity(AAFResponse.class);
- response.bufferEntity();
- String x = response.getEntity(String.class);
- AAFResponse responseObj = new ObjectMapper().readValue(x, AAFResponse.class);*/
-
- return true;
- }
-
- public static void updateMusicCache(String keyspace, String nameSpace) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for keyspace " + keyspace + " with nameSpace " + nameSpace);
- musicCache.put(keyspace, nameSpace);
- }
-
- public static void updateMusicValidateCache(String nameSpace, String userId, String password) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Updating musicCache for nameSpacce " + nameSpace + " with userId " + userId);
- Map<String, String> map = new HashMap<>();
- map.put(userId, password);
- musicValidateCache.put(nameSpace, map);
- }
-
- public static void updateisAAFCache(String namespace, String isAAF) {
- appNameCache.put(namespace, isAAF);
- }
-
- public static String isAAFApplication(String namespace) throws MusicServiceException {
- String isAAF = appNameCache.get(namespace);
- if (isAAF == null) {
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "SELECT is_aaf from admin.keyspace_master where application_name = '"
- + namespace + "' allow filtering");
- Row rs = null;
- try {
- rs = MusicCore.get(pQuery).one();
- } catch(InvalidQueryException e) {
- logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
- throw new MusicServiceException("Please make sure admin.keyspace_master table is configured.");
- }
- try {
- isAAF = String.valueOf(rs.getBool("is_aaf"));
- if(isAAF != null)
- appNameCache.put(namespace, isAAF);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR,ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- }
- }
- return isAAF;
- }
-
- public static String getUuidFromMusicCache(String keyspace) throws MusicServiceException {
- String uuid = null;
- if (uuid == null) {
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "SELECT uuid from admin.keyspace_master where keyspace_name = '"
- + keyspace + "' allow filtering");
- Row rs = MusicCore.get(pQuery).one();
- try {
- uuid = rs.getUUID("uuid").toString();
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,"Exception occured during uuid retrieval from DB."+e.getMessage());
- }
- }
- return uuid;
- }
-
- public static String getAppName(String keyspace) throws MusicServiceException {
- String appName = null;
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "SELECT application_name from admin.keyspace_master where keyspace_name = '"
- + keyspace + "' allow filtering");
- Row rs = MusicCore.get(pQuery).one();
- try {
- appName = rs.getString("application_name");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(), AppMessages.QUERYERROR, ErrorSeverity.ERROR, ErrorTypes.QUERYERROR);
- }
- return appName;
- }
-
- public static String generateUUID() {
- String uuid = UUID.randomUUID().toString();
- logger.info(EELFLoggerDelegate.applicationLogger,"New AID generated: "+uuid);
- return uuid;
- }
-
- public static Map<String, Object> validateRequest(String nameSpace, String userId,
- String password, String keyspace, String aid, String operation) {
- Map<String, Object> resultMap = new HashMap<>();
- if (!"createKeySpace".equals(operation)) {
- if (nameSpace == null) {
- resultMap.put("Exception", "Application namespace is mandatory.");
- }
- }
- return resultMap;
-
- }
-
- public static Map<String, Object> verifyOnboarding(String ns, String userId, String password) {
- Map<String, Object> resultMap = new HashMap<>();
- if (ns == null || userId == null || password == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: "+userId+" :: password: "+password);
- resultMap.put("Exception",
- "One or more required headers appName(ns), userId, password is missing. Please check.");
- return resultMap;
- }
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString(
- "select * from admin.keyspace_master where application_name = ? allow filtering");
- try {
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
- } catch(Exception e) {
- resultMap.put("Exception",
- "Unable to process input data. Invalid input data type. Please check ns, userId and password values. "+e.getMessage());
- return resultMap;
- }
- Row rs = null;
- try {
- rs = MusicCore.get(queryObject).one();
- } catch (MusicServiceException e) {
- // TODO Auto-generated catch block
- resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
- return resultMap;
- } catch (InvalidQueryException e) {
- logger.error(EELFLoggerDelegate.errorLogger,"Exception admin keyspace not configured."+e.getMessage());
- resultMap.put("Exception", "Please make sure admin.keyspace_master table is configured.");
- return resultMap;
- }
- if (rs == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"Application is not onboarded. Please contact admin.");
- resultMap.put("Exception", "Application is not onboarded. Please contact admin.");
- } else {
- if(!(rs.getString("username").equals(userId)) || !(BCrypt.checkpw(password, rs.getString("password")))) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- logger.error(EELFLoggerDelegate.errorLogger,"Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
- resultMap.put("Exception", "Namespace, UserId and password doesn't match. namespace: "+ns+" and userId: "+userId);
- return resultMap;
- }
- }
- return resultMap;
- }
-
- public static Map<String, Object> authenticateAIDUser(String nameSpace, String userId, String password,
- String keyspace) {
- Map<String, Object> resultMap = new HashMap<>();
- String pwd = null;
- if((musicCache.get(keyspace) != null) && (musicValidateCache.get(nameSpace) != null)
- && (musicValidateCache.get(nameSpace).containsKey(userId))) {
- if(!musicCache.get(keyspace).equals(nameSpace)) {
- resultMap.put("Exception", "Namespace and keyspace doesn't match");
- return resultMap;
- }
- if(!BCrypt.checkpw(password,musicValidateCache.get(nameSpace).get(userId))) {
- resultMap.put("Exception", "Namespace, userId and password doesn't match");
- return resultMap;
- }
- return resultMap;
- }
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString(
- "select * from admin.keyspace_master where keyspace_name = ? allow filtering");
- try {
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspace));
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- }
- Row rs = null;
- try {
- rs = MusicCore.get(queryObject).one();
- } catch (MusicServiceException e) {
- resultMap.put("Exception", "Unable to process operation. Error is "+e.getMessage());
- return resultMap;
- }
- if(rs == null) {
- resultMap.put("Exception", "Please make sure keyspace:"+keyspace+" exists.");
- return resultMap;
- }
- else {
- String user = rs.getString("username");
- pwd = rs.getString("password");
- String ns = rs.getString("application_name");
- if(!ns.equals(nameSpace)) {
- resultMap.put("Exception", "Namespace and keyspace doesn't match");
- return resultMap;
- }
- if(!user.equals(userId)) {
- resultMap.put("Exception", "Invalid userId :"+userId);
- return resultMap;
- }
- if(!BCrypt.checkpw(password, pwd)) {
- resultMap.put("Exception", "Invalid password");
- return resultMap;
- }
- }
- CachingUtil.updateMusicCache(keyspace, nameSpace);
- CachingUtil.updateMusicValidateCache(nameSpace, userId, pwd);
- return resultMap;
- }
-
- public static void deleteKeysFromDB(String deleteKeys) {
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "DELETE FROM admin.locks WHERE lock_id IN ("+deleteKeys+")");
- try {
- MusicCore.nonKeyRelatedPut(pQuery, "eventual");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR, "Error in deleteKeysFromDB");
- }
- }
-}
diff --git a/src/main/java/org/onap/music/main/CronJobManager.java b/src/main/java/org/onap/music/main/CronJobManager.java
deleted file mode 100644
index 4928044e..00000000
--- a/src/main/java/org/onap/music/main/CronJobManager.java
+++ /dev/null
@@ -1,112 +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.Iterator;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.TimeUnit;
-import javax.servlet.ServletContextEvent;
-import javax.servlet.ServletContextListener;
-import javax.servlet.annotation.WebListener;
-
-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.MusicServiceException;
-
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.Row;
-
-//@WebListener
-public class CronJobManager implements ServletContextListener {
-
- private ScheduledExecutorService scheduler;
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(CronJobManager.class);
-
- @Override
- public void contextInitialized(ServletContextEvent event) {
- scheduler = Executors.newSingleThreadScheduledExecutor();
- scheduler.scheduleAtFixedRate(new CachingUtil(), 0, 24, TimeUnit.HOURS);
- PreparedQueryObject pQuery = new PreparedQueryObject();
- String consistency = MusicUtil.EVENTUAL;
- pQuery.appendQueryString("CREATE TABLE IF NOT EXISTS admin.locks ( lock_id text PRIMARY KEY, ctime text)");
- try {
- ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
- } catch (MusicServiceException e1) {
- logger.error(EELFLoggerDelegate.errorLogger, e1.getMessage(),ErrorSeverity.ERROR);
- }
-
- //Zookeeper cleanup
- scheduler.scheduleAtFixedRate(new Runnable() {
- @Override
- public void run() {
- deleteLocksFromDB();
- }
- } , 0, 24, TimeUnit.HOURS);
- }
-
- @Override
- public void contextDestroyed(ServletContextEvent event) {
- scheduler.shutdownNow();
- }
-
- public void deleteLocksFromDB() {
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "select * from admin.locks");
- try {
- ResultSet rs = MusicCore.get(pQuery);
- Iterator<Row> it = rs.iterator();
- StringBuilder deleteKeys = new StringBuilder();
- Boolean expiredKeys = false;
- while (it.hasNext()) {
- Row row = (Row) it.next();
- String id = row.getString("lock_id");
- long ctime = Long.parseLong(row.getString("ctime"));
- if(System.currentTimeMillis() >= ctime + 24 * 60 * 60 * 1000) {
- expiredKeys = true;
- String new_id = id.substring(1);
- try {
- MusicCore.deleteLock(new_id);
- } catch (MusicLockingException e) {
- logger.info(EELFLoggerDelegate.applicationLogger,
- e.getMessage());
- }
- deleteKeys.append("'").append(id).append("'").append(",");
- }
- }
- if(expiredKeys) {
- deleteKeys.deleteCharAt(deleteKeys.length()-1);
- CachingUtil.deleteKeysFromDB(deleteKeys.toString());
- }
- } catch (MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage(),ErrorSeverity.ERROR);
- }
- }
-
-}
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 9f7b060b..00000000
--- a/src/main/java/org/onap/music/main/MusicCore.java
+++ /dev/null
@@ -1,1002 +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.io.StringWriter;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.StringTokenizer;
-
-import org.apache.zookeeper.KeeperException;
-import org.apache.zookeeper.KeeperException.NoNodeException;
-import org.onap.music.datastore.MusicDataStore;
-import org.onap.music.datastore.PreparedQueryObject;
-import org.onap.music.datastore.jsonobjects.JsonKeySpace;
-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.lockingservice.MusicLockState;
-import org.onap.music.lockingservice.MusicLockState.LockStatus;
-import org.onap.music.lockingservice.MusicLockingService;
-
-import com.datastax.driver.core.ColumnDefinitions;
-import com.datastax.driver.core.ColumnDefinitions.Definition;
-import com.datastax.driver.core.DataType;
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.Row;
-import com.datastax.driver.core.TableMetadata;
-
-/**
- * This class .....
- *
- *
- */
-public class MusicCore {
-
- public static MusicLockingService mLockHandle = null;
- public static MusicDataStore mDstoreHandle = null;
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicCore.class);
-
- public static class Condition {
- Map<String, Object> conditions;
- PreparedQueryObject selectQueryForTheRow;
-
- public Condition(Map<String, Object> conditions, PreparedQueryObject selectQueryForTheRow) {
- this.conditions = conditions;
- this.selectQueryForTheRow = selectQueryForTheRow;
- }
-
- public boolean testCondition() throws Exception {
- // first generate the row
- ResultSet results = quorumGet(selectQueryForTheRow);
- Row row = null;
- if(results != null) {
- row = results.one();
- }
- return getDSHandle().doesRowSatisfyCondition(row, conditions);
- }
- }
-
-
- public static MusicLockingService getLockingServiceHandle() throws MusicLockingException {
- logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring lock store handle");
- long start = System.currentTimeMillis();
-
- if (mLockHandle == null) {
- try {
- mLockHandle = new MusicLockingService();
- } 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;
- }
-
- /**
- *
- * @param remoteIp
- * @return
- */
- public static MusicDataStore getDSHandle(String remoteIp) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Acquiring data store handle");
- long start = System.currentTimeMillis();
- if (mDstoreHandle == null) {
- mDstoreHandle = new MusicDataStore(remoteIp);
- }
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire data store handle:" + (end - start) + " ms");
- return mDstoreHandle;
- }
-
- /**
- *
- * @return
- * @throws MusicServiceException
- */
- public static MusicDataStore getDSHandle() throws MusicServiceException {
- logger.info(EELFLoggerDelegate.applicationLogger,"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.applicationLogger,"Time taken to acquire data store handle:" + (end - start) + " ms");
- return mDstoreHandle;
- }
-
- public static String createLockReference(String lockName) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Creating lock reference for lock name:" + lockName);
- long start = System.currentTimeMillis();
- String lockId = null;
- try {
- lockId = getLockingServiceHandle().createLockId("/" + lockName);
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.CREATELOCK+lockName,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
-
- }
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to create lock reference:" + (end - start) + " ms");
- return lockId;
- }
-
- /**
- *
- * @param key
- * @return
- */
- public static boolean isTableOrKeySpaceLock(String key) {
- String[] splitString = key.split("\\.");
- if (splitString.length > 2)
- return false;
- else
- return true;
- }
-
- /**
- *
- * @param key
- * @return
- */
- public static MusicLockState getMusicLockState(String key) {
- long start = System.currentTimeMillis();
- try {
- String[] splitString = key.split("\\.");
- String keyspaceName = splitString[0];
- String tableName = splitString[1];
- String primaryKey = splitString[2];
- MusicLockState mls;
- String lockName = keyspaceName + "." + tableName + "." + primaryKey;
- mls = getLockingServiceHandle().getLockState(lockName);
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to get lock state:" + (end - start) + " ms");
- return mls;
- } catch (NullPointerException | MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.INVALIDLOCK,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
- return null;
- }
-
- public static ReturnType acquireLockWithLease(String key, String lockId, long leasePeriod) {
- try {
- long start = System.currentTimeMillis();
- /* check if the current lock has exceeded its lease and if yes, release that lock */
- MusicLockState mls = getMusicLockState(key);
- if (mls != null) {
- if (mls.getLockStatus().equals(LockStatus.LOCKED)) {
- logger.info(EELFLoggerDelegate.applicationLogger,"The current lock holder for " + key + " is " + mls.getLockHolder()
- + ". Checking if it has exceeded lease");
- long currentLockPeriod = System.currentTimeMillis() - mls.getLeaseStartTime();
- long currentLeasePeriod = mls.getLeasePeriod();
- if (currentLockPeriod > currentLeasePeriod) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Lock period " + currentLockPeriod
- + " has exceeded lease period " + currentLeasePeriod);
- boolean voluntaryRelease = false;
- String currentLockHolder = mls.getLockHolder();
- mls = releaseLock(currentLockHolder, voluntaryRelease);
- }
- }
- } else
- logger.error(EELFLoggerDelegate.errorLogger,key, AppMessages.INVALIDLOCK,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
-
- /*
- * call the traditional acquire lock now and if the result returned is true, set the
- * begin time-stamp and lease period
- */
- if (acquireLock(key, lockId).getResult() == ResultType.SUCCESS) {
- mls = getMusicLockState(key);// get latest state
- if ( mls == null ) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Music Lock State is null");
- return new ReturnType(ResultType.FAILURE, "Could not acquire lock, Lock State is null");
- }
- if (mls.getLeaseStartTime() == -1) {// set it again only if it is not set already
- mls.setLeaseStartTime(System.currentTimeMillis());
- mls.setLeasePeriod(leasePeriod);
- getLockingServiceHandle().setLockState(key, mls);
- }
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to acquire leased lock:" + (end - start) + " ms");
- return new ReturnType(ResultType.SUCCESS, "Accquired lock");
- } else {
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to fail to acquire leased lock:" + (end - start) + " ms");
- return new ReturnType(ResultType.FAILURE, "Could not acquire lock");
- }
- } catch (Exception e) {
- StringWriter sw = new StringWriter();
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR506E] Failed to aquire lock ",ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
-
- String exceptionAsString = sw.toString();
- return new ReturnType(ResultType.FAILURE,
- "Exception thrown in acquireLockWithLease:\n" + exceptionAsString);
- }
- }
-
- public static ReturnType acquireLock(String key, String lockId) throws MusicLockingException {
- /*
- * first check if I am on top. Since ids are not reusable there is no need to check
- * lockStatus If the status is unlocked, then the above call will automatically return
- * false.
- */
- Boolean result = false;
- try {
- result = getLockingServiceHandle().isMyTurn(lockId);
- } catch (MusicLockingException e2) {
- logger.error(EELFLoggerDelegate.errorLogger,AppMessages.INVALIDLOCK + lockId + " " + e2);
- throw new MusicLockingException();
- }
- if (!result) {
- logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Not your turn, someone else has the lock");
- try {
- if (!getLockingServiceHandle().lockIdExists(lockId)) {
- logger.info(EELFLoggerDelegate.applicationLogger, "In acquire lock: this lockId doesn't exist");
- return new ReturnType(ResultType.FAILURE, "Lockid doesn't exist");
- }
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.INVALIDLOCK+lockId,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- throw new MusicLockingException();
- }
- logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: returning failure");
- return new ReturnType(ResultType.FAILURE, "Not your turn, someone else has the lock");
- }
-
-
- // this is for backward compatibility where locks could also be acquired on just
- // keyspaces or tables.
- if (isTableOrKeySpaceLock(key)) {
- logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: A table or keyspace lock so no need to perform sync...so returning true");
- return new ReturnType(ResultType.SUCCESS, "A table or keyspace lock so no need to perform sync...so returning true");
- }
-
- // read the lock name corresponding to the key and if the status is locked or being locked,
- // then return false
- MusicLockState currentMls = null;
- MusicLockState newMls = null;
- try {
- currentMls = getMusicLockState(key);
- String currentLockHolder = null;
- if(currentMls != null) { currentLockHolder = currentMls.getLockHolder(); };
- if (lockId.equals(currentLockHolder)) {
- logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: You already have the lock!");
- return new ReturnType(ResultType.SUCCESS, "You already have the lock!");
- }
- } catch (NullPointerException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.INVALIDLOCK+lockId,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
-
- // change status to "being locked". This state transition is necessary to ensure syncing
- // before granting the lock
- String lockHolder = null;
- boolean needToSyncQuorum = false;
- if (currentMls != null)
- needToSyncQuorum = currentMls.isNeedToSyncQuorum();
-
-
- newMls = new MusicLockState(MusicLockState.LockStatus.BEING_LOCKED, lockHolder,
- needToSyncQuorum);
- try {
- getLockingServiceHandle().setLockState(key, newMls);
- } catch (MusicLockingException e1) {
- logger.error(EELFLoggerDelegate.errorLogger,e1.getMessage(), AppMessages.LOCKSTATE+key,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
- logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Set lock state to being_locked");
-
- // do syncing if this was a forced lock release
- if (needToSyncQuorum) {
- logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Since there was a forcible release, need to sync quorum!");
- try {
- syncQuorum(key);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,"Failed to set Lock state " + e);
- }
- }
-
- // change status to locked
- lockHolder = lockId;
- needToSyncQuorum = false;
- newMls = new MusicLockState(MusicLockState.LockStatus.LOCKED, lockHolder, needToSyncQuorum);
- try {
- getLockingServiceHandle().setLockState(key, newMls);
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKSTATE+key,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
- logger.info(EELFLoggerDelegate.applicationLogger,"In acquire lock: Set lock state to locked and assigned current lock ref "
- + lockId + " as holder");
-
- return new ReturnType(result?ResultType.SUCCESS:ResultType.FAILURE, "Set lock state to locked and assigned a lock holder");
- }
-
-
-
- /**
- *
- * @param keyspaceName
- * @param kspObject
- * @return
- * @throws Exception
- */
- public boolean createKeyspace(String keyspaceName, JsonKeySpace kspObject) throws Exception {
- return true;
- }
-
-
- private static void syncQuorum(String key) throws Exception {
- logger.info(EELFLoggerDelegate.applicationLogger,"Performing sync operation---");
- String[] splitString = key.split("\\.");
- String keyspaceName = splitString[0];
- String tableName = splitString[1];
- String primaryKeyValue = splitString[2];
- PreparedQueryObject selectQuery = new PreparedQueryObject();
- PreparedQueryObject updateQuery = new PreparedQueryObject();
-
- // get the primary key d
- TableMetadata tableInfo = returnColumnMetadata(keyspaceName, tableName);
- 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 " + keyspaceName + "." + tableName + " WHERE "
- + primaryKeyName + "= ?" + ";");
- selectQuery.addValue(cqlFormattedPrimaryKeyValue);
- ResultSet results = null;
- try {
- results = getDSHandle().executeCriticalGet(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 = 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 " + keyspaceName + "." + tableName + " SET "
- + fieldValueString + " WHERE " + primaryKeyName + "= ? " + ";");
- updateQuery.addValue(cqlFormattedPrimaryKeyValue);
-
- getDSHandle().executePut(updateQuery, "critical");
- } catch (MusicServiceException | MusicQueryException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.QUERYERROR +""+updateQuery ,ErrorSeverity.MAJOR, ErrorTypes.QUERYERROR);
- }
- }
-
-
-
-
- /**
- *
- * @param query
- * @return ResultSet
- */
- public static ResultSet quorumGet(PreparedQueryObject query) {
- ResultSet results = null;
- try {
- results = getDSHandle().executeCriticalGet(query);
- } catch (MusicServiceException | MusicQueryException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.MAJOR, ErrorTypes.GENERALSERVICEERROR);
-
- }
- return results;
-
- }
-
- /**
- *
- * @param results
- * @return
- * @throws MusicServiceException
- */
- public static Map<String, HashMap<String, Object>> marshallResults(ResultSet results) throws MusicServiceException {
- return getDSHandle().marshalData(results);
- }
-
- /**
- *
- * @param lockName
- * @return
- */
- public static String whoseTurnIsIt(String lockName) {
-
- try {
- return getLockingServiceHandle().whoseTurnIsIt("/" + lockName) + "";
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKINGERROR+lockName ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
- return null;
-
-
- }
-
- /**
- *
- * @param lockId
- * @return
- */
- public static String getLockNameFromId(String lockId) {
- StringTokenizer st = new StringTokenizer(lockId);
- return st.nextToken("$");
- }
-
- public static void destroyLockRef(String lockId) {
- long start = System.currentTimeMillis();
- try {
- getLockingServiceHandle().unlockAndDeleteId(lockId);
- } catch (MusicLockingException | NoNodeException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DESTROYLOCK+lockId ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to destroy lock reference:" + (end - start) + " ms");
- }
-
- public static MusicLockState releaseLock(String lockId, boolean voluntaryRelease) {
- long start = System.currentTimeMillis();
- try {
- getLockingServiceHandle().unlockAndDeleteId(lockId);
- } catch (MusicLockingException e1) {
- logger.error(EELFLoggerDelegate.errorLogger,e1.getMessage(), AppMessages.RELEASELOCK+lockId ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- } catch (KeeperException.NoNodeException nne) {
- logger.error(EELFLoggerDelegate.errorLogger,"Failed to release Lock " + lockId + " " + nne);
- MusicLockState mls = new MusicLockState("Lock doesn't exists. Release lock operation failed.");
- return mls;
- }
- String lockName = getLockNameFromId(lockId);
- MusicLockState mls;
- String lockHolder = null;
- if (voluntaryRelease) {
- mls = new MusicLockState(MusicLockState.LockStatus.UNLOCKED, lockHolder);
- logger.info(EELFLoggerDelegate.applicationLogger,"In unlock: lock voluntarily released for " + lockId);
- } else {
- boolean needToSyncQuorum = true;
- mls = new MusicLockState(MusicLockState.LockStatus.UNLOCKED, lockHolder,
- needToSyncQuorum);
- logger.info(EELFLoggerDelegate.applicationLogger,"In unlock: lock forcibly released for " + lockId);
- }
- try {
- getLockingServiceHandle().setLockState(lockName, mls);
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.RELEASELOCK+lockId ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to release lock:" + (end - start) + " ms");
- return mls;
- }
-
- public static void voluntaryReleaseLock(String lockId) throws MusicLockingException{
- try {
- getLockingServiceHandle().unlockAndDeleteId(lockId);
- } catch (KeeperException.NoNodeException e) {
- // ??? No way
- }
- }
-
- /**
- *
- * @param lockName
- * @throws MusicLockingException
- */
- public static void deleteLock(String lockName) throws MusicLockingException {
- long start = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Deleting lock for " + lockName);
- try {
- getLockingServiceHandle().deleteLock("/" + lockName);
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.DELTELOCK+lockName ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- throw new MusicLockingException(e.getMessage());
- }
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken to delete lock:" + (end - start) + " ms");
- }
-
-
-
- /**
- *
- * @param keyspace
- * @param tablename
- * @return
- * @throws MusicServiceException
- */
- public static TableMetadata returnColumnMetadata(String keyspace, String tablename) throws MusicServiceException {
- return getDSHandle().returnColumnMetadata(keyspace, tablename);
- }
-
-
- /**
- *
- * @param nodeName
- */
- public static void pureZkCreate(String nodeName) {
- try {
- getLockingServiceHandle().getzkLockHandle().createNode(nodeName);
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
- }
-
- /**
- *
- * @param nodeName
- * @param data
- */
- public static void pureZkWrite(String nodeName, byte[] data) {
- long start = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Performing zookeeper write to " + nodeName);
- try {
- getLockingServiceHandle().getzkLockHandle().setNodeData(nodeName, data);
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
- logger.info(EELFLoggerDelegate.applicationLogger,"Performed zookeeper write to " + nodeName);
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the actual zk put:" + (end - start) + " ms");
- }
-
- /**
- *
- * @param nodeName
- * @return
- */
- public static byte[] pureZkRead(String nodeName) {
- long start = System.currentTimeMillis();
- byte[] data = null;
- try {
- data = getLockingServiceHandle().getzkLockHandle().getNodeData(nodeName);
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the actual zk put:" + (end - start) + " ms");
- return data;
- }
-
-
-
- // Prepared Query Additions.
-
- /**
- *
- * @param keyspaceName
- * @param tableName
- * @param primaryKey
- * @param queryObject
- * @return ReturnType
- * @throws MusicServiceException
- */
- public static ReturnType eventualPut(PreparedQueryObject queryObject) {
- boolean result = false;
- try {
- result = getDSHandle().executePut(queryObject, MusicUtil.EVENTUAL);
- } catch (MusicServiceException | MusicQueryException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), "[ERR512E] Failed to get ZK 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, "Success");
- } else {
- return new ReturnType(ResultType.FAILURE, "Failure");
- }
- }
-
- /**
- *
- * @param keyspaceName
- * @param tableName
- * @param primaryKey
- * @param queryObject
- * @param lockId
- * @return
- */
- public static ReturnType criticalPut(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject, String lockId, Condition conditionInfo) {
- long start = System.currentTimeMillis();
-
- try {
- MusicLockState mls = getLockingServiceHandle()
- .getLockState(keyspaceName + "." + tableName + "." + primaryKey);
- if (mls.getLockHolder().equals(lockId) == true) {
- if (conditionInfo != null)
- try {
- if (conditionInfo.testCondition() == false)
- return new ReturnType(ResultType.FAILURE,
- "Lock acquired but the condition is not true");
- } catch (Exception e) {
- return new ReturnType(ResultType.FAILURE,
- "Exception thrown while doing the critical put, check sanctity of the row/conditions:\n"
- + e.getMessage());
- }
- getDSHandle().executePut(queryObject, MusicUtil.CRITICAL);
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the critical put:" + (end - start) + " ms");
- return new ReturnType(ResultType.SUCCESS, "Update performed");
- } else
- return new ReturnType(ResultType.FAILURE,
- "Cannot perform operation since you are the not the lock holder");
- } catch (MusicQueryException | MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
- return new ReturnType(ResultType.FAILURE,
- "Exception thrown while doing the critical put, check sanctity of the row/conditions:\n"
- + e.getMessage());
- }catch(MusicLockingException ex){
- return new ReturnType(ResultType.FAILURE,ex.getMessage());
- }
-
- }
-
- /**
- *
- * @param queryObject
- * @param consistency
- * @return Boolean Indicates success or failure
- * @throws MusicServiceException
- *
- *
- */
- public static ResultType nonKeyRelatedPut(PreparedQueryObject queryObject, String consistency) throws MusicServiceException {
- // 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 = getDSHandle().executePut(queryObject, consistency);
- } catch (MusicQueryException | MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- throw new MusicServiceException(ex.getMessage());
- }
- 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 static ResultSet get(PreparedQueryObject queryObject) throws MusicServiceException {
- ResultSet results = null;
- try {
- results = getDSHandle().executeEventualGet(queryObject);
- } catch (MusicQueryException | MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
- throw new MusicServiceException(e.getMessage());
- }
- return results;
- }
-
- public static String getMyHostId() {
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString("SELECT HOST_ID FROM SYSTEM.LOCAL");
- ResultSet rs = null;
- try {
- rs = getDSHandle().executeEventualGet(pQuery);
- Row row = rs.one();
- return (row == null) ? "UNKNOWN" : row.getUUID("HOST_ID").toString();
- } catch (Exception e) {
- e.printStackTrace();
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
- }
- logger.error(EELFLoggerDelegate.errorLogger, "Some issue during MusicCore.getMyHostId");
- return "UNKNOW";
- }
-
- /**
- * 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 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
- * @param lockId lock ID to check if the resource is free to perform the operation.
- * @return ResultSet
- */
- public static ResultSet criticalGet(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject, String lockId) throws MusicServiceException {
- ResultSet results = null;
- try {
- MusicLockState mls = getLockingServiceHandle()
- .getLockState(keyspaceName + "." + tableName + "." + primaryKey);
- if (mls.getLockHolder().equals(lockId)) {
- results = getDSHandle().executeCriticalGet(queryObject);
- } else
- throw new MusicServiceException("YOU DO NOT HAVE THE LOCK");
- } catch (MusicQueryException | MusicServiceException | MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- }
- 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
- */
- public static ReturnType atomicPut(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException {
-
- long start = System.currentTimeMillis();
- String key = keyspaceName + "." + tableName + "." + primaryKey;
- String lockId = createLockReference(key);
- long lockCreationTime = System.currentTimeMillis();
- ReturnType lockAcqResult = acquireLock(key, lockId);
- long lockAcqTime = System.currentTimeMillis();
- if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
- logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId);
- ReturnType criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey,
- queryObject, lockId, conditionInfo);
- long criticalPutTime = System.currentTimeMillis();
- voluntaryReleaseLock(lockId);
- 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);
- return criticalPutResult;
- } else {
- logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId);
- destroyLockRef(lockId);
- return lockAcqResult;
- }
- }
-
- /**
- * this function is mainly for the benchmarks to see the effect of lock deletion.
- *
- * @param keyspaceName
- * @param tableName
- * @param primaryKey
- * @param queryObject
- * @param conditionInfo
- * @return
- * @throws MusicLockingException
- */
- public static ReturnType atomicPutWithDeleteLock(String keyspaceName, String tableName,
- String primaryKey, PreparedQueryObject queryObject, Condition conditionInfo) throws MusicLockingException {
-
- long start = System.currentTimeMillis();
- String key = keyspaceName + "." + tableName + "." + primaryKey;
- String lockId = createLockReference(key);
- long lockCreationTime = System.currentTimeMillis();
- long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
- ReturnType lockAcqResult = acquireLock(key, lockId);
- long lockAcqTime = System.currentTimeMillis();
- if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
- logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId);
- ReturnType criticalPutResult = criticalPut(keyspaceName, tableName, primaryKey,
- queryObject, lockId, conditionInfo);
- long criticalPutTime = System.currentTimeMillis();
- deleteLock(key);
- 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);
- return criticalPutResult;
- } else {
- logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId);
- deleteLock(key);
- return lockAcqResult;
- }
- }
-
-
-
-
- /**
- * 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
- */
- public static ResultSet atomicGet(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException {
- String key = keyspaceName + "." + tableName + "." + primaryKey;
- String lockId = createLockReference(key);
- long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
- ReturnType lockAcqResult = acquireLock(key, lockId);
- if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
- logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId);
- ResultSet result =
- criticalGet(keyspaceName, tableName, primaryKey, queryObject, lockId);
- voluntaryReleaseLock(lockId);
- return result;
- } else {
- destroyLockRef(lockId);
- logger.info(EELFLoggerDelegate.applicationLogger,"unable to acquire lock, id " + lockId);
- return null;
- }
- }
-
- public static ResultSet atomicGetWithDeleteLock(String keyspaceName, String tableName, String primaryKey,
- PreparedQueryObject queryObject) throws MusicServiceException, MusicLockingException {
- String key = keyspaceName + "." + tableName + "." + primaryKey;
- String lockId = createLockReference(key);
- long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
-
- ReturnType lockAcqResult = acquireLock(key, lockId);
-
- if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
- logger.info(EELFLoggerDelegate.applicationLogger, "acquired lock with id " + lockId);
- ResultSet result = criticalGet(keyspaceName, tableName, primaryKey, queryObject, lockId);
- deleteLock(key);
- return result;
- } else {
- deleteLock(key);
- logger.info(EELFLoggerDelegate.applicationLogger, "unable to acquire lock, id " + lockId);
- return null;
- }
- }
-
-
-
- /**
- * authenticate user logic
- *
- * @param nameSpace
- * @param userId
- * @param password
- * @param keyspace
- * @param aid
- * @param operation
- * @return
- * @throws Exception
- */
- public static Map<String, Object> autheticateUser(String nameSpace, String userId,
- String password, String keyspace, String aid, String operation)
- throws Exception {
- Map<String, Object> resultMap = new HashMap<>();
- String uuid = null;
- resultMap = CachingUtil.validateRequest(nameSpace, userId, password, keyspace, aid,
- operation);
- if (!resultMap.isEmpty())
- return resultMap;
- String isAAFApp = null;
- try {
- isAAFApp= CachingUtil.isAAFApplication(nameSpace);
- } catch(MusicServiceException e) {
- resultMap.put("Exception", e.getMessage());
- return resultMap;
- }
- if(isAAFApp == null) {
- resultMap.put("Exception", "Namespace: "+nameSpace+" doesn't exist. Please make sure ns(appName)"
- + " is correct and Application is onboarded.");
- return resultMap;
- }
- boolean isAAF = Boolean.valueOf(isAAFApp);
- if (userId == null || password == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- logger.error(EELFLoggerDelegate.errorLogger,"One or more required headers is missing. userId: " + userId
- + " :: password: " + password);
- resultMap.put("Exception",
- "UserId and Password are mandatory for the operation " + operation);
- return resultMap;
- }
- if(!isAAF && !(operation.equals("createKeySpace"))) {
- resultMap = CachingUtil.authenticateAIDUser(nameSpace, userId, password, keyspace);
- if (!resultMap.isEmpty())
- return resultMap;
-
- }
- if (isAAF && nameSpace != null && userId != null && password != null) {
- boolean isValid = true;
- try {
- isValid = CachingUtil.authenticateAAFUser(nameSpace, userId, password, keyspace);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- logger.error(EELFLoggerDelegate.errorLogger,"Got exception while AAF authentication for namespace " + nameSpace);
- resultMap.put("Exception", e.getMessage());
- }
- if (!isValid) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- resultMap.put("Exception", "User not authenticated...");
- }
- if (!resultMap.isEmpty())
- return resultMap;
-
- }
-
- if (operation.equals("createKeySpace")) {
- logger.info(EELFLoggerDelegate.applicationLogger,"AID is not provided. Creating new UUID for keyspace.");
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "select uuid from admin.keyspace_master where application_name=? and username=? and keyspace_name=? allow filtering");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), nameSpace));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),
- MusicUtil.DEFAULTKEYSPACENAME));
-
- try {
- Row rs = MusicCore.get(pQuery).one();
- uuid = rs.getUUID("uuid").toString();
- resultMap.put("uuid", "existing");
- } catch (Exception e) {
- logger.info(EELFLoggerDelegate.applicationLogger,"No UUID found in DB. So creating new UUID.");
- uuid = CachingUtil.generateUUID();
- resultMap.put("uuid", "new");
- }
- resultMap.put("aid", uuid);
- }
-
- return resultMap;
- }
-
- /**
- * @param lockName
- * @return
- */
- public static Map<String, Object> validateLock(String lockName) {
- Map<String, Object> resultMap = new HashMap<>();
- String[] locks = lockName.split("\\.");
- if(locks.length < 3) {
- resultMap.put("Exception", "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;
- }
-}
diff --git a/src/main/java/org/onap/music/main/MusicDigest.java b/src/main/java/org/onap/music/main/MusicDigest.java
deleted file mode 100644
index 893cb51f..00000000
--- a/src/main/java/org/onap/music/main/MusicDigest.java
+++ /dev/null
@@ -1,78 +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 class MusicDigest {
- private String evPutStatus;
- private String vectorTs;
-
- /**
- * @param evPutStatus
- * @param vectorTs
- */
- public MusicDigest(String evPutStatus, String vectorTs) {
- this.evPutStatus = evPutStatus;
- this.vectorTs = vectorTs;
- }
-
- /**
- * @return
- */
- public String getEvPutStatus() {
- return evPutStatus;
- }
-
- /**
- * @param evPutStatus
- */
- public void setEvPutStatus(String evPutStatus) {
- this.evPutStatus = evPutStatus;
- }
-
- /**
- * @return
- */
- public String getVectorTs() {
- return vectorTs;
- }
-
- /**
- * @param vectorTs
- */
- public void setVectorTs(String vectorTs) {
- this.vectorTs = vectorTs;
- }
-
- /*
- * (non-Javadoc)
- *
- * @see java.lang.Object#toString()
- */
- public String toString() {
- return vectorTs + "|" + evPutStatus;
- }
-}
-
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 cfad845d..00000000
--- a/src/main/java/org/onap/music/main/MusicUtil.java
+++ /dev/null
@@ -1,633 +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.io.File;
-import java.io.FileNotFoundException;
-import java.io.IOException;
-import java.io.InputStream;
-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.Properties;
-import java.util.Scanner;
-import java.util.StringTokenizer;
-import java.util.UUID;
-import java.util.concurrent.ConcurrentHashMap;
-import java.util.concurrent.ConcurrentMap;
-
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-
-import org.onap.music.datastore.PreparedQueryObject;
-import org.onap.music.eelf.logging.EELFLoggerDelegate;
-
-import com.datastax.driver.core.DataType;
-import com.sun.jersey.core.util.Base64;
-
-/**
- * @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);
-
- public static final String ATOMIC = "atomic";
- public static final String EVENTUAL = "eventual";
- public static final String CRITICAL = "critical";
- public static final String ATOMICDELETELOCK = "atomic_delete_lock";
- public static final String DEFAULTKEYSPACENAME = "TBD";
- 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 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 = "password";
-
- public static final String AUTHORIZATION = "Authorization";
-
- private static final String LOCALHOST = "localhost";
- private static final String PROPERTIES_FILE = "/opt/app/music/etc/music.properties";
-
- private static int myId = 0;
- private static ArrayList<String> allIds = new ArrayList<>();
- private static String publicIp = "";
- private static ArrayList<String> allPublicIps = new ArrayList<>();
- private static String myZkHost = LOCALHOST;
- private static String myCassaHost = LOCALHOST;
- private static String defaultMusicIp = LOCALHOST;
- private static int cassandraPort = 9042;
- private static int notifytimeout = 30000;
- private static int notifyinterval = 5000;
-
- private static boolean debug = true;
- private static String version = "2.3.0";
- private static String musicRestIp = LOCALHOST;
- private static String musicPropertiesFilePath = PROPERTIES_FILE;
- private static long defaultLockLeasePeriod = 6000;
- private static final String[] propKeys = new String[] { "zookeeper.host", "cassandra.host", "music.ip", "debug",
- "version", "music.rest.ip", "music.properties", "lock.lease.period", "id", "all.ids", "public.ip",
- "all.pubic.ips", "cassandra.user", "cassandra.password", "aaf.endpoint.url","cassandra.port", "notify.timeout", "notify.interval" };
-
- private static String cassName = "cassandra";
- private static String cassPwd;
- private static String aafEndpointUrl = null;
- public static final ConcurrentMap<String, Long> zkNodeMap = new ConcurrentHashMap<>();
-
- private MusicUtil() {
- throw new IllegalStateException("Utility Class");
- }
- /**
- *
- * @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;
- }
-
- /**
- * @return the aafEndpointUrl
- */
- public static String getAafEndpointUrl() {
- return aafEndpointUrl;
- }
-
- /**
- *
- * @param aafEndpointUrl
- */
- public static void setAafEndpointUrl(String aafEndpointUrl) {
- MusicUtil.aafEndpointUrl = aafEndpointUrl;
- }
-
- /**
- *
- * @return
- */
- public static int getMyId() {
- return myId;
- }
-
- /**
- *
- * @param myId
- */
- public static void setMyId(int myId) {
- MusicUtil.myId = myId;
- }
-
- /**
- *
- * @return
- */
- public static List<String> getAllIds() {
- return allIds;
- }
-
- /**
- *
- * @param allIds
- */
- public static void setAllIds(List<String> allIds) {
- MusicUtil.allIds = (ArrayList<String>) allIds;
- }
-
- /**
- *
- * @return
- */
- public static String getPublicIp() {
- return publicIp;
- }
-
- /**
- *
- * @param publicIp
- */
- public static void setPublicIp(String publicIp) {
- MusicUtil.publicIp = publicIp;
- }
-
- /**
- *
- * @return
- */
- public static List<String> getAllPublicIps() {
- return allPublicIps;
- }
-
- /**
- *
- * @param allPublicIps
- */
- public static void setAllPublicIps(List<String> allPublicIps) {
- MusicUtil.allPublicIps = (ArrayList<String>) allPublicIps;
- }
-
- /**
- * Returns An array of property names that should be in the Properties
- * files.
- *
- * @return
- */
- public static String[] getPropkeys() {
- return propKeys;
- }
-
- /**
- * Get MusicRestIp - default = localhost property file value - music.rest.ip
- *
- * @return
- */
- public static String getMusicRestIp() {
- return musicRestIp;
- }
-
- /**
- * Set MusicRestIp
- *
- * @param musicRestIp
- */
- public static void setMusicRestIp(String musicRestIp) {
- MusicUtil.musicRestIp = musicRestIp;
- }
-
- /**
- * 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;
- }
-
- /**
- * Get MyZkHost - Zookeeper Hostname - Default = localhost property file
- * value - zookeeper.host
- *
- * @return
- */
- public static String getMyZkHost() {
- return myZkHost;
- }
-
- /**
- * Set MyZkHost - Zookeeper Hostname
- *
- * @param myZkHost
- */
- public static void setMyZkHost(String myZkHost) {
- MusicUtil.myZkHost = myZkHost;
- }
-
- /**
- * 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;
- }
-
- /**
- * Get DefaultMusicIp - Default = localhost property file value - music.ip
- *
- * @return
- */
- public static String getDefaultMusicIp() {
- return defaultMusicIp;
- }
-
- /**
- * Set DefaultMusicIp
- *
- * @param defaultMusicIp
- */
- public static void setDefaultMusicIp(String defaultMusicIp) {
- MusicUtil.defaultMusicIp = defaultMusicIp;
- }
-
- /**
- *
- * @return
- */
- 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());
- }
- return testType;
-
- }
-
- /**
- *
- * @param time
- */
- public static void sleep(long time) {
- try {
- Thread.sleep(time);
- } catch (InterruptedException e) {
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
- 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<String, Object> otMap = (Map<String, Object>) 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<String, Object>) 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<String, Object> jMap, String lineDelimiter) throws Exception{
- StringBuilder sqlString = new StringBuilder();
- int counter = 0;
- for (Map.Entry<String, Object> 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.applicationLogger,"Version In:" + versionIn);
- return response;
- }
-
-
- public static Map<String,String> extractBasicAuthentication(String authorization){
-
- Map<String,String> authValues = new HashMap<>();
- authorization = authorization.replaceFirst("Basic", "");
- String decoded = Base64.base64Decode(authorization);
- StringTokenizer token = new StringTokenizer(decoded, ":");
- authValues.put(MusicUtil.USERID, token.nextToken().toString());
- authValues.put(MusicUtil.PASSWORD,token.nextToken());
- return authValues;
-
- }
-
- public static void loadProperties() throws Exception {
- Properties prop = new Properties();
- InputStream input = null;
- try {
- // load the properties file
- input = MusicUtil.class.getClassLoader().getResourceAsStream("music.properties");
- prop.load(input);
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "Unable to find properties file.");
- throw new Exception();
- } finally {
- if (input != null) {
- try {
- input.close();
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.applicationLogger,"Load properties failed "+e.getMessage(),e);
- }
- }
- }
- // get the property value and return it
- MusicUtil.setMyCassaHost(prop.getProperty("cassandra.host"));
- String zkHosts = prop.getProperty("zookeeper.host");
- MusicUtil.setMyZkHost(zkHosts);
- MusicUtil.setCassName(prop.getProperty("cassandra.user"));
- MusicUtil.setCassPwd(prop.getProperty("cassandra.password"));
- MusicUtil.setCassandraPort(Integer.parseInt(prop.getProperty("cassandra.port")));
- MusicUtil.setNotifyTimeOut(Integer.parseInt(prop.getProperty("notify.timeout")));
- MusicUtil.setNotifyInterval(Integer.parseInt(prop.getProperty("notify.interval")));
-
- }
-
- public static void setNotifyInterval(int notifyinterval) {
- MusicUtil.notifyinterval = notifyinterval;
- }
- public static void setNotifyTimeOut(int notifytimeout) {
- MusicUtil.notifytimeout = notifytimeout;
- }
-
- public static int getNotifyInterval() {
- return MusicUtil.notifyinterval;
- }
-
- public static int getNotifyTimeout() {
- return MusicUtil.notifytimeout;
-
- }
-}
diff --git a/src/main/java/org/onap/music/main/PropertiesListener.java b/src/main/java/org/onap/music/main/PropertiesListener.java
deleted file mode 100755
index 0ed18be2..00000000
--- a/src/main/java/org/onap/music/main/PropertiesListener.java
+++ /dev/null
@@ -1,156 +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.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.net.URL;
-import java.util.ArrayList;
-import java.util.Arrays;
-import java.util.Properties;
-import javax.servlet.ServletContextEvent;
-import javax.servlet.ServletContextListener;
-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;
-
-public class PropertiesListener implements ServletContextListener {
- private Properties prop;
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(PropertiesListener.class);
-
- @Override
- public void contextInitialized(ServletContextEvent servletContextEvent) {
- prop = new Properties();
- Properties projectProp = new Properties();
- URL resource = getClass().getResource("/");
- String musicPropertiesFilePath = resource.getPath().replace("WEB-INF/classes/","WEB-INF/classes/project.properties");
-
- // Open the file
- try {
- InputStream musicProps = null;
- projectProp.load(new FileInputStream(musicPropertiesFilePath));
- if (projectProp.containsKey("music.properties")) {
- musicProps = new FileInputStream(projectProp.getProperty("music.properties"));
- } else {
- musicProps = new FileInputStream(MusicUtil.getMusicPropertiesFilePath());
- }
- prop.load(musicProps);
- musicProps.close();
- prop.putAll(projectProp);
- String[] propKeys = MusicUtil.getPropkeys();
- for (int k = 0; k < propKeys.length; k++) {
- String key = propKeys[k];
- if (prop.containsKey(key) && prop.get(key) != null) {
- logger.info(key + " : " + prop.getProperty(key));
- switch (key) {
- case "zookeeper.host":
- MusicUtil.setMyZkHost(prop.getProperty(key));
- break;
- case "cassandra.host":
- MusicUtil.setMyCassaHost(prop.getProperty(key));
- break;
- case "music.ip":
- MusicUtil.setDefaultMusicIp(prop.getProperty(key));
- break;
- case "debug":
- MusicUtil.setDebug(Boolean
- .getBoolean(prop.getProperty(key).toLowerCase()));
- break;
- case "version":
- MusicUtil.setVersion(prop.getProperty(key));
- break;
- case "music.rest.ip":
- MusicUtil.setMusicRestIp(prop.getProperty(key));
- break;
- case "music.properties":
- MusicUtil.setMusicPropertiesFilePath(prop.getProperty(key));
- break;
- case "lock.lease.period":
- MusicUtil.setDefaultLockLeasePeriod(
- Long.parseLong(prop.getProperty(key)));
- break;
- case "my.id":
- MusicUtil.setMyId(Integer.parseInt(prop.getProperty(key)));
- break;
- case "all.ids":
- String[] ids = prop.getProperty(key).split(":");
- MusicUtil.setAllIds(new ArrayList<String>(Arrays.asList(ids)));
- break;
- case "public.ip":
- MusicUtil.setPublicIp(prop.getProperty(key));
- break;
- case "all.public.ips":
- String[] ips = prop.getProperty(key).split(":");
- if (ips.length == 1) {
- // Future use
- } else if (ips.length > 1) {
- MusicUtil.setAllPublicIps(
- new ArrayList<String>(Arrays.asList(ips)));
- }
- break;
- case "cassandra.user":
- MusicUtil.setCassName(prop.getProperty(key));
- break;
- case "cassandra.password":
- MusicUtil.setCassPwd(prop.getProperty(key));
- break;
- case "aaf.endpoint.url":
- MusicUtil.setAafEndpointUrl(prop.getProperty(key));
- break;
- case "cassandra.port":
- MusicUtil.setCassandraPort(Integer.parseInt(prop.getProperty(key)));
- break;
- case "notify.interval":
- MusicUtil.setNotifyInterval(Integer.parseInt(prop.getProperty(key)));
- break;
- case "notify.timeout":
- MusicUtil.setNotifyTimeOut(Integer.parseInt(prop.getProperty(key)));
- break;
- default:
- logger.error(EELFLoggerDelegate.errorLogger,
- "No case found for " + key);
- }
- }
- }
- } catch (IOException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.IOERROR ,ErrorSeverity.CRITICAL, ErrorTypes.CONNECTIONERROR);
- logger.error(EELFLoggerDelegate.errorLogger, e.getMessage());
- }
-
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Starting MUSIC " + MusicUtil.getVersion() + " on node with id "
- + MusicUtil.getMyId() + " and public ip "
- + MusicUtil.getPublicIp() + "...");
- logger.info(EELFLoggerDelegate.applicationLogger,
- "List of all MUSIC ids:" + MusicUtil.getAllIds().toString());
- logger.info(EELFLoggerDelegate.applicationLogger,
- "List of all MUSIC public ips:" + MusicUtil.getAllPublicIps().toString());
- }
-
- @Override
- public void contextDestroyed(ServletContextEvent servletContextEvent) {
- prop = null;
- }
-}
diff --git a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java b/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java
deleted file mode 100755
index 0e365650..00000000
--- a/src/main/java/org/onap/music/rest/RestMusicAdminAPI.java
+++ /dev/null
@@ -1,845 +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.HashSet;
-import java.util.Iterator;
-import java.util.List;
-import java.nio.ByteBuffer;
-import java.nio.charset.Charset;
-import java.util.ArrayList;
-import java.util.Map;
-import java.util.Map.Entry;
-import java.util.Set;
-import java.util.UUID;
-
-import javax.ws.rs.Consumes;
-import javax.ws.rs.DELETE;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-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.codehaus.jackson.map.ObjectMapper;
-import org.mindrot.jbcrypt.BCrypt;
-import org.onap.music.datastore.PreparedQueryObject;
-import org.onap.music.datastore.jsonobjects.JSONCallbackResponse;
-import org.onap.music.datastore.jsonobjects.JSONObject;
-import org.onap.music.datastore.jsonobjects.JsonCallback;
-import org.onap.music.datastore.jsonobjects.JsonNotification;
-import org.onap.music.datastore.jsonobjects.JsonNotifyClientResponse;
-import org.onap.music.datastore.jsonobjects.JsonOnboard;
-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.CacheAccess;
-import org.onap.music.main.CachingUtil;
-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.Row;
-import com.datastax.driver.core.exceptions.InvalidQueryException;
-import com.sun.jersey.api.client.Client;
-import com.sun.jersey.api.client.ClientResponse;
-import com.sun.jersey.api.client.WebResource;
-import com.sun.jersey.core.util.Base64;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import com.datastax.driver.core.TableMetadata;
-
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import com.datastax.driver.core.ColumnDefinitions;
-import com.datastax.driver.core.ColumnDefinitions.Definition;
-import com.datastax.driver.core.TableMetadata;
-//import java.util.Base64.Encoder;
-//import java.util.Base64.Decoder;
-
-@Path("/v2/admin")
-// @Path("/v{version: [0-9]+}/admin")
-// @Path("/admin")
-@Api(value = "Admin Api", hidden = true)
-public class RestMusicAdminAPI {
- private static EELFLoggerDelegate logger =
- EELFLoggerDelegate.getLogger(RestMusicAdminAPI.class);
- /*
- * API to onboard an application with MUSIC. This is the mandatory first step.
- *
- */
- @POST
- @Path("/onboardAppWithMusic")
- @ApiOperation(value = "Onboard application", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response onboardAppWithMusic(JsonOnboard jsonObj) throws Exception {
- ResponseBuilder response =
- Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
- Map<String, Object> resultMap = new HashMap<>();
- String appName = jsonObj.getAppname();
- String userId = jsonObj.getUserId();
- String isAAF = jsonObj.getIsAAF();
- String password = jsonObj.getPassword();
- if (appName == null || userId == null || isAAF == null || password == null) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO,
- ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
- resultMap.put("Exception",
- "Unauthorized: Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing.");
- return Response.status(Status.UNAUTHORIZED).entity(resultMap).build();
- }
-
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "select uuid from admin.keyspace_master where application_name = ? allow filtering");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
- ResultSet rs = MusicCore.get(pQuery);
- if (!rs.all().isEmpty()) {
- resultMap.put("Exception", "Application " + appName
- + " has already been onboarded. Please contact admin.");
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
-
- pQuery = new PreparedQueryObject();
- String uuid = CachingUtil.generateUUID();
- pQuery.appendQueryString(
- "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
- + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),
- MusicUtil.DEFAULTKEYSPACENAME));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt())));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
-
- String returnStr = MusicCore.eventualPut(pQuery).toString();
- if (returnStr.contains("Failure")) {
- resultMap.put("Exception",
- "Oops. Something wrong with onboarding process. Please retry later or contact admin.");
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- CachingUtil.updateisAAFCache(appName, isAAF);
- resultMap.put("Success", "Your application " + appName + " has been onboarded with MUSIC.");
- resultMap.put("Generated AID", uuid);
- return Response.status(Status.OK).entity(resultMap).build();
- }
-
-
- @POST
- @Path("/search")
- @ApiOperation(value = "Search Onboard application", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response getOnboardedInfoSearch(JsonOnboard jsonObj) throws Exception {
- Map<String, Object> resultMap = new HashMap<>();
- ResponseBuilder response =
- Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
- String appName = jsonObj.getAppname();
- String uuid = jsonObj.getAid();
- String isAAF = jsonObj.getIsAAF();
-
- if (appName == null && uuid == null && isAAF == null) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO,
- ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
- resultMap.put("Exception",
- "Unauthorized: Please check the request parameters. Enter atleast one of the following parameters: appName(ns), aid, isAAF.");
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
-
- PreparedQueryObject pQuery = new PreparedQueryObject();
- String cql = "select uuid, keyspace_name from admin.keyspace_master where ";
- if (appName != null)
- cql = cql + "application_name = ? AND ";
- if (uuid != null)
- cql = cql + "uuid = ? AND ";
- if (isAAF != null)
- cql = cql + "is_aaf = ?";
-
- if (cql.endsWith("AND "))
- cql = cql.trim().substring(0, cql.length() - 4);
- logger.info("Query in callback is: " + cql);
- cql = cql + " allow filtering";
- pQuery.appendQueryString(cql);
- if (appName != null)
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
- if (uuid != null)
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
- if (isAAF != null)
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(),
- Boolean.parseBoolean(isAAF)));
- ResultSet rs = MusicCore.get(pQuery);
- Iterator<Row> it = rs.iterator();
- while (it.hasNext()) {
- Row row = (Row) it.next();
- resultMap.put(row.getUUID("uuid").toString(), row.getString("keyspace_name"));
- }
- if (resultMap.isEmpty()) {
- if (uuid != null) {
- resultMap.put("Exception",
- "Please make sure Aid is correct and application is onboarded.");
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- } else {
- resultMap.put("Exception",
- "Application is not onboarded. Please make sure all the information is correct.");
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- }
- return Response.status(Status.OK).entity(resultMap).build();
- }
-
-
- @DELETE
- @Path("/onboardAppWithMusic")
- @ApiOperation(value = "Delete Onboard application", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response deleteOnboardApp(JsonOnboard jsonObj) throws Exception {
- Map<String, Object> resultMap = new HashMap<>();
- ResponseBuilder response =
- Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
- String appName = jsonObj.getAppname();
- String aid = jsonObj.getAid();
- PreparedQueryObject pQuery = new PreparedQueryObject();
- String consistency = MusicUtil.EVENTUAL;;
- if (appName == null && aid == null) {
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGINFO,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- resultMap.put("Exception", "Please make sure either appName(ns) or Aid is present");
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- if (aid != null) {
- pQuery.appendQueryString(
- "SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
- UUID.fromString(aid)));
- Row row = MusicCore.get(pQuery).one();
- if (row != null) {
- String ks = row.getString("keyspace_name");
- if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString("DROP KEYSPACE IF EXISTS " + ks + ";");
- MusicCore.nonKeyRelatedPut(queryObject, consistency);
- }
- }
- pQuery = new PreparedQueryObject();
- pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ? IF EXISTS");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
- UUID.fromString(aid)));
- ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
- if (result == ResultType.SUCCESS) {
- resultMap.put("Success", "Your application has been deleted successfully");
- } else {
- resultMap.put("Exception",
- "Oops. Something went wrong. Please make sure Aid is correct or Application is onboarded");
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
-
- }
- return Response.status(Status.OK).entity(resultMap).build();
- }
-
- pQuery.appendQueryString(
- "select uuid from admin.keyspace_master where application_name = ? allow filtering");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
- ResultSet rs = MusicCore.get(pQuery);
- List<Row> rows = rs.all();
- String uuid = null;
- if (rows.size() == 0) {
- resultMap.put("Exception",
- "Application not found. Please make sure Application exists.");
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- } else if (rows.size() == 1) {
- uuid = rows.get(0).getUUID("uuid").toString();
- pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "SELECT keyspace_name FROM admin.keyspace_master WHERE uuid = ?");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
- UUID.fromString(uuid)));
- Row row = MusicCore.get(pQuery).one();
- String ks = row.getString("keyspace_name");
- if (!ks.equals(MusicUtil.DEFAULTKEYSPACENAME)) {
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString("DROP KEYSPACE " + ks + ";");
- MusicCore.nonKeyRelatedPut(queryObject, consistency);
- }
-
- pQuery = new PreparedQueryObject();
- pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
- UUID.fromString(uuid)));
- MusicCore.eventualPut(pQuery);
- resultMap.put("Success", "Your application " + appName + " has been deleted.");
- return Response.status(Status.OK).entity(resultMap).build();
- } else {
- resultMap.put("Failure",
- "More than one Aid exists for this application, so please provide Aid.");
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MULTIPLERECORDS,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- }
-
-
- @PUT
- @Path("/onboardAppWithMusic")
- @ApiOperation(value = "Update Onboard application", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response updateOnboardApp(JsonOnboard jsonObj) throws Exception {
- Map<String, Object> resultMap = new HashMap<>();
- ResponseBuilder response =
- Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
- String aid = jsonObj.getAid();
- String appName = jsonObj.getAppname();
- String userId = jsonObj.getUserId();
- String isAAF = jsonObj.getIsAAF();
- String password = jsonObj.getPassword();
- String consistency = "eventual";
- PreparedQueryObject pQuery;
-
- if (aid == null) {
- resultMap.put("Exception", "Please make sure Aid is present");
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
-
- if (appName == null && userId == null && password == null && isAAF == null) {
- resultMap.put("Exception",
- "No parameters found to update. Please update atleast one parameter.");
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
-
- if (appName != null) {
- pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "select uuid from admin.keyspace_master where application_name = ? allow filtering");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
- ResultSet rs = MusicCore.get(pQuery);
- if (!rs.all().isEmpty()) {
- resultMap.put("Exception", "Application " + appName
- + " has already been onboarded. Please contact admin.");
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.ALREADYEXIST,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- }
-
- pQuery = new PreparedQueryObject();
- StringBuilder preCql = new StringBuilder("UPDATE admin.keyspace_master SET ");
- if (appName != null)
- preCql.append(" application_name = ?,");
- if (userId != null)
- preCql.append(" username = ?,");
- if (password != null)
- preCql.append(" password = ?,");
- if (isAAF != null)
- preCql.append(" is_aaf = ?,");
- preCql.deleteCharAt(preCql.length() - 1);
- preCql.append(" WHERE uuid = ? IF EXISTS");
- pQuery.appendQueryString(preCql.toString());
- if (appName != null)
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
- if (userId != null)
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
- if (password != null)
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt())));
- if (isAAF != null)
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
-
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), UUID.fromString(aid)));
- ResultType result = MusicCore.nonKeyRelatedPut(pQuery, consistency);
-
- if (result == ResultType.SUCCESS) {
- resultMap.put("Success", "Your application has been updated successfully");
- } else {
- resultMap.put("Exception",
- "Oops. Something went wrong. Please make sure Aid is correct and application is onboarded");
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
-
- return Response.status(Status.OK).entity(resultMap).build();
- }
-
- Client client = Client.create();
- ObjectMapper mapper = new ObjectMapper();
-
- @POST
- @Path("/callbackOps")
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.APPLICATION_JSON)
- public Response callbackOps(final JSONObject inputJsonObj) {
- // {"keyspace":"conductor","full_table":"conductor.plans","changeValue":{"conductor.plans.status":"Who??","position":"3"},"operation":"update","table_name":"plans","primary_key":"3"}
- Map<String, Object> resultMap = new HashMap<>();
- new Thread(new Runnable() {
- public void run() {
- makeAsyncCall(inputJsonObj);
- }
- }).start();
-
- return Response.status(Status.OK).entity(resultMap).build();
- }
-
- private Response makeAsyncCall(JSONObject inputJsonObj) {
-
- Map<String, Object> resultMap = new HashMap<>();
- try {
- logger.info(EELFLoggerDelegate.applicationLogger, "Got notification: " + inputJsonObj.getData());
- String dataStr = inputJsonObj.getData();
- JSONCallbackResponse jsonResponse = mapper.readValue(dataStr, JSONCallbackResponse.class);
- String operation = jsonResponse.getOperation();
- Map<String, String> changeValueMap = jsonResponse.getChangeValue();
- String primaryKey = jsonResponse.getPrimary_key();
- String ksTableName = jsonResponse.getFull_table(); //conductor.plans
- if(ksTableName.equals("admin.notification_master")) {
- CachingUtil.updateCallbackNotifyList(new ArrayList<String>());
- return Response.status(Status.OK).entity(resultMap).build();
- }
- List<String> inputUpdateList = jsonResponse.getUpdateList();
- /*String field_value = changeValueMap.get("field_value");
- if(field_value == null)
- field_value = jsonResponse.getFull_table();*/
- String field_value = null;
- List<String> notifiyList = CachingUtil.getCallbackNotifyList();
- if(notifiyList == null || notifiyList.isEmpty()) {
- logger.info("Is cache empty? reconstructing Object from cache..");
- constructJsonCallbackFromCache();
- /*notifiyList = CachingUtil.getCallbackNotifyList();
- if("update".equals(operation)) {
- List<String> updateList = jsonResponse.getUpdateList();
- //logger.info("update list from trigger: "+updateList);
- for(String element : updateList) {
- logger.info("element: "+element);
- logger.info("notifiyList: "+notifiyList);
- if(notifiyList.contains(element)) {
- logger.info("Found the notifyOn property: "+element);
- field_value = element;
- }
- }
- }
-
- baseRequestObj = CachingUtil.getCallBackCache(field_value);
- logger.info("Reconstructing Object from cache is Successful.."+baseRequestObj);*/
- }
- notifiyList = CachingUtil.getCallbackNotifyList();
- JsonCallback baseRequestObj = null;
-
- if("update".equals(operation)) {
- for(String element: inputUpdateList) {
- baseRequestObj = CachingUtil.getCallBackCache(element);
- if(baseRequestObj != null) {
- logger.info("Found the element that was changed... "+element);
- break;
- }
- }
-
- List<String> updateList = jsonResponse.getUpdateList();
- //logger.info("update list from trigger: "+updateList);
- for(String element : updateList) {
- if(notifiyList.contains(element)) {
- logger.info("Found the notifyOn property: "+element);
- field_value = element;
- break;
- }
- }
- if(baseRequestObj == null || field_value == null) {
- for(String element: inputUpdateList) {
- String[] elementArr = element.split(":");
- String newElement = null;
- if(elementArr.length >= 2) {
- newElement = elementArr[0]+":"+elementArr[1];
- }
- baseRequestObj = CachingUtil.getCallBackCache(newElement);
- if(baseRequestObj != null) {
- logger.info("Found the element that was changed... "+newElement);
- break;
- }
- }
- for(String element : updateList) {
- String[] elementArr = element.split(":");
- String newElement = null;
- if(elementArr.length >= 2) {
- newElement = elementArr[0]+":"+elementArr[1];
- }
- if(notifiyList.contains(newElement)) {
- logger.info("Found the notifyOn property: "+newElement);
- field_value = newElement;
- break;
- }
- }
- }
- } else {
- field_value = jsonResponse.getFull_table();
- baseRequestObj = CachingUtil.getCallBackCache(field_value);
- }
-
- if(baseRequestObj == null) {
- resultMap.put("Exception",
- "Oops. Something went wrong. Please make sure Callback properties are onboarded.");
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.INCORRECTDATA,
- ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- logger.info("Going through list: "+operation+ " && List: "+jsonResponse.getUpdateList());
-
- String key = "admin" + "." + "notification_master" + "." + baseRequestObj.getUuid();
- String lockId = MusicCore.createLockReference(key);
- ReturnType lockAcqResult = MusicCore.acquireLock(key, lockId);
- if(! lockAcqResult.getResult().toString().equals("SUCCESS")) {
- logger.error(EELFLoggerDelegate.errorLogger, "Some other node is notifying the caller..: ");
- }
-
- logger.info(operation+ ": Operation :: changeValue: "+changeValueMap);
- if(operation.equals("update")) {
- String notifyWhenChangeIn = baseRequestObj.getNotifyWhenChangeIn(); // conductor.plans.status
- if(null!=field_value) {
- if(field_value.equals(notifyWhenChangeIn)) {
- notifyCallBackAppl(jsonResponse, baseRequestObj);
- }
- }
- } else if(operation.equals("delete")) {
- String notifyWhenDeletesIn = baseRequestObj.getNotifyWhenDeletesIn(); // conductor.plans.status
- if(null!=field_value) {
- if(field_value.equals(notifyWhenDeletesIn)) {
- notifyCallBackAppl(jsonResponse, baseRequestObj);
- }
- }
- } else if(operation.equals("insert")) {
- String notifyWhenInsertsIn = baseRequestObj.getNotifyWhenInsertsIn(); // conductor.plans.status
- if(null!=field_value) {
- if(field_value.equals(notifyWhenInsertsIn)) {
- notifyCallBackAppl(jsonResponse, baseRequestObj);
- }
- }
- }
- MusicCore.releaseLock(lockId, true);
- } catch(Exception e) {
- e.printStackTrace();
- logger.info("Exception...");
- }
- logger.info(EELFLoggerDelegate.applicationLogger, "callback is completed. Notification was sent from Music...");
- return Response.status(Status.OK).entity(resultMap).build();
- }
-
- private void notifyCallBackAppl(JSONCallbackResponse jsonResponse, JsonCallback baseRequestObj) {
- int notifytimeout = MusicUtil.getNotifyTimeout();
- int notifyinterval = MusicUtil.getNotifyInterval();
- String endpoint = baseRequestObj.getApplicationNotificationEndpoint();
- String username = baseRequestObj.getApplicationUsername();
- String password = baseRequestObj.getApplicationPassword();
- JsonNotification jsonNotification = constructJsonNotification(jsonResponse, baseRequestObj);
- jsonNotification.setOperation_type(jsonResponse.getOperation());
- logger.info(EELFLoggerDelegate.applicationLogger, "Notification Response sent is: "+jsonNotification);
- WebResource webResource = client.resource(endpoint);
- String authData = username+":"+password;
- byte[] plainCredsBytes = authData.getBytes();
- byte[] base64CredsBytes = Base64.encode(plainCredsBytes);
- String base64Creds = new String(base64CredsBytes);
- Map<String, String> response_body = baseRequestObj.getResponseBody();
- ClientResponse response = null;
- try {
- response = webResource.header("Authorization", "Basic " + base64Creds).accept("application/json").type("application/json")
- .post(ClientResponse.class, jsonNotification);
- } catch (com.sun.jersey.api.client.ClientHandlerException chf) {
- boolean ok = false;
- logger.info(EELFLoggerDelegate.applicationLogger, "Is Service down?");
- long now= System.currentTimeMillis();
- long end = now+notifytimeout;
- while(! ok) {
- logger.info(EELFLoggerDelegate.applicationLogger, "retrying since error in notifying callback..");
- try {
- response = webResource.header("Authorization", "Basic " + base64Creds).accept("application/json").type("application/json")
- .post(ClientResponse.class, jsonNotification);
- if(response.getStatus() == 200) ok = true;
- }catch (Exception e) {
- logger.info(EELFLoggerDelegate.applicationLogger, "Retry until "+(end-System.currentTimeMillis()));
- if(response == null && System.currentTimeMillis() < end) ok = false;
- else ok = true;
- try{ Thread.sleep(notifyinterval); } catch(Exception e1) {}
- }
- }
- }
- if(response == null) {
- logger.error(EELFLoggerDelegate.errorLogger, "Can NOT notify the caller as caller failed to respond..");
- return;
- }
- JsonNotifyClientResponse responseStr = response.getEntity(JsonNotifyClientResponse.class);
- logger.info(EELFLoggerDelegate.applicationLogger, "Response from Notified client: "+responseStr);
-
- if(response.getStatus() != 200){
- long now= System.currentTimeMillis();
- long end = now+30000;
- while(response.getStatus() != 200 && System.currentTimeMillis() < end) {
- logger.info(EELFLoggerDelegate.applicationLogger, "retrying since error in notifying callback..");
- response = webResource.header("Authorization", "Basic " + base64Creds).accept("application/json").type("application/json")
- .post(ClientResponse.class, jsonNotification);
- }
- logger.info(EELFLoggerDelegate.applicationLogger, "Exception while notifying.. "+response.getStatus());
- }
- }
-
- private JsonNotification constructJsonNotification(JSONCallbackResponse jsonResponse, JsonCallback baseRequestObj) {
-
- JsonNotification jsonNotification = new JsonNotification();
- try {
- jsonNotification.setNotify_field(baseRequestObj.getNotifyOn());
- jsonNotification.setEndpoint(baseRequestObj.getApplicationNotificationEndpoint());
- jsonNotification.setUsername(baseRequestObj.getApplicationUsername());
- jsonNotification.setPassword(baseRequestObj.getApplicationPassword());
- String pkValue = jsonResponse.getPrimary_key();
-
- String[] fullNotifyArr = baseRequestObj.getNotifyOn().split(":");
-
- String[] tableArr = fullNotifyArr[0].split("\\.");
- TableMetadata tableInfo = MusicCore.returnColumnMetadata(tableArr[0], tableArr[1]);
- DataType primaryIdType = tableInfo.getPrimaryKey().get(0).getType();
- String primaryId = tableInfo.getPrimaryKey().get(0).getName();
-
- Map<String, String> responseBodyMap = baseRequestObj.getResponseBody();
- Map<String, String> newMap = new HashMap<>();
- if(responseBodyMap.size() == 1 && responseBodyMap.containsKey("")) {
- jsonNotification.setResponse_body(newMap);
- } else {
- for (Entry<String, String> entry : new HashSet<>(responseBodyMap.entrySet())) {
- String trimmed = entry.getKey().trim();
- if (!trimmed.equals(entry.getKey())) {
- responseBodyMap.remove(entry.getKey());
- responseBodyMap.put(trimmed, entry.getValue());
- }
- }
-
- Set<String> keySet = responseBodyMap.keySet();
- String cql = "select *";
- /*for(String keys: keySet) {
- cql = cql + keys + ",";
- }*/
- //cql = cql.substring(0, cql.length()-1);
- cql = cql + " FROM "+fullNotifyArr[0]+" WHERE "+primaryId+" = ?";
- logger.info("CQL in constructJsonNotification: "+cql);
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(cql);
- pQuery.addValue(MusicUtil.convertToActualDataType(primaryIdType, pkValue));
- Row row = MusicCore.get(pQuery).one();
- if(row != null) {
- ColumnDefinitions colInfo = row.getColumnDefinitions();
- for (Definition definition : colInfo) {
- String colName = definition.getName();
- if(keySet.contains(colName)) {
- DataType colType = definition.getType();
- Object valueObj = MusicCore.getDSHandle().getColValue(row, colName, colType);
- Object valueString = MusicUtil.convertToActualDataType(colType, valueObj);
- logger.info(colName+" : "+valueString);
- newMap.put(colName, valueString.toString());
- keySet.remove(colName);
- }
- }
- }
- if(! keySet.isEmpty()) {
- Iterator<String> iterator = keySet.iterator();
- while (iterator.hasNext()) {
- String element = iterator.next();
- if(element != null && element.length() > 0)
- newMap.put(element,"COLUMN_NOT_FOUND");
- }
- }
-
- if("delete".equals(jsonResponse.getOperation()) || newMap.isEmpty()) {
- newMap.put(primaryId, pkValue);
- }
- jsonNotification.setResponse_body(newMap);
- }
- } catch(Exception e) {
- e.printStackTrace();
- }
- return jsonNotification;
- }
-
- private void constructJsonCallbackFromCache() throws Exception{
- PreparedQueryObject pQuery = new PreparedQueryObject();
- JsonCallback jsonCallback = null;
- List<String> notifyList = new java.util.ArrayList<>();
- String cql =
- "select id, endpoint_userid, endpoint_password, notify_to_endpoint, notify_insert_on,"
- + " notify_delete_on, notify_update_on, request, notifyon from admin.notification_master allow filtering";
- pQuery.appendQueryString(cql);
- //pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), fullTable));
- logger.info("Query: "+pQuery.getQuery());
-
- ResultSet rs = MusicCore.get(pQuery);
- Iterator<Row> it = rs.iterator();
- while (it.hasNext()) {
- Row row = (Row) it.next();
- String endpoint = row.getString("notify_to_endpoint");
- String username = row.getString("endpoint_userid");
- ByteBuffer passwordBytes = row.getBytes("endpoint_password");
- String insert = row.getString("notify_insert_on");
- String delete = row.getString("notify_delete_on");
- String update = row.getString("notify_update_on");
- String request = row.getString("request");
- String notifyon = row.getString("notifyon");
- String uuid = row.getUUID("id").toString();
- notifyList.add(notifyon);
- jsonCallback = new JsonCallback();
- jsonCallback.setApplicationNotificationEndpoint(endpoint);
-
- Charset charset = Charset.forName("ISO-8859-1");
- String decodedPwd = charset.decode(passwordBytes).toString();
- jsonCallback.setApplicationPassword(decodedPwd);
- jsonCallback.setApplicationUsername(username);
- jsonCallback.setNotifyOn(notifyon);
- jsonCallback.setNotifyWhenInsertsIn(insert);
- jsonCallback.setNotifyWhenDeletesIn(delete);
- jsonCallback.setNotifyWhenChangeIn(update);
- jsonCallback.setUuid(uuid);
- logger.info("From DB. Saved request_body: "+request);
- request = request.substring(1, request.length()-1);
- String[] keyValuePairs = request.split(",");
- Map<String,String> responseBody = new HashMap<>();
-
- for(String pair : keyValuePairs) {
- String[] entry = pair.split("=");
- String val = "";
- if(entry.length == 2)
- val = entry[1];
- responseBody.put(entry[0], val);
- }
- logger.info("After parsing. Saved request_body: "+responseBody);
- jsonCallback.setResponseBody(responseBody);
- logger.info("Updating Cache with updateCallBackCache: "+notifyon+ " :::: "+jsonCallback);
- CachingUtil.updateCallBackCache(notifyon, jsonCallback);
- }
- CachingUtil.updateCallbackNotifyList(notifyList);
- }
-
- @POST
- @Path("/onboardCallback")
- @Produces(MediaType.APPLICATION_JSON)
- @Consumes(MediaType.APPLICATION_JSON)
- public Response addCallback(JsonNotification jsonNotification) {
- Map<String, Object> resultMap = new HashMap<>();
- ResponseBuilder response =
- Response.noContent().header("X-latestVersion", MusicUtil.getVersion());
- String username = jsonNotification.getUsername();
- String password = jsonNotification.getPassword();
- String endpoint = jsonNotification.getEndpoint();
- String notify_field = jsonNotification.getNotify_field();
- Map<String, String> responseBody = jsonNotification.getResponse_body();
- String triggerName = jsonNotification.getTriggerName();
- if(triggerName == null || triggerName.length() == 0)
- triggerName = "MusicTrigger";
-
- /*JsonCallback callBackCache = CachingUtil.getCallBackCache(notify_field);
- if(callBackCache != null) {
- resultMap.put("Exception", "The notification property has already been onboarded.");
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }*/
-
- String[] allFields = notify_field.split(":");
- String inserts = null;
- String updates = null;
- String deletes = null;
- String tableName = null;
- if(allFields.length >= 2) {
- inserts = updates = notify_field;
- } else if(allFields.length == 1) {
- inserts = deletes = notify_field;;
- }
- tableName = allFields[0];
- String cql = "CREATE TRIGGER IF NOT EXISTS musictrigger ON "+tableName+" Using '"+triggerName+"'";
- PreparedQueryObject pQuery = new PreparedQueryObject();
-
- String uuid = CachingUtil.generateUUID();
- try {
- pQuery.appendQueryString(
- "INSERT INTO admin.notification_master (id, endpoint_userid, endpoint_password, notify_to_endpoint, "
- + "notifyon, notify_insert_on, notify_delete_on, notify_update_on, request, current_notifier) VALUES (?,?,?,?,?,?,?,?,?,?)");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), username));
- Charset charset = Charset.forName("ISO-8859-1");
- ByteBuffer decodedPwd = charset.encode(password);
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.blob(), decodedPwd.array()));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), endpoint));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), notify_field));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), inserts));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), deletes));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), updates));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), responseBody));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), MusicCore.getMyHostId()));
- MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.EVENTUAL);
- JsonCallback jsonCallback = new JsonCallback();
- jsonCallback.setUuid(uuid);
- jsonCallback.setApplicationNotificationEndpoint(endpoint);
- jsonCallback.setApplicationPassword(password);
- jsonCallback.setApplicationUsername(username);
- jsonCallback.setNotifyOn(notify_field);
- jsonCallback.setNotifyWhenChangeIn(updates);
- jsonCallback.setNotifyWhenDeletesIn(deletes);
- jsonCallback.setNotifyWhenInsertsIn(inserts);
- jsonCallback.setResponseBody(responseBody);
- CachingUtil.updateCallBackCache(notify_field, jsonCallback);
- logger.info("Cache updated ");
- pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(cql);
- ResultType nonKeyRelatedPut = MusicCore.nonKeyRelatedPut(pQuery, MusicUtil.EVENTUAL);
- logger.info(EELFLoggerDelegate.applicationLogger, "Created trigger");
- //callBackCache.put(jsonCallback.getApplicationName(), jsonMap);
- } catch (InvalidQueryException e) {
- logger.error(EELFLoggerDelegate.errorLogger,"Exception callback_api table not configured."+e.getMessage());
- resultMap.put("Exception", "Please make sure admin.notification_master table is configured.");
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- } catch(Exception e) {
- e.printStackTrace();
- resultMap.put("Exception", "Exception Occured.");
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Callback api successfully registered").toMap()).build();
- }
-
- /*public String encodePwd(String password) {
- return Base64.getEncoder().encodeToString(password.getBytes());
- }
-
- public String decodePwd(String password) {
- byte[] bytes = Base64.getDecoder().decode(password);
- return new String(bytes);
- }*/
-}
diff --git a/src/main/java/org/onap/music/rest/RestMusicBmAPI.java b/src/main/java/org/onap/music/rest/RestMusicBmAPI.java
deleted file mode 100644
index 55eb47f2..00000000
--- a/src/main/java/org/onap/music/rest/RestMusicBmAPI.java
+++ /dev/null
@@ -1,307 +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.List;
-import java.util.Map;
-import java.util.UUID;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.GET;
-import javax.ws.rs.POST;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.PathParam;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.Context;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.UriInfo;
-import org.onap.music.datastore.jsonobjects.JsonInsert;
-import org.onap.music.eelf.logging.EELFLoggerDelegate;
-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.datastore.PreparedQueryObject;
-import com.datastax.driver.core.DataType;
-import com.datastax.driver.core.TableMetadata;
-import io.swagger.annotations.Api;
-//import io.swagger.annotations.ApiOperation;
-//import io.swagger.annotations.ApiParam;
-
-/*
- * These are functions created purely for benchmarking purposes. Commented out Swagger - This should
- * be undocumented API
- *
- */
-@Path("/v{version: [0-9]+}/benchmarks/")
-@Api(value = "Benchmark API", hidden = true)
-public class RestMusicBmAPI {
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicBmAPI.class);
-
- // pure zk calls...
-
- /**
- *
- * @param nodeName
- * @throws Exception
- */
- @POST
- @Path("/purezk/{name}")
- @Consumes(MediaType.APPLICATION_JSON)
- public void pureZkCreate(@PathParam("name") String nodeName) throws Exception {
- MusicCore.pureZkCreate("/" + nodeName);
- }
-
-
- /**
- *
- * @param insObj
- * @param nodeName
- * @throws Exception
- */
- @PUT
- @Path("/purezk/{name}")
- @Consumes(MediaType.APPLICATION_JSON)
- public void pureZkUpdate(JsonInsert insObj, @PathParam("name") String nodeName)
- throws Exception {
- logger.info(EELFLoggerDelegate.applicationLogger,"--------------Zk normal update-------------------------");
- long start = System.currentTimeMillis();
- MusicCore.pureZkWrite(nodeName, insObj.serialize());
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Total time taken for Zk normal update:" + (end - start) + " ms");
- }
-
- /**
- *
- * @param nodeName
- * @return
- * @throws Exception
- */
- @GET
- @Path("/purezk/{name}")
- @Consumes(MediaType.TEXT_PLAIN)
- public byte[] pureZkGet(@PathParam("name") String nodeName) throws Exception {
- return MusicCore.pureZkRead(nodeName);
- }
-
- /**
- *
- * @param insObj
- * @param lockName
- * @param nodeName
- * @throws Exception
- */
- @PUT
- @Path("/purezk/atomic/{lockname}/{name}")
- @Consumes(MediaType.APPLICATION_JSON)
- public void pureZkAtomicPut(JsonInsert updateObj, @PathParam("lockname") String lockname,
- @PathParam("name") String nodeName) throws Exception {
- long startTime = System.currentTimeMillis();
- String operationId = UUID.randomUUID().toString();// just for debugging purposes.
- String consistency = updateObj.getConsistencyInfo().get("type");
-
- logger.info(EELFLoggerDelegate.applicationLogger,"--------------Zookeeper " + consistency + " update-" + operationId
- + "-------------------------");
-
- byte[] data = updateObj.serialize();
- long jsonParseCompletionTime = System.currentTimeMillis();
-
- String lockId = MusicCore.createLockReference(lockname);
-
- long lockCreationTime = System.currentTimeMillis();
-
- long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
- ReturnType lockAcqResult = MusicCore.acquireLockWithLease(lockname, lockId, leasePeriod);
- long lockAcqTime = System.currentTimeMillis();
- long zkPutTime = 0, lockReleaseTime = 0;
-
- if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
- logger.info(EELFLoggerDelegate.applicationLogger,"acquired lock with id " + lockId);
- MusicCore.pureZkWrite(lockname, data);
- zkPutTime = System.currentTimeMillis();
- boolean voluntaryRelease = true;
- if (consistency.equals("atomic"))
- MusicCore.releaseLock(lockId, voluntaryRelease);
- else if (consistency.equals("atomic_delete_lock"))
- MusicCore.deleteLock(lockname);
- lockReleaseTime = System.currentTimeMillis();
- } else {
- MusicCore.destroyLockRef(lockId);
- }
-
- long actualUpdateCompletionTime = System.currentTimeMillis();
-
-
- long endTime = System.currentTimeMillis();
-
- String lockingInfo = "|lock creation time:" + (lockCreationTime - jsonParseCompletionTime)
- + "|lock accquire time:" + (lockAcqTime - lockCreationTime)
- + "|zk put time:" + (zkPutTime - lockAcqTime);
-
- if (consistency.equals("atomic"))
- lockingInfo = lockingInfo + "|lock release time:" + (lockReleaseTime - zkPutTime) + "|";
- else if (consistency.equals("atomic_delete_lock"))
- lockingInfo = lockingInfo + "|lock delete time:" + (lockReleaseTime - zkPutTime) + "|";
-
- String timingString = "Time taken in ms for Zookeeper " + consistency + " update-"
- + operationId + ":" + "|total operation time:" + (endTime - startTime)
- + "|json parsing time:" + (jsonParseCompletionTime - startTime)
- + "|update time:" + (actualUpdateCompletionTime - jsonParseCompletionTime)
- + lockingInfo;
-
- logger.info(EELFLoggerDelegate.applicationLogger,timingString);
- }
-
- /**
- *
- * @param insObj
- * @param lockName
- * @param nodeName
- * @throws Exception
- */
- @GET
- @Path("/purezk/atomic/{lockname}/{name}")
- @Consumes(MediaType.APPLICATION_JSON)
- public void pureZkAtomicGet(JsonInsert insObj, @PathParam("lockname") String lockName,
- @PathParam("name") String nodeName) throws Exception {
- logger.info("--------------Zk atomic read-------------------------");
- long start = System.currentTimeMillis();
- String lockId = MusicCore.createLockReference(lockName);
- long leasePeriod = MusicUtil.getDefaultLockLeasePeriod();
- ReturnType lockAcqResult = MusicCore.acquireLockWithLease(lockName, lockId, leasePeriod);
- if (lockAcqResult.getResult().equals(ResultType.SUCCESS)) {
- logger.info("acquired lock with id " + lockId);
- MusicCore.pureZkRead(nodeName);
- boolean voluntaryRelease = true;
- MusicCore.releaseLock(lockId, voluntaryRelease);
- } else {
- MusicCore.destroyLockRef(lockId);
- }
-
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Total time taken for Zk atomic read:" + (end - start) + " ms");
- }
-
- /**
- *
- * doing an update directly to cassa but through the rest api
- *
- * @param insObj
- * @param keyspace
- * @param tablename
- * @param info
- * @return
- * @throws Exception
- */
- @PUT
- @Path("/cassa/keyspaces/{keyspace}/tables/{tablename}/rows")
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public boolean updateTableCassa(JsonInsert insObj, @PathParam("keyspace") String keyspace,
- @PathParam("tablename") String tablename, @Context UriInfo info)
- throws Exception {
- long startTime = System.currentTimeMillis();
- String operationId = UUID.randomUUID().toString();// just for debugging purposes.
- String consistency = insObj.getConsistencyInfo().get("type");
- logger.info(EELFLoggerDelegate.applicationLogger,"--------------Cassandra " + consistency + " update-" + operationId
- + "-------------------------");
- PreparedQueryObject queryObject = new PreparedQueryObject();
- Map<String, Object> valuesMap = insObj.getValues();
- TableMetadata tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename);
- String vectorTs = "'" + Thread.currentThread().getId() + System.currentTimeMillis() + "'";
- String fieldValueString = "vector_ts= ? ,";
- queryObject.addValue(vectorTs);
-
- int counter = 0;
- for (Map.Entry<String, Object> entry : valuesMap.entrySet()) {
- Object valueObj = entry.getValue();
- DataType colType = tableInfo.getColumn(entry.getKey()).getType();
- Object valueString = MusicUtil.convertToActualDataType(colType, valueObj);
- fieldValueString = fieldValueString + entry.getKey() + "= ?";
- queryObject.addValue(valueString);
- if (counter != valuesMap.size() - 1)
- fieldValueString = fieldValueString + ",";
- counter = counter + 1;
- }
-
- // get the row specifier
- String rowSpec = "";
- counter = 0;
- queryObject.appendQueryString("UPDATE " + keyspace + "." + tablename + " ");
- MultivaluedMap<String, String> rowParams = info.getQueryParameters();
- String primaryKey = "";
- for (MultivaluedMap.Entry<String, List<String>> entry : rowParams.entrySet()) {
- String keyName = entry.getKey();
- List<String> valueList = entry.getValue();
- String indValue = valueList.get(0);
- DataType colType = tableInfo.getColumn(entry.getKey()).getType();
- Object formattedValue = MusicUtil.convertToActualDataType(colType, indValue);
- primaryKey = primaryKey + indValue;
- rowSpec = rowSpec + keyName + "= ? ";
- queryObject.addValue(formattedValue);
- if (counter != rowParams.size() - 1)
- rowSpec = rowSpec + " AND ";
- counter = counter + 1;
- }
-
-
- String ttl = insObj.getTtl();
- String timestamp = insObj.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(" SET " + fieldValueString + " WHERE " + rowSpec + ";");
-
- long jsonParseCompletionTime = System.currentTimeMillis();
-
- boolean operationResult = true;
- MusicCore.getDSHandle().executePut(queryObject, insObj.getConsistencyInfo().get("type"));
-
- long actualUpdateCompletionTime = System.currentTimeMillis();
-
- long endTime = System.currentTimeMillis();
-
- String timingString = "Time taken in ms for Cassandra " + consistency + " update-"
- + operationId + ":" + "|total operation time:" + (endTime - startTime)
- + "|json parsing time:" + (jsonParseCompletionTime - startTime)
- + "|update time:" + (actualUpdateCompletionTime - jsonParseCompletionTime)
- + "|";
- logger.info(EELFLoggerDelegate.applicationLogger,timingString);
-
- return operationResult;
- }
-}
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 2d1a8836..00000000
--- a/src/main/java/org/onap/music/rest/RestMusicDataAPI.java
+++ /dev/null
@@ -1,1467 +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.nio.ByteBuffer;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.servlet.http.HttpServletResponse;
-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.HttpHeaders;
-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.apache.commons.lang3.StringUtils;
-import org.mindrot.jbcrypt.BCrypt;
-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.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.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.MusicServiceException;
-import org.onap.music.main.CachingUtil;
-import org.onap.music.main.MusicCore;
-import org.onap.music.main.MusicCore.Condition;
-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.Row;
-import com.datastax.driver.core.TableMetadata;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-
-/* 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 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)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- //public Map<String, Object> createKeySpace(
- 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 = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
- JsonKeySpace kspObject,
- @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- Map<String, Object> authMap = CachingUtil.verifyOnboarding(ns, userId, password);
- if (!authMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
- response.status(Status.UNAUTHORIZED);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build();
- }
- if(kspObject == null || kspObject.getReplicationInfo() == null) {
- authMap.put(ResultType.EXCEPTION.getResult(), ResultType.BODYMISSING.getResult());
- response.status(Status.BAD_REQUEST);
- return response.entity(authMap).build();
- }
-
-
- try {
- authMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
- "createKeySpace");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- response.status(Status.BAD_REQUEST);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError("Unable to authenticate.").toMap()).build();
- }
- String newAid = null;
- if (!authMap.isEmpty()) {
- if (authMap.containsKey("aid")) {
- newAid = (String) authMap.get("aid");
- } else {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
- response.status(Status.UNAUTHORIZED);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build();
- }
- }
-
- String consistency = MusicUtil.EVENTUAL;// for now this needs only
- // eventual consistency
-
- PreparedQueryObject queryObject = new PreparedQueryObject();
- long start = System.currentTimeMillis();
- Map<String, Object> replicationInfo = kspObject.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 (kspObject.getDurabilityOfWrites() != null) {
- queryObject.appendQueryString(
- " AND durable_writes = " + kspObject.getDurabilityOfWrites());
- }
-
- queryObject.appendQueryString(";");
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,
- "Time taken for setting up query in create keyspace:" + (end - start));
-
- ResultType result = ResultType.FAILURE;
- try {
- result = MusicCore.nonKeyRelatedPut(queryObject, consistency);
- logger.info(EELFLoggerDelegate.applicationLogger, "result = " + result);
- } catch ( MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("err:" + ex.getMessage()).toMap()).build();
- }
-
- try {
- queryObject = new PreparedQueryObject();
- queryObject.appendQueryString("CREATE ROLE IF NOT EXISTS '" + userId
- + "' WITH PASSWORD = '" + password + "' AND LOGIN = true;");
- MusicCore.nonKeyRelatedPut(queryObject, consistency);
- queryObject = new PreparedQueryObject();
- queryObject.appendQueryString("GRANT ALL PERMISSIONS on KEYSPACE " + keyspaceName
- + " to '" + userId + "'");
- queryObject.appendQueryString(";");
- MusicCore.nonKeyRelatedPut(queryObject, consistency);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- }
-
- try {
- boolean isAAF = Boolean.valueOf(CachingUtil.isAAFApplication(ns));
- String hashedpwd = BCrypt.hashpw(password, BCrypt.gensalt());
- queryObject = new PreparedQueryObject();
- queryObject.appendQueryString(
- "INSERT into admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
- + "password, username, is_aaf) values (?,?,?,?,?,?,?)");
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), newAid));
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), keyspaceName));
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), ns));
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), hashedpwd));
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
- queryObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
- CachingUtil.updateMusicCache(keyspaceName, ns);
- CachingUtil.updateMusicValidateCache(ns, userId, hashedpwd);
- MusicCore.eventualPut(queryObject);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- return response.status(Response.Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
- }
-
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Created").toMap()).build();
- }
-
- /**
- *
- * @param kspObject
- * @param keyspaceName
- * @return
- * @throws Exception
- */
- @DELETE
- @Path("/{name}")
- @ApiOperation(value = "Delete Keyspace", response = String.class)
- @Produces(MediaType.APPLICATION_JSON)
- //public Map<String, Object> dropKeySpace(
- 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 = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "Application namespace",required = true) @HeaderParam(NS) String ns,
- @ApiParam(value = "Keyspace Name",required = true) @PathParam("name") String keyspaceName) throws Exception {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password,keyspaceName, aid, "dropKeySpace");
- if (authMap.containsKey("aid"))
- authMap.remove("aid");
- if (!authMap.isEmpty()) {
- return response.status(Status.UNAUTHORIZED).entity(authMap).build();
- }
-
- String consistency = MusicUtil.EVENTUAL;// for now this needs only
- // eventual
- // consistency
- String appName = CachingUtil.getAppName(keyspaceName);
- String uuid = CachingUtil.getUuidFromMusicCache(keyspaceName);
- PreparedQueryObject pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "select count(*) as count from admin.keyspace_master where application_name=? allow filtering;");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
- Row row = MusicCore.get(pQuery).one();
- long count = row.getLong(0);
-
- if (count == 0) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Keyspace not found. Please make sure keyspace exists.").toMap()).build();
- // Admin Functions:
- } else if (count == 1) {
- pQuery = new PreparedQueryObject();
- pQuery.appendQueryString(
- "UPDATE admin.keyspace_master SET keyspace_name=? where uuid = ?;");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.text(),
- MusicUtil.DEFAULTKEYSPACENAME));
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
- MusicCore.nonKeyRelatedPut(pQuery, consistency);
- } else {
- pQuery = new PreparedQueryObject();
- pQuery.appendQueryString("delete from admin.keyspace_master where uuid = ?");
- pQuery.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
- MusicCore.nonKeyRelatedPut(pQuery, consistency);
- }
-
- PreparedQueryObject queryObject = new PreparedQueryObject();
- queryObject.appendQueryString("DROP KEYSPACE " + keyspaceName + ";");
- ResultType result = MusicCore.nonKeyRelatedPut(queryObject, consistency);
- if ( result.equals(ResultType.FAILURE) ) {
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(result).setError("Error Deleteing Keyspace " + keyspaceName).toMap()).build();
- }
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setMessage("Keyspace " + keyspaceName + " Deleted").toMap()).build();
- }
-
- /**
- *
- * @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)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- //public Map<String, Object> createTable(
- 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 = true) @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 = "Keyspace Name",required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name",required = true) @PathParam("tablename") String tablename) throws Exception {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
- aid, "createTable");
- if (authMap.containsKey("aid"))
- authMap.remove("aid");
- if (!authMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build();
- }
- String consistency = MusicUtil.EVENTUAL;
- // for now this needs only eventual consistency
-
- String primaryKey = null;
- String partitionKey = tableObj.getPartitionKey();
- String clusterKey = tableObj.getClusteringKey();
- String filteringKey = tableObj.getFilteringKey();
- if(filteringKey != null) {
- clusterKey = clusterKey + "," + filteringKey;
- }
- primaryKey = tableObj.getPrimaryKey(); // get primaryKey if available
-
- PreparedQueryObject queryObject = new PreparedQueryObject();
- // first read the information about the table fields
- Map<String, String> fields = tableObj.getFields();
- StringBuilder fieldsString = new StringBuilder("(vector_ts text,");
- int counter = 0;
- for (Map.Entry<String, String> entry : fields.entrySet()) {
- if (entry.getKey().equals("PRIMARY KEY")) {
- primaryKey = entry.getValue(); // replaces 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) ) {
-
- //logger.info("cjc2 field="+entry.getValue()+"counter=" + counter+"fieldsize-1="+(fields.size() -1) + ",");
- counter = counter + 1;
- } else {
- //logger.info("cjc3 field="+entry.getValue()+"counter=" + counter+"fieldsize="+fields.size() + ",");
- if((primaryKey != null) && (partitionKey == null)) {
- 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("Create Table 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("[\\(]+","");
- 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.trim();
- clusterKey= primaryKey.substring(primaryKey.indexOf(')'));
- clusterKey=clusterKey.replaceAll("[\\(]+","");
- clusterKey=clusterKey.replaceAll("[\\)]+","");
- clusterKey.trim();
- if (clusterKey.indexOf(",") == 0) clusterKey=clusterKey.substring(1);
- 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();
-
- }
-
- if (partitionKey.isEmpty() ) primaryKey="";
- else if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey + ")";
- else primaryKey=" (" + partitionKey + ")," + clusterKey;
-
- //if (primaryKey != null) fieldsString.append("" + entry.getKey() + " (" + primaryKey + " )");
- if (primaryKey != null) fieldsString.append(", PRIMARY KEY (" + primaryKey + " )");
-
- } // end of length > 0
- else {
- 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();
- }
-
- if (partitionKey.isEmpty() ) primaryKey="";
- else if (clusterKey.isEmpty() ) primaryKey=" (" + partitionKey + ")";
- else primaryKey=" (" + partitionKey + ")," + clusterKey;
-
- //if (primaryKey != null) fieldsString.append("" + entry.getKey() + " (" + primaryKey + " )");
- 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<String, Object> propertiesMap = tableObj.getProperties();
- StringBuilder propertiesString = new StringBuilder();
- if (propertiesMap != null) {
- counter = 0;
- for (Map.Entry<String, Object> entry : propertiesMap.entrySet()) {
- Object ot = entry.getValue();
- String value = ot + "";
- if (ot instanceof String) {
- value = "'" + value + "'";
- } else if (ot instanceof Map) {
- @SuppressWarnings("unchecked")
- Map<String, Object> otMap = (Map<String, Object>) ot;
- value = "{" + MusicUtil.jsonMaptoSqlString(otMap, ",") + "}";
- }
-
- propertiesString.append(entry.getKey() + "=" + value + "");
- if (counter != propertiesMap.size() - 1)
- propertiesString.append(" AND ");
-
- counter = counter + 1;
- }
- }
-
- String clusteringOrder = tableObj.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 {
- //logger.error("createTable/Clustering Order vlaue ERROR: valid clustering order is ASC or DESC or expecting colname order; please correct clusteringOrder:\"+ clusteringOrder+\".\"", " valid clustering order is ASC or DESC; please correct clusteringOrder:"+ clusteringOrder+".");
- // logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA,
- // ErrorSeverity.CRITICAL, ErrorTypes.DATAERROR);
- 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();
- }
- // 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 " + keyspace + "." + tablename + " " + fieldsString);
-
-
- if (propertiesString != null && propertiesString.length()>0 )
- queryObject.appendQueryString(" WITH " + propertiesString);
- queryObject.appendQueryString(";");
- ResultType result = ResultType.FAILURE;
- try {
- //logger.info("cjc query="+queryObject.getQuery());
- result = MusicCore.nonKeyRelatedPut(queryObject, consistency);
- } 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 + " Created under keyspace " + keyspace).toMap()).build();
- }
-
- /**
- *
- * @param keyspace
- * @param tablename
- * @param fieldName
- * @param info
- * @throws Exception
- */
- @POST
- @Path("/{keyspace}/tables/{tablename}/index/{field}")
- @ApiOperation(value = "Create Index", response = String.class)
- @Produces(MediaType.APPLICATION_JSON)
- 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 = true) @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 = "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 {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,aid, "createIndex");
- if (authMap.containsKey("aid"))
- authMap.remove("aid");
- if (!authMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
- response.status(Status.UNAUTHORIZED);
- return response.entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build();
- }
- MultivaluedMap<String, String> rowParams = info.getQueryParameters();
- String indexName = "";
- if (rowParams.getFirst("index_name") != null)
- indexName = rowParams.getFirst("index_name");
- PreparedQueryObject query = new PreparedQueryObject();
- query.appendQueryString("Create index if not exists " + indexName + " on " + keyspace + "."
- + tablename + " (" + fieldName + ");");
-
- ResultType result = ResultType.FAILURE;
- try {
- result = MusicCore.nonKeyRelatedPut(query, "eventual");
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- 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();
- }
- }
-
- /**
- *
- * @param insObj
- * @param keyspace
- * @param tablename
- * @return
- * @throws Exception
- */
- @POST
- @Path("/{keyspace}/tables/{tablename}/rows")
- @ApiOperation(value = "Insert Into Table", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- 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 = true) @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 = "Keyspace Name",
- required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name",
- required = true) @PathParam("tablename") String tablename) {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- Map<String, Object> authMap = null;
-
- try {
- authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
- aid, "insertIntoTable");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
- }
- if (authMap.containsKey("aid"))
- authMap.remove("aid");
- if (!authMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build();
- }
-
- Map<String, Object> valuesMap = insObj.getValues();
- PreparedQueryObject queryObject = new PreparedQueryObject();
- TableMetadata tableInfo = null;
- try {
- tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename);
- if(tableInfo == null) {
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Table name doesn't exists. Please check the table name.").toMap()).build();
- }
- } catch (MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
- }
- 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);
- int counter = 0;
- String primaryKey = "";
- Map<String, byte[]> objectMap = insObj.getObjectMap();
- for (Map.Entry<String, Object> 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);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Invalid column name : "+entry.getKey()).toMap()).build();
- }
-
- Object formattedValue = null;
- try {
- formattedValue = MusicUtil.convertToActualDataType(colType, valueObj);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
- }
- valueString.append("?");
-
- queryObject.addValue(formattedValue);
-
- if (counter == valuesMap.size() - 1) {
- fieldsString.append(")");
- valueString.append(")");
- } else {
- fieldsString.append(",");
- valueString.append(",");
- }
- counter = counter + 1;
- }
-
- //blobs..
- if(objectMap != null) {
- for (Map.Entry<String, byte[]> 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;
- /*if (counter == valuesMap.size() - 1) {
- fieldsString.append(")");
- valueString.append(")");
- } else {*/
- fieldsString.append(",");
- valueString.append(",");
- //}
- } }
-
- if(primaryKey == null || primaryKey.length() <= 0) {
- logger.error(EELFLoggerDelegate.errorLogger, "Some required partition key parts are missing: "+primaryKeyName );
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.SYNTAXERROR).setError("Some required partition key parts are missing: "+primaryKeyName).toMap()).build();
- }
-
- fieldsString.replace(fieldsString.length()-1, fieldsString.length(), ")");
- valueString.replace(valueString.length()-1, valueString.length(), ")");
-
- queryObject.appendQueryString("INSERT INTO " + keyspace + "." + tablename + " "
- + fieldsString + " VALUES " + valueString);
-
- String ttl = insObj.getTtl();
- String timestamp = insObj.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(";");
-
- ReturnType result = null;
- String consistency = insObj.getConsistencyInfo().get("type");
- try {
- if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL)) {
- result = MusicCore.eventualPut(queryObject);
- } else 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.criticalPut(keyspace, tablename, primaryKey, queryObject, lockId,null);
- } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
- result = MusicCore.atomicPut(keyspace, tablename, primaryKey, queryObject, null);
-
- }
- else if (consistency.equalsIgnoreCase(MusicUtil.ATOMICDELETELOCK)) {
- result = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, primaryKey, queryObject, null);
-
- }
- } catch (Exception ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.MUSICSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
- }
-
- if (result==null) {
- logger.error(EELFLoggerDelegate.errorLogger,"", 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();
- }
- return response.status(Status.OK).entity(new JsonResponse(result.getResult()).setMessage("Insert Successful").toMap()).build();
- }
-
- /**
- *
- * @param insObj
- * @param keyspace
- * @param tablename
- * @param info
- * @return
- * @throws Exception
- */
- @PUT
- @Path("/{keyspace}/tables/{tablename}/rows")
- @ApiOperation(value = "Update Table", response = String.class)
- @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 = true) @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 = "Keyspace Name",
- required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name",
- required = true) @PathParam("tablename") String tablename,
- @Context UriInfo info) {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- Map<String, Object> authMap;
- try {
- authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
- aid, "updateTable");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
- }
- if (authMap.containsKey("aid"))
- authMap.remove("aid");
- if (!authMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build();
- }
- long startTime = System.currentTimeMillis();
- String operationId = UUID.randomUUID().toString();// just for infoging
- // purposes.
- String consistency = updateObj.getConsistencyInfo().get("type");
- logger.info(EELFLoggerDelegate.applicationLogger, "--------------Music " + consistency
- + " update-" + operationId + "-------------------------");
- // obtain the field value pairs of the update
-
- PreparedQueryObject queryObject = new PreparedQueryObject();
- Map<String, Object> valuesMap = updateObj.getValues();
-
- TableMetadata tableInfo;
- try {
- tableInfo = MusicCore.returnColumnMetadata(keyspace, tablename);
- } catch (MusicServiceException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
- }
- if (tableInfo == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"", 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= "
- + keyspace + "." + tablename).toMap()).build();
- }
- String vectorTs =
- String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
- StringBuilder fieldValueString = new StringBuilder("vector_ts=?,");
- queryObject.addValue(vectorTs);
- int counter = 0;
- for (Map.Entry<String, Object> entry : valuesMap.entrySet()) {
- Object valueObj = entry.getValue();
- DataType colType = null;
- try {
- colType = tableInfo.getColumn(entry.getKey()).getType();
- } catch(NullPointerException ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "Invalid column name : "+entry.getKey());
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Invalid column name : "+entry.getKey()).toMap()).build();
- }
- Object valueString = null;
- try {
- valueString = MusicUtil.convertToActualDataType(colType, valueObj);
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage());
- }
- fieldValueString.append(entry.getKey() + "= ?");
- queryObject.addValue(valueString);
- if (counter != valuesMap.size() - 1)
- fieldValueString.append(",");
- counter = counter + 1;
- }
- String ttl = updateObj.getTtl();
- String timestamp = updateObj.getTimestamp();
-
- queryObject.appendQueryString("UPDATE " + keyspace + "." + tablename + " ");
- 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(keyspace, tablename, info.getQueryParameters(), queryObject);
- 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();
- }
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
- }
-
- queryObject.appendQueryString(
- " SET " + fieldValueString + " WHERE " + rowId.rowIdString + ";");
-
- // get the conditional, if any
- Condition conditionInfo;
- if (updateObj.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 " + keyspace + "." + tablename + " WHERE "
- + rowId.rowIdString + ";");
- selectQuery.addValue(rowId.primarKeyValue);
- conditionInfo = new MusicCore.Condition(updateObj.getConditions(), selectQuery);
- }
-
- ReturnType operationResult = null;
- long jsonParseCompletionTime = System.currentTimeMillis();
-
- if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL))
- operationResult = MusicCore.eventualPut(queryObject);
- else 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.criticalPut(keyspace, tablename, rowId.primarKeyValue,
- queryObject, lockId, conditionInfo);
- } else if (consistency.equalsIgnoreCase("atomic_delete_lock")) {
- // this function is mainly for the benchmarks
- try {
- operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename,
- rowId.primarKeyValue, queryObject, conditionInfo);
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
- }
- } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
- try {
- operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue,
- queryObject, conditionInfo);
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
- }
- }
- long actualUpdateCompletionTime = System.currentTimeMillis();
-
- long endTime = 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();
- }
-
- }
-
- /**
- *
- * @param delObj
- * @param keyspace
- * @param tablename
- * @param info
- * @return
- * @throws Exception
- */
- @DELETE
- @Path("/{keyspace}/tables/{tablename}/rows")
- @ApiOperation(value = "Delete From table", response = String.class)
- @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 = true) @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 = "Keyspace Name",
- required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name",
- required = true) @PathParam("tablename") String tablename,
- @Context UriInfo info) {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- Map<String, Object> authMap = null;
- try {
- authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,
- aid, "deleteFromTable");
- } catch (Exception e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(e.getMessage()).toMap()).build();
- }
- if (authMap.containsKey("aid"))
- authMap.remove("aid");
- if (!authMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build();
- }
- if(delObj == null) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGDATA ,ErrorSeverity.WARN, ErrorTypes.DATAERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Required HTTP Request body is missing.").toMap()).build();
- }
- PreparedQueryObject queryObject = new PreparedQueryObject();
- StringBuilder columnString = new StringBuilder();
-
- int counter = 0;
- ArrayList<String> columnList = delObj.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(keyspace, tablename, info.getQueryParameters(), queryObject);
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
- }
- String rowSpec = rowId.rowIdString.toString();
-
- if ((columnList != null) && (!rowSpec.isEmpty())) {
- queryObject.appendQueryString("DELETE " + columnString + " FROM " + keyspace + "."
- + tablename + " WHERE " + rowSpec + ";");
- }
-
- if ((columnList == null) && (!rowSpec.isEmpty())) {
- queryObject.appendQueryString("DELETE FROM " + keyspace + "." + tablename + " WHERE "
- + rowSpec + ";");
- }
-
- if ((columnList != null) && (rowSpec.isEmpty())) {
- queryObject.appendQueryString(
- "DELETE " + columnString + " FROM " + keyspace + "." + rowSpec + ";");
- }
- // get the conditional, if any
- Condition conditionInfo;
- if (delObj.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 " + keyspace + "." + tablename + " WHERE "
- + rowId.rowIdString + ";");
- selectQuery.addValue(rowId.primarKeyValue);
- conditionInfo = new MusicCore.Condition(delObj.getConditions(), selectQuery);
- }
-
- String consistency = delObj.getConsistencyInfo().get("type");
-
- ReturnType operationResult = null;
- try {
- if (consistency.equalsIgnoreCase(MusicUtil.EVENTUAL))
- operationResult = MusicCore.eventualPut(queryObject);
- else 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.criticalPut(keyspace, tablename, rowId.primarKeyValue,
- queryObject, lockId, conditionInfo);
- } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
- operationResult = MusicCore.atomicPut(keyspace, tablename, rowId.primarKeyValue,
- queryObject, conditionInfo);
- }
- else if (consistency.equalsIgnoreCase(MusicUtil.ATOMICDELETELOCK)) {
- operationResult = MusicCore.atomicPutWithDeleteLock(keyspace, tablename, rowId.primarKeyValue,
- queryObject, conditionInfo);
- }
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- 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,"", 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,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(operationResult.getMessage()).toMap()).build();
- }
- }
-
- /**
- *
- * @param tabObj
- * @param keyspace
- * @param tablename
- * @throws Exception
- */
- @DELETE
- @Path("/{keyspace}/tables/{tablename}")
- @ApiOperation(value = "Drop Table", response = String.class)
- @Produces(MediaType.APPLICATION_JSON)
- 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 = true) @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 = "Keyspace Name",
- required = true) @PathParam("keyspace") String keyspace,
- @ApiParam(value = "Table Name",
- required = true) @PathParam("tablename") String tablename) throws Exception {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- Map<String, Object> authMap =
- MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "dropTable");
- if (authMap.containsKey("aid"))
- authMap.remove("aid");
- if (!authMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build();
- }
- String consistency = "eventual";// for now this needs only eventual
- // consistency
- PreparedQueryObject query = new PreparedQueryObject();
- query.appendQueryString("DROP TABLE " + keyspace + "." + tablename + ";");
- try {
- return response.status(Status.OK).entity(new JsonResponse(MusicCore.nonKeyRelatedPut(query, consistency)).toMap()).build();
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
- }
-
- }
-
- /**
- *
- * @param selObj
- * @param keyspace
- * @param tablename
- * @param info
- * @return
- */
- @PUT
- @Path("/{keyspace}/tables/{tablename}/rows/criticalget")
- @ApiOperation(value = "Select Critical", response = Map.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response selectCritical(
- @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(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 {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- Map<String, Object> authMap = MusicCore.autheticateUser(ns, userId, password, keyspace,aid, "selectCritical");
- if (authMap.containsKey("aid"))
- authMap.remove("aid");
- if (!authMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"Error while authentication... ", AppMessages.MISSINGINFO ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build();
- }
- String lockId = selObj.getConsistencyInfo().get("lockId");
-
- PreparedQueryObject queryObject = new PreparedQueryObject();
-
- RowIdentifier rowId = null;
- try {
- rowId = getRowIdentifier(keyspace, tablename, info.getQueryParameters(), queryObject);
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,ex.getMessage(), AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
- }
- queryObject.appendQueryString(
- "SELECT * FROM " + keyspace + "." + tablename + " WHERE " + rowId.rowIdString + ";");
-
- ResultSet results = null;
-
- String consistency = selObj.getConsistencyInfo().get("type");
-
- 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.criticalGet(keyspace, tablename, rowId.primarKeyValue, queryObject,
- lockId);
- } else if (consistency.equalsIgnoreCase(MusicUtil.ATOMIC)) {
- results = MusicCore.atomicGet(keyspace, tablename, rowId.primarKeyValue, queryObject);
- }
-
- else if (consistency.equalsIgnoreCase(MusicUtil.ATOMICDELETELOCK)) {
- results = MusicCore.atomicGetWithDeleteLock(keyspace, tablename, rowId.primarKeyValue, queryObject);
- }
- if(results!=null && results.getAvailableWithoutFetching() >0) {
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).toMap()).build();
- }
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setError("No data found").toMap()).build();
-
-
- }
-
- /**
- *
- * @param keyspace
- * @param tablename
- * @param info
- * @return
- * @throws Exception
- */
- @GET
- @Path("/{keyspace}/tables/{tablename}/rows")
- @ApiOperation(value = "Select All or Select Specific", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response select(
- @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(MusicUtil.AUTHORIZATION) String authorization,
- @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 {
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
-
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- Map<String, Object> authMap =
- MusicCore.autheticateUser(ns, userId, password, keyspace, aid, "select");
- if (authMap.containsKey("aid"))
- authMap.remove("aid");
- if (!authMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.AUTHENTICATIONERROR ,ErrorSeverity.WARN, ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED).entity(new JsonResponse(ResultType.FAILURE).setError(String.valueOf(authMap.get("Error"))).toMap()).build();
- }
- PreparedQueryObject queryObject = new PreparedQueryObject();
-
- if (info.getQueryParameters().isEmpty())// select all
- queryObject.appendQueryString("SELECT * FROM " + keyspace + "." + tablename + ";");
- else {
- int limit = -1; // do not limit the number of results
- try {
- queryObject = selectSpecificQuery(VERSION, minorVersion, patchVersion, aid, ns,
- userId, password, keyspace, tablename, info, limit);
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
- }
- }
-
- try {
- ResultSet results = MusicCore.get(queryObject);
- if(results.getAvailableWithoutFetching() >0) {
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).toMap()).build();
- }
- return response.status(Status.OK).entity(new JsonResponse(ResultType.SUCCESS).setDataResult(MusicCore.marshallResults(results)).setError("No data found").toMap()).build();
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError(ex.getMessage()).toMap()).build();
- }
-
- }
-
- /**
- *
- * @param keyspace
- * @param tablename
- * @param info
- * @param limit
- * @return
- * @throws MusicServiceException
- */
- public PreparedQueryObject selectSpecificQuery(String version, String minorVersion,
- String patchVersion, String aid, String ns, String userId, String password,
- 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<String, String> rowParams, PreparedQueryObject queryObject)
- throws MusicServiceException {
- StringBuilder rowSpec = new StringBuilder();
- int counter = 0;
- TableMetadata tableInfo = MusicCore.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<String, List<String>> entry : rowParams.entrySet()) {
- String keyName = entry.getKey();
- List<String> 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.getMessage());
- }
- 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 895f0abf..00000000
--- a/src/main/java/org/onap/music/rest/RestMusicHealthCheckAPI.java
+++ /dev/null
@@ -1,120 +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;
-/**
- * @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.Consumes;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.Response.ResponseBuilder;
-import javax.ws.rs.core.Response.Status;
-
-
-import org.onap.music.response.jsonobjects.JsonResponse;
-import org.onap.music.eelf.healthcheck.MusicHealthCheck;
-import org.onap.music.eelf.logging.EELFLoggerDelegate;
-import org.onap.music.main.MusicUtil;
-import org.onap.music.main.ResultType;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import com.datastax.driver.core.ConsistencyLevel;
-
-import io.swagger.annotations.Api;
-import io.swagger.annotations.ApiOperation;
-import io.swagger.annotations.ApiParam;
-
-
-
-
-@Path("/v{version: [0-9]+}/service")
-@Api(value="Healthcheck Api")
-public class RestMusicHealthCheckAPI {
-
-
- private static EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(MusicUtil.class);
-
-
- @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<String, Object> resultMap = new HashMap<>();
- if(ConsistencyLevel.valueOf(consistency) == null) {
- resultMap.put("INVALID", "Consistency level is invalid...");
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- MusicHealthCheck cassHealthCheck = new MusicHealthCheck();
- String status = cassHealthCheck.getCassandraStatus(consistency);
- if(status.equals("ACTIVE")) {
- resultMap.put("ACTIVE", "Cassandra Running and Listening to requests");
- return Response.status(Status.OK).entity(resultMap).build();
- } else {
- resultMap.put("INACTIVE", "One or more nodes in the Cluster is/are down or not responding.");
- return Response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
-
-
-
- }
-
- @GET
- @Path("/pingZookeeper")
- @ApiOperation(value = "Get Health Status", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response ZKStatus(@Context HttpServletResponse response) {
- logger.info(EELFLoggerDelegate.applicationLogger,"Replying to request for MUSIC Health Check status for Zookeeper");
- Map<String, Object> resultMap = new HashMap<>();
- MusicHealthCheck ZKHealthCheck = new MusicHealthCheck();
- String status = ZKHealthCheck.getZookeeperStatus();
- if(status.equals("ACTIVE")) {
- resultMap.put("ACTIVE", "Zookeeper is Active and Running");
- return Response.status(Status.OK).entity(resultMap).build();
- }else {
- resultMap.put("INACTIVE", "Zookeeper is not responding");
- return Response.status(Status.BAD_REQUEST).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 70583baa..00000000
--- a/src/main/java/org/onap/music/rest/RestMusicLocksAPI.java
+++ /dev/null
@@ -1,424 +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.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.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.lockingservice.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;
-
-
-@Path("/v2/locks/")
-@Api(value="Lock 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 in zookeeper if it did not already exist
- *
- * @param lockName
- * @return
- * @throws Exception
- */
- @POST
- @Path("/create/{lockname}")
- @ApiOperation(value = "Create Lock",
- notes = "Puts the requesting process in the q for this lock." +
- " The corresponding node will be created in zookeeper if it did not already exist." +
- " Lock Name is the \"key\" of the form keyspaceName.tableName.rowId",
- response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- 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 = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam("ns") String ns) throws Exception{
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- Map<String, Object> resultMap = MusicCore.validateLock(lockName);
- if (resultMap.containsKey("Exception")) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- String keyspaceName = (String) resultMap.get("keyspace");
- resultMap.remove("keyspace");
- resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
- "createLockReference");
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.MISSINGINFO ,ErrorSeverity.CRITICAL, ErrorTypes.AUTHENTICATIONERROR);
- return response.status(Status.UNAUTHORIZED).entity(resultMap).build();
- }
- ResultType status = ResultType.SUCCESS;
- String lockId = MusicCore.createLockReference(lockName);
-
- if (lockId == null) {
- status = ResultType.FAILURE;
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.LOCKINGERROR ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(status).setError("Lock Id is null").toMap()).build();
- }
- return response.status(Status.OK).entity(new JsonResponse(status).setLock(lockId).toMap()).build();
- }
-
- /**
- *
- * Checks if the node is in the top of the queue and hence acquires the lock
- *
- * @param lockId
- * @return
- * @throws Exception
- */
- @GET
- @Path("/acquire/{lockreference}")
- @ApiOperation(value = "Aquire Lock",
- notes = "Checks if the node is in the top of the queue and hence acquires the lock",
- response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- public Response accquireLock(
- @ApiParam(value="Lock Reference",required=true) @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 = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam("ns") String ns) throws Exception{
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- Map<String, Object> resultMap = MusicCore.validateLock(lockId);
- if (resultMap.containsKey("Exception")) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- String keyspaceName = (String) resultMap.get("keyspace");
- resultMap.remove("keyspace");
- resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
- "accquireLock");
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- 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);
- return response.status(Status.BAD_REQUEST).entity(new JsonResponse(ResultType.FAILURE).setError("Unable to aquire lock").toMap()).build();
- }
- }
-
-
-
-
- @POST
- @Path("/acquire-with-lease/{lockreference}")
- @ApiOperation(value = "Aquire Lock with Lease", response = Map.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
- public Response accquireLockWithLease(JsonLeasedLock lockObj,
- @ApiParam(value="Lock Reference",required=true) @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 = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam("ns") String ns) throws Exception{
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- Map<String, Object> resultMap = MusicCore.validateLock(lockId);
- if (resultMap.containsKey("Exception")) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- String keyspaceName = (String) resultMap.get("keyspace");
- resultMap.remove("keyspace");
- resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
- "accquireLockWithLease");
-
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- 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();
- }
-
-
- @GET
- @Path("/enquire/{lockname}")
- @ApiOperation(value = "Get Lock Holder",
- notes = "Gets the current Lock Holder",
- response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- 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 = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam("ns") String ns) throws Exception{
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- Map<String, Object> resultMap = MusicCore.validateLock(lockName);
- if (resultMap.containsKey("Exception")) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- String keyspaceName = (String) resultMap.get("keyspace");
- resultMap.remove("keyspace");
- resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
- "currentLockHolder");
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- 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();
- }
-
- @GET
- @Path("/{lockname}")
- @ApiOperation(value = "Lock State",
- notes = "Returns current Lock State and Holder.",
- response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- 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 = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam("ns") String ns,
- @ApiParam(value = "userId",
- required = true) @HeaderParam("userId") String userId,
- @ApiParam(value = "Password",
- required = true) @HeaderParam("password") String password) throws Exception{
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- Map<String, Object> resultMap = MusicCore.validateLock(lockName);
- if (resultMap.containsKey("Exception")) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- String keyspaceName = (String) resultMap.get("keyspace");
- resultMap.remove("keyspace");
- resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
- "currentLockState");
-
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
-
- MusicLockState mls = MusicCore.getMusicLockState(lockName);
- Map<String,Object> returnMap = null;
- JsonResponse jsonResponse = new JsonResponse(ResultType.FAILURE).setLock(lockName);
- if(mls == null) {
- jsonResponse.setError("");
- jsonResponse.setMessage("No lock object created yet..");
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(jsonResponse.toMap()).build();
- } else {
- jsonResponse.setStatus(ResultType.SUCCESS);
- jsonResponse.setLockStatus(mls.getLockStatus());
- jsonResponse.setLockHolder(mls.getLockHolder());
- return response.status(Status.OK).entity(jsonResponse.toMap()).build();
- }
- }
-
- /**
- *
- * deletes the process from the zk queue
- *
- * @param lockId
- * @throws Exception
- */
- @DELETE
- @Path("/release/{lockreference}")
- @ApiOperation(value = "Release Lock",
- notes = "deletes the process from the zk queue",
- response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- 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 = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam("ns") String ns) throws Exception{
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- Map<String, Object> resultMap = MusicCore.validateLock(lockId);
- if (resultMap.containsKey("Exception")) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- String keyspaceName = (String) resultMap.get("keyspace");
- resultMap.remove("keyspace");
- resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
- "unLock");
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.INCORRECTDATA ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- 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<String,Object> 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();
- }
-
- /**
- *
- * @param lockName
- * @throws Exception
- */
- @DELETE
- @Path("/delete/{lockname}")
- @ApiOperation(value = "Delete Lock", response = Map.class)
- @Produces(MediaType.APPLICATION_JSON)
- 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 = true) @HeaderParam("aid") String aid,
- @ApiParam(value = "Authorization", required = true) @HeaderParam(MusicUtil.AUTHORIZATION) String authorization,
- @ApiParam(value = "Application namespace",
- required = true) @HeaderParam("ns") String ns) throws Exception{
- ResponseBuilder response = MusicUtil.buildVersionResponse(VERSION, minorVersion, patchVersion);
- Map<String, Object> resultMap = MusicCore.validateLock(lockName);
- if (resultMap.containsKey("Exception")) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- Map<String,String> userCredentials = MusicUtil.extractBasicAuthentication(authorization);
- String userId = userCredentials.get(MusicUtil.USERID);
- String password = userCredentials.get(MusicUtil.PASSWORD);
- String keyspaceName = (String) resultMap.get("keyspace");
- resultMap.remove("keyspace");
- resultMap = MusicCore.autheticateUser(ns, userId, password, keyspaceName, aid,
- "deleteLock");
- if (resultMap.containsKey("aid"))
- resultMap.remove("aid");
- if (!resultMap.isEmpty()) {
- logger.error(EELFLoggerDelegate.errorLogger,"", AppMessages.UNKNOWNERROR ,ErrorSeverity.CRITICAL, ErrorTypes.GENERALSERVICEERROR);
- return response.status(Status.BAD_REQUEST).entity(resultMap).build();
- }
- try{
- MusicCore.deleteLock(lockName);
- }catch (Exception 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();
- }
-
-}
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 1f6ec24f..00000000
--- a/src/main/java/org/onap/music/rest/RestMusicQAPI.java
+++ /dev/null
@@ -1,492 +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.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.PreparedQueryObject;
-import com.datastax.driver.core.ResultSet;
-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("/v{version: [0-9]+}/priorityq/")
-@Path("{version}/priorityq/")
-@Api(value = "Q Api")
-public class RestMusicQAPI {
-
- private EELFLoggerDelegate logger = EELFLoggerDelegate.getLogger(RestMusicQAPI.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 USERID = "userId"; private static final String PASSWORD = "password";
- * */
- // private static final String VERSION = "v2";
-
-
- /**
- *
- * @param tableObj
- * @param keyspace
- * @param tablename
- * @throws Exception
- */
-
- @POST
- @Path("/keyspaces/{keyspace}/{qname}") // is it same as tablename?down
- @ApiOperation(value = "Create Q", response = String.class)
- @Consumes(MediaType.APPLICATION_JSON)
- @Produces(MediaType.APPLICATION_JSON)
-
- /* old
- @POST
- @Path("/keyspaces/{keyspace}/{qname}")
- @ApiOperation(value = "", response = Void.class)
- @Consumes(MediaType.APPLICATION_JSON)
- */
- public Response createQ(
- // public Map<String,Object> 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 = true) @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<String, String> 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.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.trim();
- clusteringKey= primaryKey.substring(primaryKey.indexOf(')'));
- clusteringKey=clusteringKey.replaceAll("[\\(]+","");
- clusteringKey=clusteringKey.replaceAll("[\\)]+","");
- clusteringKey.trim();
- if (clusteringKey.indexOf(",") == 0) {
- clusteringKey=clusteringKey.substring(1);
- }
- clusteringKey.trim();
- if (",".equals(clusteringKey) ) {
- 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<String, Object> 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 = true) @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)
- throws Exception {
-
- // check valuesMap.isEmpty and proceed
- // response.addHeader(xLatestVersion, MusicUtil.getVersion());
- 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 = true) @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) {
-
- //logger.info(EELFLoggerDelegate.errorLogger, "", AppMessages.MISSINGDATA, ErrorSeverity.CRITICAL,
- 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 = true) @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 = "userId", required = true) @HeaderParam("userId") String userId,
- // @ApiParam(value = "Password", required = true) @HeaderParam("password") String password,
- 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) {
- // 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<String, HashMap<String, Object>> 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 = true) @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 {
- int limit =1; //peek must return just the top row
- Map<String ,String> 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(version, minorVersion,
- patchVersion, aid, ns, userId, password, keyspace, tablename, info, limit);
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "MusicServiceException occured in peek"+ ex);
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR,
- ErrorSeverity.WARN, ErrorTypes.GENERALSERVICEERROR);
- 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(MusicCore.marshallResults(results)).toMap()).build();
- } catch (MusicServiceException ex) {
- logger.error(EELFLoggerDelegate.errorLogger, "MusicServiceException occured in peek"+ ex);
- logger.error(EELFLoggerDelegate.errorLogger, "", AppMessages.UNKNOWNERROR,
- ErrorSeverity.ERROR, ErrorTypes.MUSICSERVICEERROR);
- 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<String, HashMap<String, Object>> 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 = true) @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 = "userId", required = true) @HeaderParam("userId") String userId,
- //@ApiParam(value = "Password", required = true) @HeaderParam("password") String password,
- @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 {
- /*
- * PreparedQueryObject query = new RestMusicDataAPI().selectSpecificQuery(version, minorVersion,
- * patchVersion, aid, ns, userId, password, keyspace, tablename, info, limit); ResultSet results
- */
- /* Map<String ,String> auth = new HashMap<>();
- String userId =auth.get(MusicUtil.USERID);
- String password =auth.get(MusicUtil.PASSWORD);
- */
- return new RestMusicDataAPI().select(version, minorVersion, patchVersion, aid, ns, authorization, 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 = true) @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 = "userId", required = true) @HeaderParam("userId") String userId,
- //@ApiParam(value = "Password", required = true) @HeaderParam("password") String password,
- // cjc JsonTable tabObj,
- @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/test/java/org/onap/music/unittests/MusicUtilTest.java b/src/test/java/org/onap/music/unittests/MusicUtilTest.java
deleted file mode 100644
index b117c330..00000000
--- a/src/test/java/org/onap/music/unittests/MusicUtilTest.java
+++ /dev/null
@@ -1,207 +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 java.math.BigInteger;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-import java.util.UUID;
-import org.apache.cassandra.exceptions.PreparedQueryNotFoundException;
-import org.junit.Test;
-import org.onap.music.datastore.PreparedQueryObject;
-import org.onap.music.exceptions.MusicServiceException;
-import org.onap.music.main.MusicUtil;
-import com.datastax.driver.core.DataType;
-import javassist.CodeConverter.ArrayAccessReplacementMethodNames;
-
-public class MusicUtilTest {
-
- @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 testGetAafEndpointUrl() {
- MusicUtil.setAafEndpointUrl("url");
- assertEquals(MusicUtil.getAafEndpointUrl(),"url");
- }
-
- @Test
- public void testGetMyId() {
- MusicUtil.setMyId(1);
- assertEquals(MusicUtil.getMyId(),1);
- }
-
- @Test
- public void testGetAllIds() {
- List<String> ids = new ArrayList<String>();
- ids.add("1");
- ids.add("2");
- ids.add("3");
- MusicUtil.setAllIds(ids);
- assertEquals(MusicUtil.getAllIds().get(0),"1");
- }
-
-// @Test
-// public void testGetPublicIp() {
-// MusicUtil.setPublicIp("10.0.0.1");
-// assertEquals(MusicUtil.getPublicIp(),"10.0.0.1");
-// }
-
- @Test
- public void testGetAllPublicIps() {
- List<String> ips = new ArrayList<String>();
- ips.add("10.0.0.1");
- ips.add("10.0.0.2");
- ips.add("10.0.0.3");
- MusicUtil.setAllPublicIps(ips);
- assertEquals(MusicUtil.getAllPublicIps().get(1),"10.0.0.2");
- }
-
- @Test
- public void testGetPropkeys() {
- assertEquals(MusicUtil.getPropkeys()[2],"music.ip");
- }
-
- @Test
- public void testGetMusicRestIp() {
- MusicUtil.setMusicRestIp("localhost");
- assertEquals(MusicUtil.getMusicRestIp(),"localhost");
- }
-
- @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 testGetMyZkHost() {
- MusicUtil.setMyZkHost("10.0.0.2");
- assertEquals(MusicUtil.getMyZkHost(),"10.0.0.2");
- }*/
-
- @Test
- public void testGetMyCassaHost() {
- MusicUtil.setMyCassaHost("10.0.0.2");
- assertEquals(MusicUtil.getMyCassaHost(),"10.0.0.2");
- }
-
- @Test
- public void testGetDefaultMusicIp() {
- MusicUtil.setDefaultMusicIp("10.0.0.2");
- assertEquals(MusicUtil.getDefaultMusicIp(),"10.0.0.2");
- }
-
-// @Test
-// public void testGetTestType() {
-// fail("Not yet implemented"); // TODO
-// }
-
- @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
- public void testConvertToCQLDataType() throws Exception {
- Map<String,Object> myMap = new HashMap<String,Object>();
- 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"));
- Map<String,Object> myMap = new HashMap<String,Object>();
- myMap.put("name","tom");
- assertEquals(MusicUtil.convertToActualDataType(DataType.map(DataType.varchar(),DataType.varchar()),myMap),myMap);
-
- }
-
- @Test
- public void testJsonMaptoSqlString() throws Exception {
- Map<String,Object> myMap = new HashMap<>();
- myMap.put("name","tom");
- myMap.put("value",5);
- String result = MusicUtil.jsonMaptoSqlString(myMap,",");
- assertTrue(result.contains("name"));
- assertTrue(result.contains("value"));
- }
-
-}
diff --git a/src/test/java/org/onap/music/unittests/TestLockStore.java b/src/test/java/org/onap/music/unittests/TestLockStore.java
deleted file mode 100644
index 4dbc7b4f..00000000
--- a/src/test/java/org/onap/music/unittests/TestLockStore.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.unittests;
-
-import org.apache.log4j.Logger;
-import org.onap.music.lockingservice.MusicLockingService;
-
-public class TestLockStore {
- final static Logger logger = Logger.getLogger(TestLockStore.class);
-
- public static void main(String[] args) throws Exception {
- String lockName = "/achristmkllas";
- MusicLockingService ml = new MusicLockingService();
- ml.deleteLock(lockName);
-
-
- logger.info("lockname:" + lockName);
-
- String lockId1 = ml.createLockId(lockName);
- logger.info("lockId1 " + lockId1);
- logger.info(ml.isMyTurn(lockId1));
-
- String lockId2 = ml.createLockId(lockName);
- logger.info("lockId2 " + lockId2);
- logger.info("check " + ml.isMyTurn("$bank$x-94608776321630264-0000000000"));
- logger.info(ml.isMyTurn(lockId2));
-
- // zkClient.unlock(lockId1);
- // logger.info(ml.lock(lockId2));
- // zkClient.unlock(lockId2);
- }
-
-
-}
diff --git a/src/test/java/org/onap/music/unittests/TestMusicCore.java b/src/test/java/org/onap/music/unittests/TestMusicCore.java
deleted file mode 100644
index ed9c2f68..00000000
--- a/src/test/java/org/onap/music/unittests/TestMusicCore.java
+++ /dev/null
@@ -1,678 +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 static org.onap.music.main.MusicCore.mDstoreHandle;
-import static org.onap.music.main.MusicCore.mLockHandle;
-import java.util.HashMap;
-import java.util.Map;
-import org.apache.zookeeper.KeeperException.NoNodeException;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.onap.music.exceptions.MusicLockingException;
-import org.onap.music.exceptions.MusicQueryException;
-import org.onap.music.exceptions.MusicServiceException;
-import org.onap.music.lockingservice.MusicLockState;
-import org.onap.music.lockingservice.MusicLockingService;
-import org.onap.music.lockingservice.MusicLockState.LockStatus;
-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.main.MusicCore.Condition;
-import org.onap.music.datastore.MusicDataStore;
-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 com.att.eelf.exception.EELFException;
-import com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.Session;
-
-@RunWith(MockitoJUnitRunner.class)
-public class TestMusicCore {
-
- @Mock
- private Condition condition;
-
- @Mock
- private ResultSet rs;
-
- @Mock
- private PreparedQueryObject preparedQueryObject;
-
- @Mock
- private Session session;
-
- @Before
- public void setUp() {
- mLockHandle = Mockito.mock(MusicLockingService.class);
-
- }
-
- @Test
- public void testCreateLockReferenceforvalidlock() {
- Mockito.when(mLockHandle.createLockId("/" + "test")).thenReturn("lock");
- String lockId = MusicCore.createLockReference("test");
- assertEquals("lock", lockId);
- Mockito.verify(mLockHandle).createLockId("/" + "test");
- }
-
-
- @Test
- public void testCreateLockReferencefornullname() {
- Mockito.when(mLockHandle.createLockId("/" + "test")).thenReturn("lock");
- String lockId = MusicCore.createLockReference("x"); //test");
- //System.out.println("cjc exception lockhandle=" + mLockHandle+"lockid="+lockId );
- assertNotEquals("lock", lockId);
- //Mockito.verify(mLockHandle).createLockId("/" + "test");
- }
-
- @Test
- public void testIsTableOrKeySpaceLock() {
- Boolean result = MusicCore.isTableOrKeySpaceLock("ks1.tn1");
- assertTrue(result);
- }
-
- @Test
- public void testIsTableOrKeySpaceLockwithPrimarykey() {
- Boolean result = MusicCore.isTableOrKeySpaceLock("ks1.tn1.pk1");
- assertFalse(result);
- }
-
- @Test
- public void testGetMusicLockState() throws MusicLockingException {
- MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1");
- Mockito.when(mLockHandle.getLockState("ks1.tb1.pk1")).thenReturn(musicLockState);
- MusicLockState mls = MusicCore.getMusicLockState("ks1.tb1.pk1");
- assertEquals(musicLockState, mls);
- Mockito.verify(mLockHandle).getLockState("ks1.tb1.pk1");
- }
-
- @Test
- public void testAcquireLockifisMyTurnTrue() throws MusicLockingException {
- Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true);
- ReturnType lock = MusicCore.acquireLock("ks1.tn1", "id1");
- assertEquals(lock.getResult(), ResultType.SUCCESS);
- Mockito.verify(mLockHandle).isMyTurn("id1");
- }
-
- @Test
- public void testAcquireLockifisMyTurnFalse() throws MusicLockingException {
- Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false);
- ReturnType lock = MusicCore.acquireLock("ks1.ts1", "id1");
- assertEquals(lock.getResult(), ResultType.FAILURE);
- Mockito.verify(mLockHandle).isMyTurn("id1");
- }
-
- @Test
- public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockTrue() throws MusicLockingException {
- Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true);
- ReturnType lock = MusicCore.acquireLock("ks1.tn1", "id1");
- assertEquals(lock.getResult(), ResultType.SUCCESS);
- Mockito.verify(mLockHandle).isMyTurn("id1");
- }
-
- @Test
- public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockFalseandHaveLock() throws MusicLockingException {
- MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1");
- Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true);
- Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState);
- ReturnType lock = MusicCore.acquireLock("ks1.tn1.pk1", "id1");
- assertEquals(lock.getResult(), ResultType.SUCCESS);
- Mockito.verify(mLockHandle).isMyTurn("id1");
- Mockito.verify(mLockHandle).getLockState("ks1.tn1.pk1");
- }
-
- @Test
- public void testAcquireLockifisMyTurnTrueandIsTableOrKeySpaceLockFalseandDontHaveLock() throws MusicLockingException {
- MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id2");
- Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true);
- Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState);
- ReturnType lock = MusicCore.acquireLock("ks1.tn1.pk1", "id1");
- assertEquals(lock.getResult(), ResultType.SUCCESS);
- Mockito.verify(mLockHandle).isMyTurn("id1");
- Mockito.verify(mLockHandle).getLockState("ks1.tn1.pk1");
- }
-
- @Test
- public void testAcquireLockifLockRefDoesntExist() throws MusicLockingException {
- Mockito.when(mLockHandle.lockIdExists("bs1")).thenReturn(false);
- ReturnType lock = MusicCore.acquireLock("ks1.ts1", "bs1");
- assertEquals(lock.getResult(), ResultType.FAILURE);
- assertEquals(lock.getMessage(), "Lockid doesn't exist");
- Mockito.verify(mLockHandle).lockIdExists("bs1");
- }
-
- @Test
- public void testAcquireLockWithLeasewithLease() throws MusicLockingException {
- MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1");
- musicLockState.setLeasePeriod(0);
- ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes");
- Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState);
- Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true);
- ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000);
- assertEquals(expectedResult.getResult(), actualResult.getResult());
- Mockito.verify(mLockHandle).isMyTurn("id1");
- Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1");
- }
-
- @Test
- public void testAcquireLockWithLeasewithException() throws MusicLockingException {
- ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "failure");
- Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenThrow(new MusicLockingException());
- Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true);
- ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000);
- assertEquals(expectedResult.getResult(), actualResult.getResult());
- Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1");
- }
-
- @Test
- public void testAcquireLockWithLeasewithLockStatusLOCKED() throws MusicLockingException {
- MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1");
- ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes");
- Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState);
- Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true);
- ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000);
- assertEquals(expectedResult.getResult(), actualResult.getResult());
- Mockito.verify(mLockHandle).isMyTurn("id1");
- Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1");
- }
-
- @Test
- public void testAcquireLockWithLeasewithLockStatusUNLOCKED() throws MusicLockingException {
- MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1");
- ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes");
- Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState);
- Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true);
- ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000);
- assertEquals(expectedResult.getResult(), actualResult.getResult());
- Mockito.verify(mLockHandle).isMyTurn("id1");
- Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1");
-
- }
-
- @Test
- public void testAcquireLockWithLeaseIfNotMyTurn() throws MusicLockingException {
- MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1");
- ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure");
- Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState);
- Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false);
- ReturnType actualResult = MusicCore.acquireLockWithLease("ks1.tn1.pk1", "id1", 6000);
- assertEquals(expectedResult.getResult(), actualResult.getResult());
- Mockito.verify(mLockHandle).isMyTurn("id1");
- Mockito.verify(mLockHandle).getLockState("ks1.tn1.pk1");
- }
-
- @Test
- public void testQuorumGet() throws MusicServiceException, MusicQueryException {
- preparedQueryObject = Mockito.mock(PreparedQueryObject.class);
- mDstoreHandle = Mockito.mock(MusicDataStore.class);
- rs = Mockito.mock(ResultSet.class);
- session = Mockito.mock(Session.class);
- Mockito.when(mDstoreHandle.getSession()).thenReturn(session);
- Mockito.when(mDstoreHandle.executeCriticalGet(preparedQueryObject)).thenReturn(rs);
- ResultSet rs1 = MusicCore.quorumGet(preparedQueryObject);
- assertNotNull(rs1);
- }
-
- @Test
- public void testGetLockNameFromId() {
- String lockname = MusicCore.getLockNameFromId("lockName$id");
- assertEquals("lockName", lockname);
- }
-
- @Test
- public void testDestroyLockRef() throws NoNodeException {
- Mockito.doNothing().when(mLockHandle).unlockAndDeleteId("id1");
- MusicCore.destroyLockRef("id1");
- Mockito.verify(mLockHandle, Mockito.atLeastOnce()).unlockAndDeleteId("id1");
- }
-
- @Test
- public void testreleaseLockwithvoluntaryReleaseTrue() throws NoNodeException {
- MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2");
- Mockito.doNothing().when(mLockHandle).unlockAndDeleteId("id1");
- MusicLockState musicLockState1 = MusicCore.releaseLock("id1", true);
- assertEquals(musicLockState.getLockStatus(), musicLockState1.getLockStatus());
- Mockito.verify(mLockHandle, Mockito.atLeastOnce()).unlockAndDeleteId("id1");
- }
-
- @Test
- public void testreleaseLockwithvoluntaryReleaseFalse() throws NoNodeException {
- MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2");
- Mockito.doNothing().when(mLockHandle).unlockAndDeleteId("id1");
- MusicLockState musicLockState1 = MusicCore.releaseLock("id1", false);
- assertEquals(musicLockState.getLockStatus(), musicLockState1.getLockStatus());
- Mockito.verify(mLockHandle, Mockito.atLeastOnce()).unlockAndDeleteId("id1");
- }
-
- @Test
- public void testDeleteLock() throws MusicLockingException {
- Mockito.doNothing().when(mLockHandle).deleteLock("/" + "id1");
- MusicCore.deleteLock("id1");
- Mockito.verify(mLockHandle).deleteLock("/" + "id1");
- }
-
- /*
- * @Test public void testNonKeyRelatedPut() throws Exception { mDstoreHandle =
- * Mockito.mock(MusicDataStore.class); Mockito.when(mDstoreHandle.executePut("qu1",
- * "consistency")).thenReturn(true); Boolean result = MusicCore.nonKeyRelatedPut("qu1",
- * "consistency"); assertTrue(result); Mockito.verify(mDstoreHandle).executePut("qu1",
- * "consistency"); }
- */
-
- @Test
- public void testEventualPutPreparedQuery() throws MusicServiceException, MusicQueryException {
- mDstoreHandle = Mockito.mock(MusicDataStore.class);
- preparedQueryObject = Mockito.mock(PreparedQueryObject.class);
- ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes");
- session = Mockito.mock(Session.class);
- Mockito.when(mDstoreHandle.getSession()).thenReturn(session);
- Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "eventual")).thenReturn(true);
- ReturnType actualResult = MusicCore.eventualPut(preparedQueryObject);
- assertEquals(expectedResult.getResult(), actualResult.getResult());
- Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "eventual");
- }
-
- @Test
- public void testEventualPutPreparedQuerywithResultFalse()
- throws MusicServiceException, MusicQueryException {
- mDstoreHandle = Mockito.mock(MusicDataStore.class);
- preparedQueryObject = Mockito.mock(PreparedQueryObject.class);
- ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure");
- session = Mockito.mock(Session.class);
- Mockito.when(mDstoreHandle.getSession()).thenReturn(session);
- Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "eventual")).thenReturn(false);
- ReturnType actualResult = MusicCore.eventualPut(preparedQueryObject);
- assertEquals(expectedResult.getResult(), actualResult.getResult());
- Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "eventual");
- //Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, MusicUtil.EVENTUAL);
- }
-
- @Test
- public void testCriticalPutPreparedQuerywithValidLockId()
- throws Exception {
- mDstoreHandle = Mockito.mock(MusicDataStore.class);
- preparedQueryObject = Mockito.mock(PreparedQueryObject.class);
- MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1");
- Mockito.when(condition.testCondition()).thenReturn(true);
- session = Mockito.mock(Session.class);
- Mockito.when(mDstoreHandle.getSession()).thenReturn(session);
- ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes");
- Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1"))
- .thenReturn(musicLockState);
- Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "critical")).thenReturn(true);
- ReturnType returnType = MusicCore.criticalPut("ks1", "tn1", "pk1", preparedQueryObject,
- "id1", condition);
- assertEquals(expectedResult.getResult(), returnType.getResult());
- Mockito.verify(condition).testCondition();
- Mockito.verify(mLockHandle).getLockState("ks1" + "." + "tn1" + "." + "pk1");
- Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "critical");
- }
-
- @Test
- public void testCriticalPutPreparedQuerywithInvalidLockId() throws MusicLockingException {
- mDstoreHandle = Mockito.mock(MusicDataStore.class);
- preparedQueryObject = Mockito.mock(PreparedQueryObject.class);
- MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2");
- ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure");
- Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1"))
- .thenReturn(musicLockState);
- ReturnType returnType = MusicCore.criticalPut("ks1", "tn1", "pk1", preparedQueryObject,
- "id1", condition);
- assertEquals(expectedResult.getResult(), returnType.getResult());
- Mockito.verify(mLockHandle).getLockState("ks1" + "." + "tn1" + "." + "pk1");
- }
-
- @Test
- public void testCriticalPutPreparedQuerywithvalidLockIdandTestConditionFalse() throws Exception {
- mDstoreHandle = Mockito.mock(MusicDataStore.class);
- preparedQueryObject = Mockito.mock(PreparedQueryObject.class);
- MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1");
- Mockito.when(condition.testCondition()).thenReturn(false);
- ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure");
- Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1"))
- .thenReturn(musicLockState);
- ReturnType returnType = MusicCore.criticalPut("ks1", "tn1", "pk1", preparedQueryObject,
- "id1", condition);
- assertEquals(expectedResult.getResult(), returnType.getResult());
- Mockito.verify(condition).testCondition();
- Mockito.verify(mLockHandle).getLockState("ks1" + "." + "tn1" + "." + "pk1");
- }
-
- @Test
- public void testNonKeyRelatedPutPreparedQuery() throws Exception {
- mDstoreHandle = Mockito.mock(MusicDataStore.class);
- preparedQueryObject = Mockito.mock(PreparedQueryObject.class);
- session = Mockito.mock(Session.class);
- Mockito.when(mDstoreHandle.getSession()).thenReturn(session);
- Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "consistency")).thenReturn(true);
- ResultType result = MusicCore.nonKeyRelatedPut(preparedQueryObject, "consistency");
- assertEquals(ResultType.SUCCESS, result);
- Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "consistency");
- }
-
- @Test
- public void testAtomicPutPreparedQuery() throws Exception {
- mDstoreHandle = Mockito.mock(MusicDataStore.class);
- preparedQueryObject = Mockito.mock(PreparedQueryObject.class);
- Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1");
- MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1");
- ReturnType expectedResult = new ReturnType(ResultType.SUCCESS, "Succes");
- session = Mockito.mock(Session.class);
- Mockito.when(mDstoreHandle.getSession()).thenReturn(session);
- Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState);
- Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true);
- Mockito.when(condition.testCondition()).thenReturn(true);
- Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1"))
- .thenReturn(musicLockState);
- Mockito.when(mDstoreHandle.executePut(preparedQueryObject, "critical")).thenReturn(true);
- ReturnType returnType =
- MusicCore.atomicPut("ks1", "tn1", "pk1", preparedQueryObject, condition);
- assertEquals(expectedResult.getResult(), returnType.getResult());
- Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1");
- Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1");
- Mockito.verify(mLockHandle).isMyTurn("id1");
- Mockito.verify(condition).testCondition();
- Mockito.verify(mLockHandle, Mockito.atLeastOnce())
- .getLockState("ks1" + "." + "tn1" + "." + "pk1");
- Mockito.verify(mDstoreHandle).executePut(preparedQueryObject, "critical");
- }
-
- @Test
- public void testAtomicPutPreparedQuerywithAcquireLockWithLeaseFalse() throws MusicLockingException {
- mDstoreHandle = Mockito.mock(MusicDataStore.class);
- preparedQueryObject = Mockito.mock(PreparedQueryObject.class);
- Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1");
- ReturnType expectedResult = new ReturnType(ResultType.FAILURE, "Failure");
- Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false);
- ReturnType returnType =
- MusicCore.atomicPut("ks1", "tn1", "pk1", preparedQueryObject, condition);
- assertEquals(expectedResult.getResult(), returnType.getResult());
- Mockito.verify(mLockHandle).isMyTurn("id1");
- Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1");
- }
-
- @Test
- public void testAtomicGetPreparedQuery() throws MusicServiceException, MusicQueryException, MusicLockingException {
- mDstoreHandle = Mockito.mock(MusicDataStore.class);
- preparedQueryObject = Mockito.mock(PreparedQueryObject.class);
- rs = Mockito.mock(ResultSet.class);
- session = Mockito.mock(Session.class);
- Mockito.when(mDstoreHandle.getSession()).thenReturn(session);
- Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1");
- MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1");
- Mockito.when(mLockHandle.getLockState("ks1.tn1.pk1")).thenReturn(musicLockState);
- Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(true);
- Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1"))
- .thenReturn(musicLockState);
- Mockito.when(mDstoreHandle.executeCriticalGet(preparedQueryObject)).thenReturn(rs);
- ResultSet rs1 = MusicCore.atomicGet("ks1", "tn1", "pk1", preparedQueryObject);
- assertNotNull(rs1);
- Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1");
- Mockito.verify(mLockHandle, Mockito.atLeastOnce()).getLockState("ks1.tn1.pk1");
- Mockito.verify(mLockHandle).isMyTurn("id1");
- Mockito.verify(mLockHandle, Mockito.atLeastOnce())
- .getLockState("ks1" + "." + "tn1" + "." + "pk1");
- Mockito.verify(mDstoreHandle).executeCriticalGet(preparedQueryObject);
- }
-
- @Test
- public void testAtomicGetPreparedQuerywithAcquireLockWithLeaseFalse()
- throws MusicServiceException, MusicLockingException {
- mDstoreHandle = Mockito.mock(MusicDataStore.class);
- preparedQueryObject = Mockito.mock(PreparedQueryObject.class);
- rs = Mockito.mock(ResultSet.class);
- Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1");
- Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false);
- ResultSet rs1 = MusicCore.atomicGet("ks1", "tn1", "pk1", preparedQueryObject);
- assertNull(rs1);
- Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1");
- Mockito.verify(mLockHandle).isMyTurn("id1");
- }
-
- @Test
- public void testGetPreparedQuery() throws MusicServiceException, MusicQueryException {
- mDstoreHandle = Mockito.mock(MusicDataStore.class);
- rs = Mockito.mock(ResultSet.class);
- preparedQueryObject = Mockito.mock(PreparedQueryObject.class);
- session = Mockito.mock(Session.class);
- Mockito.when(mDstoreHandle.getSession()).thenReturn(session);
- Mockito.when(mDstoreHandle.executeEventualGet(preparedQueryObject)).thenReturn(rs);
- ResultSet rs1 = MusicCore.get(preparedQueryObject);
- assertNotNull(rs1);
- Mockito.verify(mDstoreHandle).executeEventualGet(preparedQueryObject);
-
- }
-
- @Test
- public void testcriticalGetPreparedQuery() throws MusicServiceException, MusicQueryException, MusicLockingException {
- mDstoreHandle = Mockito.mock(MusicDataStore.class);
- preparedQueryObject = Mockito.mock(PreparedQueryObject.class);
- MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id1");
- rs = Mockito.mock(ResultSet.class);
- session = Mockito.mock(Session.class);
- Mockito.when(mDstoreHandle.getSession()).thenReturn(session);
- Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1"))
- .thenReturn(musicLockState);
- Mockito.when(mDstoreHandle.executeCriticalGet(preparedQueryObject)).thenReturn(rs);
- ResultSet rs1 = MusicCore.criticalGet("ks1", "tn1", "pk1", preparedQueryObject, "id1");
- assertNotNull(rs1);
- Mockito.verify(mLockHandle, Mockito.atLeastOnce())
- .getLockState("ks1" + "." + "tn1" + "." + "pk1");
- Mockito.verify(mDstoreHandle).executeCriticalGet(preparedQueryObject);
- }
-
- @Test
- public void testcriticalGetPreparedQuerywithInvalidLockId() throws MusicServiceException, MusicLockingException {
- mDstoreHandle = Mockito.mock(MusicDataStore.class);
- preparedQueryObject = Mockito.mock(PreparedQueryObject.class);
- MusicLockState musicLockState = new MusicLockState(LockStatus.UNLOCKED, "id2");
- Mockito.when(mLockHandle.getLockState("ks1" + "." + "tn1" + "." + "pk1"))
- .thenReturn(musicLockState);
- ResultSet rs1 = MusicCore.criticalGet("ks1", "tn1", "pk1", preparedQueryObject, "id1");
- assertNull(rs1);
- Mockito.verify(mLockHandle, Mockito.atLeastOnce())
- .getLockState("ks1" + "." + "tn1" + "." + "pk1");
- }
-
- @Test
- public void testAtomicGetPreparedQuerywithDeleteLockWithLeaseFalse()
- throws MusicServiceException, MusicLockingException {
- mDstoreHandle = Mockito.mock(MusicDataStore.class);
- preparedQueryObject = Mockito.mock(PreparedQueryObject.class);
- rs = Mockito.mock(ResultSet.class);
- Mockito.when(mLockHandle.createLockId("/" + "ks1.tn1.pk1")).thenReturn("id1");
- Mockito.when(mLockHandle.isMyTurn("id1")).thenReturn(false);
- ResultSet rs1 = MusicCore.atomicGet("ks1", "tn1", "pk1", preparedQueryObject);
- assertNull(rs1);
- Mockito.verify(mLockHandle).createLockId("/" + "ks1.tn1.pk1");
- Mockito.verify(mLockHandle).isMyTurn("id1");
- }
-
- @Test
- public void testCondition() throws Exception {
- //Condition conClass = Mockito.mock(Condition.class);
- // boolean ret=true;
- //Mockito.when(conClass.testCondition().thenReturn(ret);
- Map<String, Object> conditionsx=null;
- PreparedQueryObject selectQueryForTheRowx=null;
- try {
- Condition con = new Condition(conditionsx,selectQueryForTheRowx);
- assertTrue(con.testCondition());
- } catch (Exception e) {
- assertFalse(false);
- }
- }
- //getLockingServiceHandl
-
- @Ignore
- @Test(expected = MusicLockingException.class) //("Failed to aquire Locl store handle " + e))
- public void testgetLockingServiceHandle() throws Exception {
- // MusicLockingService mLockHandlex = Mockito.mock(MusicLockingService.class);
- //MusicLockingService mLockHandlea = mLockHandle;
- //mLockHandle=null;
- System.out.println("cjc 0 locking test n");
- // Mockito.when(MusicCore.getLockingServiceHandle()).thenReturn(mLockHandle);
- //mLockHandle=null;
- //System.out.println("cjc 0-1 locking test n");
- MusicLockingService mLockHandlea = mLockHandle;
- mLockHandle=null;
-
- MusicLockingService mLockHandley=null; //MusicCore.getLockingServiceHandle();
- Mockito.when(MusicCore.getLockingServiceHandle()).thenReturn(mLockHandley);
- System.out.println("cjc locking test n");
- mLockHandle=mLockHandlea;
- assertTrue(true);
-
- }
-
- @Test(expected = MusicServiceException.class)
- public void testGetDSHandle() throws MusicServiceException, MusicQueryException {
- // rs = Mockito.mock(ResultSet.class);
- // session = Mockito.mock(Session.class);
- //Mockito.when(mDstoreHandle.getSession()).thenReturn(session);
- //Mockito.when(mDstoreHandle.executeCriticalGet(preparedQueryObject)).thenReturn(rs);
-
- MusicDataStore mDstoreHandlea = Mockito.mock(MusicDataStore.class);
- //MusicUtil mMusicUtil=Mockito.mock(MusicUtil.class);
- //System.out.println("cjc 0 getDsHandle");
- Mockito.when(MusicCore.getDSHandle()).thenReturn(mDstoreHandlea);
- // System.out.println("cjc localhost");
- // Mockito.when(mMusicUtil.getMyCassaHost().equals("localhost")).thenReturn(null);
- //System.out.println("cjc 1 localhost");
- // mDstoreHandle = new MusicDataStore(MusicUtil.getMyCassaHost());
- // } else {
- // mDstoreHandle = new MusicDataStore();
- // }
- assertTrue(true);
- }
-
- //add mocking
- @Ignore
- @Test
- public void testGetDSHandleIp() throws MusicServiceException, MusicQueryException {
- // rs = Mockito.mock(ResultSet.class);
- // session = Mockito.mock(Session.class);
- //Mockito.when(mDstoreHandle.getSession()).thenReturn(session);
- //Mockito.when(mDstoreHandle.executeCriticalGet(preparedQueryObject)).thenReturn(rs);
-
- //mDstoreHandle = Mockito.mock(MusicDataStore.class);
- //MusicUtil mMusicUtil=Mockito.mock(MusicUtil.class);
- System.out.println("cjc 0 getDsHandleIP");
- Mockito.when(MusicCore.getDSHandle("1.127.0.1")).thenReturn(mDstoreHandle);
- System.out.println("cjc localhost");
- // Mockito.when(mMusicUtil.getMyCassaHost().equals("localhost")).thenReturn(null);
- System.out.println("cjc 1 localhost IP");
- // mDstoreHandle = new MusicDataStore(MusicUtil.getMyCassaHost());
- // } else {
- // mDstoreHandle = new MusicDataStore();
- // }
- assertTrue(true);
- }
-
- @Ignore
- @Test
- public void testPureZkCreate() {
- try {
- MusicCore.pureZkCreate("local");
- } catch(NullPointerException e) {
- System.out.println("cjc zkcreate null pointwer exception:"+ e);
- }
- }
-
- @Ignore
- @Test
- public void testPureZkRead() { //String nodeName) {
- byte[] data = MusicCore.pureZkRead("localhost");
- }
-
- //need fixing
- @Ignore
- @Test
- public void testPureZkWrite() { //String nodeName, byte[] data) {
- /*
- long start = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Performing zookeeper write to " + nodeName);
- try {
- getLockingServiceHandle().getzkLockHandle().setNodeData(nodeName, data);
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), "[ERR512E] Failed to get ZK Lock Handle " ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
- logger.info(EELFLoggerDelegate.applicationLogger,"Performed zookeeper write to " + nodeName);
- long end = System.currentTimeMillis();
- logger.info(EELFLoggerDelegate.applicationLogger,"Time taken for the actual zk put:" + (end - start) + " ms");
- */
-
- // mDstoreHandle = Mockito.mock(MusicDataStore.class);
- // rs = Mockito.mock(ResultSet.class);
- // session = Mockito.mock(Session.class);
- //Mockito.when(mDstoreHandle.getSession()).thenReturn(session);
-
- byte[] data= "Testing Zoo Keeper".getBytes();
- MusicCore.pureZkWrite("1.127.0.1", data);
- // assertNotNull(rs1);
- }
-
- @Test
- public void testWhoseTurnIsIt() { //(String lockName) {
-
- /*
- try {
- return getLockingServiceHandle().whoseTurnIsIt("/" + lockName) + "";
- } catch (MusicLockingException e) {
- logger.error(EELFLoggerDelegate.errorLogger,e.getMessage(), AppMessages.LOCKINGERROR+lockName ,ErrorSeverity.CRITICAL, ErrorTypes.LOCKINGERROR);
- }
- return null;
- */
-
- String lockName="xxx";
- if (MusicCore.whoseTurnIsIt(lockName) != null) assertTrue(true);
-
-
-
- }
-
- @Test
- public void testMarshallResults() {
- Map<String, HashMap<String, Object>> ret=null;
- //ResultSet results =null;
- rs = Mockito.mock(ResultSet.class);
- try {
- ret= MusicCore.marshallResults(rs);
-
- } catch( Exception e ) {
-
- }
-
- if (ret != null) assertTrue(true);
- }
-
-}
diff --git a/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java b/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java
deleted file mode 100644
index d327d0f0..00000000
--- a/src/test/java/org/onap/music/unittests/TestMusicCoreIntegration.java
+++ /dev/null
@@ -1,176 +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 static org.junit.Assert.assertTrue;
-import java.io.File;
-import java.util.List;
-import org.apache.curator.test.TestingServer;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.runners.MethodSorters;
-import org.onap.music.datastore.PreparedQueryObject;
-import org.onap.music.exceptions.MusicQueryException;
-import org.onap.music.exceptions.MusicServiceException;
-import org.onap.music.lockingservice.MusicLockState;
-import org.onap.music.lockingservice.MusicLockingService;
-import org.onap.music.lockingservice.MusicLockState.LockStatus;
-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 com.datastax.driver.core.ResultSet;
-import com.datastax.driver.core.Row;
-
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class TestMusicCoreIntegration {
-
- static TestingServer zkServer;
- static PreparedQueryObject testObject;
- static String lockId = null;
- static String lockName = "ks1.tb1.pk1";
-
- @BeforeClass
- public static void init() throws Exception {
- try {
- MusicCore.mDstoreHandle = CassandraCQL.connectToEmbeddedCassandra();
- zkServer = new TestingServer(2181, new File("/tmp/zk"));
- MusicCore.mLockHandle = new MusicLockingService();
- } catch (Exception e) {
- e.printStackTrace();
- }
- System.out.println("####Port:" + zkServer.getPort());
- }
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {
- System.out.println("After class");
- testObject = new PreparedQueryObject();
- testObject.appendQueryString(CassandraCQL.dropKeyspace);
- MusicCore.eventualPut(testObject);
- MusicCore.deleteLock(lockName);
- MusicCore.mDstoreHandle.close();
- MusicCore.mLockHandle.getzkLockHandle().close();
- MusicCore.mLockHandle.close();
- zkServer.stop();
-
- }
-
- @Test
- public void Test1_SetUp() throws MusicServiceException, MusicQueryException {
- MusicCore.mLockHandle = new MusicLockingService();
- ResultType result = ResultType.FAILURE;
- testObject = new PreparedQueryObject();
- testObject.appendQueryString(CassandraCQL.createKeySpace);
- MusicCore.eventualPut(testObject);
- testObject = new PreparedQueryObject();
- testObject.appendQueryString(CassandraCQL.createTableEmployees);
- result = MusicCore.nonKeyRelatedPut(testObject, MusicUtil.EVENTUAL);
- assertEquals(ResultType.SUCCESS, result);
- }
-
- @Test
- public void Test2_atomicPut() throws Exception {
- testObject = new PreparedQueryObject();
- testObject = CassandraCQL.setPreparedInsertQueryObject1();
- ReturnType returnType = MusicCore.atomicPut("testCassa", "employees", "Mr Test one",
- testObject, null);
- assertEquals(ResultType.SUCCESS, returnType.getResult());
- }
-
- @Test
- public void Test3_atomicPutWithDeleteLock() throws Exception {
- testObject = new PreparedQueryObject();
- testObject = CassandraCQL.setPreparedInsertQueryObject2();
- ReturnType returnType = MusicCore.atomicPutWithDeleteLock("testCassa", "employees",
- "Mr Test two", testObject, null);
- assertEquals(ResultType.SUCCESS, returnType.getResult());
- }
-
- @Test
- public void Test4_atomicGetWithDeleteLock() throws Exception {
- testObject = new PreparedQueryObject();
- testObject = CassandraCQL.setPreparedGetQuery();
- ResultSet resultSet = MusicCore.atomicGetWithDeleteLock("testCassa", "employees",
- "Mr Test one", testObject);
- List<Row> rows = resultSet.all();
- assertEquals(1, rows.size());
- }
-
- @Test
- public void Test5_atomicGet() throws Exception {
- testObject = new PreparedQueryObject();
- testObject = CassandraCQL.setPreparedGetQuery();
- ResultSet resultSet =
- MusicCore.atomicGet("testCassa", "employees", "Mr Test two", testObject);
- List<Row> rows = resultSet.all();
- assertEquals(1, rows.size());
- }
-
- @Test
- public void Test6_createLockReference() throws Exception {
- lockId = MusicCore.createLockReference(lockName);
- assertNotNull(lockId);
- }
-
- @Test
- public void Test7_acquireLockwithLease() throws Exception {
- ReturnType lockLeaseStatus = MusicCore.acquireLockWithLease(lockName, lockId, 1000);
- assertEquals(ResultType.SUCCESS, lockLeaseStatus.getResult());
- }
-
- @Test
- public void Test8_acquireLock() throws Exception {
- ReturnType lockStatus = MusicCore.acquireLock(lockName, lockId);
- assertEquals(ResultType.SUCCESS, lockStatus.getResult());
- }
-
- @Test
- public void Test9_release() throws Exception {
- MusicLockState musicLockState = new MusicLockState(LockStatus.LOCKED, "id1");
- MusicLockState musicLockState1 = new MusicLockState(LockStatus.UNLOCKED, "id1");
- MusicCore.whoseTurnIsIt(lockName);
- MusicLockState mls = MusicCore.getMusicLockState(lockName);
- boolean voluntaryRelease = true;
- MusicLockState mls1 = MusicCore.releaseLock(lockId, voluntaryRelease);
- assertEquals(musicLockState.getLockStatus(), mls.getLockStatus());
- assertEquals(musicLockState1.getLockStatus(), mls1.getLockStatus());
- }
-
- @Test
- public void Test10_create() {
- MusicCore.pureZkCreate("/nodeName");
- }
-
- @Test
- public void Test11_write() {
- MusicCore.pureZkWrite("nodeName", "I'm Test".getBytes());
- }
-
- @Test
- public void Test12_read() {
- byte[] data = MusicCore.pureZkRead("nodeName");
- String data1 = new String(data);
- assertEquals("I'm Test", data1);
- }
-
-}
diff --git a/src/test/java/org/onap/music/unittests/TestRestAdminData.java b/src/test/java/org/onap/music/unittests/TestRestAdminData.java
deleted file mode 100644
index 892a20f6..00000000
--- a/src/test/java/org/onap/music/unittests/TestRestAdminData.java
+++ /dev/null
@@ -1,2244 +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.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.onap.music.main.MusicCore.mLockHandle;
-
-import java.io.File;
-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.MultivaluedMap;
-import javax.ws.rs.core.Response;
-import javax.ws.rs.core.UriInfo;
-import org.apache.curator.test.TestingServer;
-import org.apache.http.impl.client.AutoRetryHttpClient;
-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.mindrot.jbcrypt.BCrypt;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.Mockito;
-import org.mockito.MockitoAnnotations;
-import org.mockito.runners.MockitoJUnitRunner;
-import org.onap.music.conductor.conditionals.JsonConditional;
-import org.onap.music.conductor.conditionals.MusicConditional;
-import org.onap.music.conductor.conditionals.RestMusicConditionalAPI;
-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.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.exceptions.MusicServiceException;
-import org.onap.music.lockingservice.MusicLockState;
-import org.onap.music.lockingservice.MusicLockingService;
-import org.onap.music.lockingservice.MusicLockState.LockStatus;
-import org.onap.music.main.CachingUtil;
-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.RestMusicAdminAPI;
-import org.onap.music.rest.RestMusicBmAPI;
-import org.onap.music.rest.RestMusicDataAPI;
-import org.onap.music.rest.RestMusicHealthCheckAPI;
-import org.onap.music.rest.RestMusicLocksAPI;
-import org.onap.music.rest.RestMusicTestAPI;
-import org.onap.music.rest.RestMusicVersionAPI;
-
-import com.datastax.driver.core.ConsistencyLevel;
-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;
-
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-@RunWith(MockitoJUnitRunner.class)
-public class TestRestAdminData {
-
- RestMusicDataAPI data = new RestMusicDataAPI();
- RestMusicAdminAPI admin = new RestMusicAdminAPI();
- RestMusicLocksAPI lock = new RestMusicLocksAPI();
- static PreparedQueryObject testObject;
- static TestingServer zkServer;
-
- @Mock
- HttpServletResponse http;
-
- @Mock
- UriInfo info;
-
- //* cjc out
- @Mock
- CachingUtil cachUtilMock;
-
- @InjectMocks
- private MusicCore mCore;
- //*/
-
- 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 tableNameConditional = "Conductor";
- static String xLatestVersion = "X-latestVersion";
- static String onboardUUID = null;
- static String lockId = null;
- static String lockName = "testCassa.employees.sample3";
-
- @BeforeClass
- public static void init() throws Exception {
- try {
- MusicCore.mDstoreHandle = CassandraCQL.connectToEmbeddedCassandra();
- zkServer = new TestingServer(2181, new File("/tmp/zk"));
- MusicCore.mLockHandle = new MusicLockingService();
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
- @AfterClass
- public static void tearDownAfterClass() throws Exception {
- 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);
- MusicCore.mDstoreHandle.close();
- MusicCore.mLockHandle.getzkLockHandle().close();
- MusicCore.mLockHandle.close();
- zkServer.stop();
- }
-
- @Test
- public void Test1_createKeyspace() throws Exception {
- 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<Row> rows = rs.all();
- if (rows.size() > 0) {
- System.out.println("#######UUID is:" + rows.get(0).getUUID("uuid"));
- }
- }
-
- @Test
- public void Test2_createKeyspace() throws Exception {
- JsonKeySpace jsonKeyspace = new JsonKeySpace();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> 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 is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertEquals(200,response.getStatus());
- }
-
- @Test
- public void Test2_createKeyspace1() throws Exception {
- JsonKeySpace jsonKeyspace = new JsonKeySpace();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> 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 is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertEquals(200,response.getStatus());
- }
-
- @Test
- public void Test2_createKeyspace0() throws Exception {
- JsonKeySpace jsonKeyspace = new JsonKeySpace();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> replicationInfo = new HashMap<>();
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.createKeySpace("1", "1", "1", null, authorization,appName, jsonKeyspace, keyspaceName);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertEquals(400,response.getStatus());
- }
-//MusicCore.autheticateUser
- @Test
- public void Test2_createKeyspace01() throws Exception {
- JsonKeySpace jsonKeyspace = new JsonKeySpace();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> replicationInfo = new HashMap<>();
- String appName1 = "test";
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.createKeySpace("1", "1", "1", null,authorization, appName1, jsonKeyspace, keyspaceName);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertEquals(401,response.getStatus());
- }
-
- @Test
- public void Test3_createKeyspace1() throws Exception {
- JsonKeySpace jsonKeyspace = new JsonKeySpace();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> 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);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.createKeySpace("1", "1", "1", null,authorization, "TestApp1",
- jsonKeyspace, keyspaceName);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertEquals(401,response.getStatus());
- }
-
- @Test
- public void Test2_createKeyspaceEmptyAuth() throws Exception {
-
- //MockitoAnnotations.initMocks(this);
- JsonKeySpace jsonKeyspace = new JsonKeySpace();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> 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);
- //Map<String, Object> m1= new HashMap<>() ;
- //Mockito.when(CachingUtil.verifyOnboarding("x","y","x")).thenReturn(m1);
- //Mockito.when(CachingUtil.verifyOnboarding(appNamex,userId,password).thenReturn(m1));
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- String authDatax = ":"+password;
- String authorizationx = new String(Base64.encode(authDatax.getBytes()));
- try {
- Response response = data.createKeySpace("1", "1", "1", null,authorizationx, appName, jsonKeyspace, keyspaceName);
- //System.out.println("#######status is " + response.getStatus());
- //System.out.println("Entity" + response.getEntity());
- //assertNotEquals(200,response.getStatus());
- } catch (RuntimeException e ) {
- System.out.println("#######status is runtime exception= " + e);
- }
- }
-
- @Test
- public void Test3_createTable() throws Exception {
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertEquals(200, response.getStatus());
- }
-
-
- @Test
- public void Test3_createTableClusterOrderBad() throws Exception {
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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);
- 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);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertNotEquals(200, response.getStatus());
- }
-
- @Test
- public void Test3_createTable_withPropertiesNotNull() throws Exception {
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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<String, Object> 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);
-
- 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_prop);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test3_createTable_duplicateTable() throws Exception {
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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 = data.createTable("1", "1", "1",
- "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 = data.createTable("1", "1", "1",
- "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());
-
- }
-
- // Improper Auth
- @Test
- public void Test3_createTable1() throws Exception {
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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, wrongAuthorization,
- jsonTable, keyspaceName, tableName);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertEquals(401, response.getStatus());
- }
-
- // Improper keyspace
- @Test
- public void Test3_createTable3() throws Exception {
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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, "wrong", tableName);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertEquals(401, response.getStatus());
- }
-
- @Test
- public void Test3_createTable3_with_samePartition_clusteringKeys() throws Exception {
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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.setPartitionKey("emp_name");
- jsonTable.setClusteringKey("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);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test3_createTable3_with_Partition_clusteringKeys() throws Exception {
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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.setPartitionKey("emp_name");
- jsonTable.setClusteringKey("uuid");
- 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, "tableName1");
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertEquals(200, response.getStatus());
- }
-
- // Improper parenthesis in key field
- @Test
- public void Test3_createTable_badParantesis() throws Exception {
- String tableNameC ="testTable0";
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.createTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonTable, keyspaceName, tableNameC);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- //assertEquals(400, response.getStatus());
- assertTrue(200 != response.getStatus());
- }
-
-
- // good clustering key
- @Test
- public void Test3_createTable_1_clusterKey_good() throws Exception {
- String tableNameC ="testTableC1";
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.createTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonTable, keyspaceName, tableNameC);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertEquals(200, response.getStatus());
- }
-
- // bad partition key=clustering key
- @Test
- public void Test3_createTable_2_clusterKey_bad() throws Exception {
- String tableNameC ="testTableC2";
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.createTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonTable, keyspaceName, tableNameC);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertTrue(200 !=response.getStatus());
- }
-
- // good composite partition key,clustering key
- @Test
- public void Test3_createTable_3_partition_clusterKey_good() throws Exception {
- String tableNameC ="testTableC3";
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.createTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonTable, keyspaceName, tableNameC);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertEquals(200, response.getStatus());
- }
-
- // bad - not all cols in order by of composite partition key,clustering key
- @Test
- public void Test3_createTable_4_clusteringOrder_bad() throws Exception {
- String tableNameC ="testTableC4";
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.createTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonTable, keyspaceName, tableNameC);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertTrue(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 {
- String tableNameC ="testTableC5";
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.createTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonTable, keyspaceName, tableNameC);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertTrue(200 != response.getStatus());
- }
-
- // bad - wrong cols in order by of composite partition key,clustering key
- @Test
- public void Test3_createTable_6_clusteringOrder_bad() throws Exception {
- String tableNameC ="testTableC6";
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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("((uuid,emp_name),emp_id,emp_salary)"); // overridden by
- jsonTable.setTableName(tableNameC);
- jsonTable.setClusteringOrder("emp_id desc, emp_salary ASC,uuid desc");
- 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, tableNameC);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertTrue(200 != response.getStatus());
- }
-
-
- @Test
- public void Test3_createTableIndex_1() throws Exception {
- String tableNameC ="testTableCinx";
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.createTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonTable, keyspaceName, tableNameC);
- MultivaluedMap<String, String> rowParams = Mockito.mock(MultivaluedMap.class);
- Mockito.when(info.getQueryParameters()).thenReturn(rowParams);
- Mockito.when(rowParams.getFirst("index_name")).thenReturn("my_index");
- response = data.createIndex("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- keyspaceName, tableNameC,"uuid",info);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test3_createTableIndex_badindexname() throws Exception {
- String tableNameC ="testTableCinx";
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.createTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonTable, keyspaceName, tableNameC);
- MultivaluedMap<String, String> rowParams = Mockito.mock(MultivaluedMap.class);
- Mockito.when(info.getQueryParameters()).thenReturn(rowParams);
- Mockito.when(rowParams.getFirst("index_name")).thenReturn("my index");
- response = data.createIndex("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- keyspaceName, tableNameC,"uuid",info);
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test3_createTableIndex_wrongindex() throws Exception {
- String tableNameC ="testTableCinx";
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> 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);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.createTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonTable, keyspaceName, tableNameC);
- MultivaluedMap<String, String> rowParams = Mockito.mock(MultivaluedMap.class);
- Mockito.when(info.getQueryParameters()).thenReturn(rowParams);
- Mockito.when(rowParams.getFirst("index_name")).thenReturn("my_index");
- response = data.createIndex("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- keyspaceName, tableNameC,"id",info);
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test4_insertIntoTable() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> 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 = data.insertIntoTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- appName, authorization, jsonInsert, keyspaceName, tableName);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test4_insertIntoTable2() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> 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 = data.insertIntoTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonInsert, keyspaceName, tableName);
- assertEquals(200, response.getStatus());
- }
-
- // Auth Error
- @Test
- public void Test4_insertIntoTable3() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> 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 = data.insertIntoTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, wrongAuthorization,
- jsonInsert, keyspaceName, tableName);
- assertEquals(401, response.getStatus());
- }
-
- // Table wrong
- @Test
- public void Test4_insertIntoTable4() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> 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 = data.insertIntoTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonInsert, keyspaceName, "wrong");
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test4_insertIntoTable5() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> values = new HashMap<>();
- values.put("id", "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 = data.insertIntoTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonInsert, keyspaceName, tableName);
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test4_insertIntoTable6() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> values = new HashMap<>();
- values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
- 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 = data.insertIntoTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonInsert, keyspaceName, tableName);
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test4_insertIntoTable7() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> values = new HashMap<>();
- values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
- values.put("emp_name", "test2");
- values.put("emp_salary", 1500);
- consistencyInfo.put("type", "eventual");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- jsonInsert.setKeyspaceName(keyspaceName);
- jsonInsert.setTableName(tableName);
- jsonInsert.setValues(values);
- jsonInsert.setTtl("1000");
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.insertIntoTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonInsert, keyspaceName, tableName);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test4_insertIntoTable8() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> values = new HashMap<>();
- values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
- values.put("emp_name", "test3");
- values.put("emp_salary", 1500);
- consistencyInfo.put("type", "eventual");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- jsonInsert.setKeyspaceName(keyspaceName);
- jsonInsert.setTableName(tableName);
- jsonInsert.setValues(values);
- jsonInsert.setTimestamp("15000");
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.insertIntoTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonInsert, keyspaceName, tableName);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test4_insertIntoTable9() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> values = new HashMap<>();
- values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
- values.put("emp_name", "test4");
- values.put("emp_salary", 1500);
- consistencyInfo.put("type", "eventual");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- jsonInsert.setKeyspaceName(keyspaceName);
- jsonInsert.setTableName(tableName);
- jsonInsert.setValues(values);
- jsonInsert.setTtl("1000");
- jsonInsert.setTimestamp("15000");
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.insertIntoTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonInsert, keyspaceName, tableName);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test4_insertIntoTable10() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> values = new HashMap<>();
- values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
- values.put("emp_name", "test5");
- values.put("emp_salary", 1500);
- consistencyInfo.put("type", "critical");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- jsonInsert.setKeyspaceName(keyspaceName);
- jsonInsert.setTableName(tableName);
- jsonInsert.setValues(values);
- jsonInsert.setTtl("1000");
- jsonInsert.setTimestamp("15000");
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.insertIntoTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonInsert, keyspaceName, tableName);
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test4_insertIntoTable11() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> values = new HashMap<>();
- values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
- values.put("emp_name", "test6");
- values.put("emp_salary", 1500);
- consistencyInfo.put("type", "atomic_delete_lock");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- jsonInsert.setKeyspaceName(keyspaceName);
- jsonInsert.setTableName(tableName);
- jsonInsert.setValues(values);
- jsonInsert.setTtl("1000");
- jsonInsert.setTimestamp("15000");
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.insertIntoTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonInsert, keyspaceName, tableName);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test4_insertIntoTable12() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> values = new HashMap<>();
- values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
- values.put("emp_name", "test7");
- values.put("emp_salary", 1500);
- consistencyInfo.put("type", "atomic");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- jsonInsert.setKeyspaceName(keyspaceName);
- jsonInsert.setTableName(tableName);
- jsonInsert.setValues(values);
- jsonInsert.setTtl("1000");
- jsonInsert.setTimestamp("15000");
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.insertIntoTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonInsert, keyspaceName, tableName);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test5_updateTable() throws Exception {
- JsonUpdate jsonUpdate = new JsonUpdate();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> 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 = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
- authorization, jsonUpdate, keyspaceName, tableName, info);
- assertEquals(200, response.getStatus());
- }
-
- // need mock code to create error for MusicCore methods
- @Test
- public void Test5_updateTableAuthE() throws Exception {
- MockitoAnnotations.initMocks(this);
- JsonUpdate jsonUpdate = new JsonUpdate();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> 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 = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
- authorization, jsonUpdate, keyspaceName, tableName, info);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test5_updateTableAuthException1() throws Exception {
- JsonUpdate jsonUpdate = new JsonUpdate();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> 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);
- String authDatax = ":";//+password;
- String authorizationx = new String(Base64.encode(authDatax.getBytes()));
- try {
- Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
- authorizationx, jsonUpdate, keyspaceName, tableName, info);
- assertEquals(200, response.getStatus());
- } catch(RuntimeException e) {
- System.out.println("Update table Runtime exception="+e);
- }
- }
-
- @Test
- public void Test5_updateTableAuthEmpty() throws Exception {
- JsonUpdate jsonUpdate = new JsonUpdate();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> 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);
- String authDatax =":"+password;
- String authorizationx = new String(Base64.encode(authDatax.getBytes()));
- String appNamex="xx";
- try {
- // Response response = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
- Response response = data.updateTable("1", "1", "1", "", appNamex,
- authorizationx, jsonUpdate, keyspaceName, tableName, info);
- assertEquals(200, response.getStatus());
- } catch(RuntimeException e) {
- System.out.println("Update table Runtime exception="+e);
- }
- }
-
- @Test
- public void Test5_updateTable_wrongauth() throws Exception {
- JsonUpdate jsonUpdate = new JsonUpdate();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> 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 = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
- wrongAuthorization, jsonUpdate, keyspaceName, tableName, info);
- assertEquals(401, response.getStatus());
- }
-
- @Test
- public void Test5_updateTable_invalidColumn() throws Exception {
- JsonUpdate jsonUpdate = new JsonUpdate();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> values = new HashMap<>();
- row.add("id", "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 = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
- authorization, jsonUpdate, keyspaceName, tableName, info);
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test5_updateTable_ttl() throws Exception {
- JsonUpdate jsonUpdate = new JsonUpdate();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> values = new HashMap<>();
- row.add("emp_name", "testName8");
- values.put("emp_salary", 2500);
- consistencyInfo.put("type", "atomic");
- jsonUpdate.setConsistencyInfo(consistencyInfo);
- jsonUpdate.setKeyspaceName(keyspaceName);
- jsonUpdate.setTableName(tableName);
- jsonUpdate.setValues(values);
- jsonUpdate.setTtl("1000");
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- 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 Test5_updateTable_timsetamp() throws Exception {
- JsonUpdate jsonUpdate = new JsonUpdate();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> values = new HashMap<>();
- row.add("emp_name", "testName9");
- values.put("emp_salary", 2500);
- consistencyInfo.put("type", "atomic");
- jsonUpdate.setConsistencyInfo(consistencyInfo);
- jsonUpdate.setKeyspaceName(keyspaceName);
- jsonUpdate.setTableName(tableName);
- jsonUpdate.setValues(values);
- jsonUpdate.setTimestamp("15000");
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- 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 Test5_updateTable_ttl_timestamp() throws Exception {
- JsonUpdate jsonUpdate = new JsonUpdate();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> values = new HashMap<>();
- row.add("emp_name", "testName10");
- values.put("emp_salary", 2500);
- consistencyInfo.put("type", "atomic");
- jsonUpdate.setConsistencyInfo(consistencyInfo);
- jsonUpdate.setKeyspaceName(keyspaceName);
- jsonUpdate.setTableName(tableName);
- jsonUpdate.setValues(values);
- jsonUpdate.setTtl("1000");
- jsonUpdate.setTimestamp("15000");
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- 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 Test5_updateTable_rowIdEmpty() throws Exception {
- JsonUpdate jsonUpdate = new JsonUpdate();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> values = new HashMap<>();
- //row.add("emp_name", "testName3");
- values.put("emp_salary", 2500);
- consistencyInfo.put("type", "atomic");
- jsonUpdate.setConsistencyInfo(consistencyInfo);
- jsonUpdate.setKeyspaceName(keyspaceName);
- jsonUpdate.setTableName(tableName);
- jsonUpdate.setValues(values);
- jsonUpdate.setTtl("1000");
- jsonUpdate.setTimestamp("15000");
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- 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 Test5_updateTable_conditions() throws Exception {
- JsonUpdate jsonUpdate = new JsonUpdate();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> values = new HashMap<>();
- Map<String, Object> conditions = new HashMap<>();
- conditions.put("emp_name","testName3");
- row.add("emp_name", "testName3");
- values.put("emp_salary", 2500);
- consistencyInfo.put("type", "atomic");
- jsonUpdate.setConsistencyInfo(consistencyInfo);
- jsonUpdate.setKeyspaceName(keyspaceName);
- jsonUpdate.setTableName(tableName);
- jsonUpdate.setValues(values);
- jsonUpdate.setConditions(conditions);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- 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 Test5_updateTable_eventual() throws Exception {
- JsonUpdate jsonUpdate = new JsonUpdate();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> values = new HashMap<>();
- row.add("emp_name", "testName");
- values.put("emp_salary", 2500);
- consistencyInfo.put("type", "eventual");
- 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 = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
- authorization, jsonUpdate, keyspaceName, tableName, info);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test5_updateTable_critical() throws Exception {
- JsonUpdate jsonUpdate = new JsonUpdate();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> values = new HashMap<>();
- row.add("emp_name", "testName");
- values.put("emp_salary", 2500);
- consistencyInfo.put("type", "critical");
- 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 = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
- authorization, jsonUpdate, keyspaceName, tableName, info);
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test5_updateTable_atomic_delete_lock() throws Exception {
- JsonUpdate jsonUpdate = new JsonUpdate();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> values = new HashMap<>();
- row.add("emp_name", "testName");
- values.put("emp_salary", 2500);
- consistencyInfo.put("type", "atomic_delete_lock");
- 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 = data.updateTable("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
- authorization, jsonUpdate, keyspaceName, tableName, info);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test6_select() throws Exception {
- JsonSelect jsonSelect = new JsonSelect();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> 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 = data.select("1", "1", "1","abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- appName, authorization, keyspaceName, tableName, info);
- HashMap<String,HashMap<String,Object>> map = (HashMap<String, HashMap<String, Object>>) response.getEntity();
- HashMap<String, Object> result = map.get("result");
- assertEquals("2500", ((HashMap<String,Object>) result.get("row 0")).get("emp_salary").toString());
- }
-
- @Test
- public void Test6_select_withException() throws Exception {
- JsonSelect jsonSelect = new JsonSelect();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> 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);
- RestMusicDataAPI spyData = Mockito.spy(RestMusicDataAPI.class);
- Mockito.doThrow(MusicServiceException.class).when(spyData).selectSpecificQuery("v2", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password, keyspaceName, tableName, info, -1);
- Response response = spyData.select("1", "1", "1","abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- appName, authorization, keyspaceName, tableName, info);
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test6_select_nodata() throws Exception {
- JsonSelect jsonSelect = new JsonSelect();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- row.add("emp_name", "testName12");
- consistencyInfo.put("type", "atomic");
- jsonSelect.setConsistencyInfo(consistencyInfo);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Mockito.when(info.getQueryParameters()).thenReturn(row);
- Response response = data.select("1", "1", "1","abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- appName, authorization, keyspaceName, tableName, info);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test6_selectCritical() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- row.add("emp_name", "testName");
- consistencyInfo.put("type", "atomic");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- 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<String,HashMap<String,Object>> map = (HashMap<String, HashMap<String, Object>>) response.getEntity();
- HashMap<String, Object> result = map.get("result");
- assertEquals("2500", ((HashMap<String,Object>) result.get("row 0")).get("emp_salary").toString());
- }
-
- @Test
- public void Test6_selectCritical_without_lockID() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- row.add("emp_name", "testName");
- consistencyInfo.put("type", "critical");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Mockito.when(info.getQueryParameters()).thenReturn(row);
- Response response = data.selectCritical("1", "1", "1","abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- appName, authorization, jsonInsert, keyspaceName, tableName,info);
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test6_selectCritical_with_atomic_delete_lock() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- row.add("emp_name", "testName");
- consistencyInfo.put("type", "atomic_delete_lock");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Mockito.when(info.getQueryParameters()).thenReturn(row);
- Response response = data.selectCritical("1", "1", "1","abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- appName, authorization, jsonInsert, keyspaceName, tableName,info);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test6_selectCritical_with_nodata() throws Exception {
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- row.add("emp_name", "testName12");
- consistencyInfo.put("type", "atomic_delete_lock");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Mockito.when(info.getQueryParameters()).thenReturn(row);
- Response response = data.selectCritical("1", "1", "1","abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- appName, authorization, jsonInsert, keyspaceName, tableName,info);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test6_select_all() throws Exception {
- JsonSelect jsonSelect = new JsonSelect();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();;
- consistencyInfo.put("type", "atomic");
- jsonSelect.setConsistencyInfo(consistencyInfo);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Mockito.when(info.getQueryParameters()).thenReturn(row);
- Response response = data.select("1", "1", "1","abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- appName, authorization, keyspaceName, tableName, info);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test6_deleteFromTable() throws Exception {
- JsonDelete jsonDelete = new JsonDelete();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> 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 = data.deleteFromTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonDelete, keyspaceName, tableName, info);
- assertEquals(200, response.getStatus());
- }
-
- // Values
- @Test
- public void Test6_deleteFromTable1() throws Exception {
- JsonDelete jsonDelete = new JsonDelete();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> 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 = data.deleteFromTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonDelete, keyspaceName, tableName, info);
- assertEquals(400, response.getStatus());
- }
-
- // delObj
- @Test
- public void Test6_deleteFromTable2() throws Exception {
- JsonDelete jsonDelete = new JsonDelete();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> 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 = data.deleteFromTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- null, keyspaceName, tableName, info);
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test6_deleteFromTable_columns() throws Exception {
- JsonDelete jsonDelete = new JsonDelete();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- row.add("emp_name", "test1");
- consistencyInfo.put("type", "atomic");
- jsonDelete.setConsistencyInfo(consistencyInfo);
- ArrayList<String> columns = new ArrayList<>();
- columns.add("uuid");
- jsonDelete.setColumns(columns);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Mockito.when(info.getQueryParameters()).thenReturn(row);
- Response response = data.deleteFromTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonDelete, keyspaceName, tableName, info);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test6_deleteFromTable_conditions() throws Exception {
- JsonDelete jsonDelete = new JsonDelete();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- Map<String, Object> conditions = new HashMap<>();
- conditions.put("emp_name","testName3");
- row.add("emp_name", "test1");
- consistencyInfo.put("type", "atomic");
- jsonDelete.setConsistencyInfo(consistencyInfo);
- ArrayList<String> columns = new ArrayList<>();
- jsonDelete.setConditions(conditions);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Mockito.when(info.getQueryParameters()).thenReturn(row);
- Response response = data.deleteFromTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonDelete, keyspaceName, tableName, info);
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test6_deleteFromTable_eventual() throws Exception {
- JsonDelete jsonDelete = new JsonDelete();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- row.add("emp_name", "test2");
- consistencyInfo.put("type", "eventual");
- jsonDelete.setConsistencyInfo(consistencyInfo);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Mockito.when(info.getQueryParameters()).thenReturn(row);
- Response response = data.deleteFromTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonDelete, keyspaceName, tableName, info);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test6_deleteFromTable_critical() throws Exception {
- JsonDelete jsonDelete = new JsonDelete();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- row.add("emp_name", "test2");
- consistencyInfo.put("type", "critical");
- jsonDelete.setConsistencyInfo(consistencyInfo);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Mockito.when(info.getQueryParameters()).thenReturn(row);
- Response response = data.deleteFromTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonDelete, keyspaceName, tableName, info);
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test6_deleteFromTable_atomic_delete_lock() throws Exception {
- JsonDelete jsonDelete = new JsonDelete();
- Map<String, String> consistencyInfo = new HashMap<>();
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- row.add("emp_name", "test3");
- consistencyInfo.put("type", "atomic_delete_lock");
- jsonDelete.setConsistencyInfo(consistencyInfo);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Mockito.when(info.getQueryParameters()).thenReturn(row);
- Response response = data.deleteFromTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- jsonDelete, keyspaceName, tableName, info);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test7_dropTable() throws Exception {
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- consistencyInfo.put("type", "atomic");
- jsonTable.setConsistencyInfo(consistencyInfo);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.dropTable("1", "1", "1",
- "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
- keyspaceName, tableName);
- assertEquals(200, response.getStatus());
- }
-
-
- @Test
- public void Test8_deleteKeyspace() throws Exception {
- JsonKeySpace jsonKeyspace = new JsonKeySpace();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> 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);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.dropKeySpace("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- authorization,appName, keyspaceName);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test8_deleteKeyspace1() throws Exception {
- JsonKeySpace jsonKeyspace = new JsonKeySpace();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> 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);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.dropKeySpace("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- authorization,appName, "keyspaceName");
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test8_deleteKeyspace2() throws Exception {
- JsonKeySpace jsonKeyspace = new JsonKeySpace();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> 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);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = data.dropKeySpace("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- wrongAuthorization, appName, keyspaceName);
- assertEquals(401, response.getStatus());
- }
-
- @Test
- public void Test6_onboard() throws Exception {
- JsonOnboard jsonOnboard = new JsonOnboard();
- jsonOnboard.setAppname("TestApp2");
- jsonOnboard.setIsAAF("false");
- jsonOnboard.setUserId("TestUser2");
- jsonOnboard.setPassword("TestPassword2");
- Map<String, Object> resultMap = (Map<String, Object>) admin.onboardAppWithMusic(jsonOnboard).getEntity();
- resultMap.containsKey("success");
- onboardUUID = resultMap.get("Generated AID").toString();
- assertEquals("Your application TestApp2 has been onboarded with MUSIC.", resultMap.get("Success"));
- }
-
- @Test
- public void Test6_onboard_duplicate() throws Exception {
- JsonOnboard jsonOnboard = new JsonOnboard();
- jsonOnboard.setAppname("TestApp2");
- jsonOnboard.setIsAAF("false");
- jsonOnboard.setUserId("TestUser2");
- jsonOnboard.setPassword("TestPassword2");
- Response response = admin.onboardAppWithMusic(jsonOnboard);
- assertEquals(400, response.getStatus());
- }
-
- // Missing appname
- @Test
- public void Test6_onboard1() throws Exception {
- JsonOnboard jsonOnboard = new JsonOnboard();
- jsonOnboard.setIsAAF("false");
- jsonOnboard.setUserId("TestUser2");
- jsonOnboard.setPassword("TestPassword2");
- Map<String, Object> resultMap = (Map<String, Object>) admin.onboardAppWithMusic(jsonOnboard).getEntity();
- resultMap.containsKey("success");
- System.out.println("--->" + resultMap.toString());
- assertEquals("Unauthorized: Please check the request parameters. Some of the required values appName(ns), userId, password, isAAF are missing.", resultMap.get("Exception"));
- }
-
-
- @Test
- public void Test7_onboardSearch() throws Exception {
- JsonOnboard jsonOnboard = new JsonOnboard();
- jsonOnboard.setAppname("TestApp2");
- jsonOnboard.setIsAAF("false");
- jsonOnboard.setAid(onboardUUID);
- Map<String, Object> resultMap = (Map<String, Object>) admin.getOnboardedInfoSearch(jsonOnboard).getEntity();
- resultMap.containsKey("success");
- assertEquals(MusicUtil.DEFAULTKEYSPACENAME, resultMap.get(onboardUUID));
- }
-
- // Missing appname
- @Test
- public void Test7_onboardSearch1() throws Exception {
- JsonOnboard jsonOnboard = new JsonOnboard();
- jsonOnboard.setIsAAF("false");
- jsonOnboard.setAid(onboardUUID);
- Map<String, Object> resultMap = (Map<String, Object>) admin.getOnboardedInfoSearch(jsonOnboard).getEntity();
- System.out.println("--->" + resultMap.toString());
- resultMap.containsKey("success");
- assertEquals(MusicUtil.DEFAULTKEYSPACENAME, resultMap.get(onboardUUID));
- }
-
- @Test
- public void Test7_onboardSearch_empty() throws Exception {
- JsonOnboard jsonOnboard = new JsonOnboard();
- Response response = admin.getOnboardedInfoSearch(jsonOnboard);
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test7_onboardSearch_invalidAid() throws Exception {
- JsonOnboard jsonOnboard = new JsonOnboard();
- jsonOnboard.setAppname("TestApp2");
- jsonOnboard.setIsAAF("false");
- jsonOnboard.setAid("abc66ccc-d857-4e90-b1e5-df98a3d40ce6");
- Response response = admin.getOnboardedInfoSearch(jsonOnboard);
- assertEquals(400, response.getStatus());
- }
-
- @Test
- public void Test8_onboardUpdate() throws Exception {
- JsonOnboard jsonOnboard = new JsonOnboard();
- jsonOnboard.setIsAAF("false");
- jsonOnboard.setUserId("TestUser3");
- jsonOnboard.setPassword("TestPassword3");
- jsonOnboard.setAid(onboardUUID);
- Map<String, Object> resultMap = (Map<String, Object>) admin.updateOnboardApp(jsonOnboard).getEntity();
- System.out.println("--->" + resultMap.toString());
- resultMap.containsKey("success");
- assertEquals("Your application has been updated successfully", resultMap.get("Success"));
- }
-
- // Aid null
- @Test
- public void Test8_onboardUpdate1() throws Exception {
- JsonOnboard jsonOnboard = new JsonOnboard();
- jsonOnboard.setIsAAF("false");
- jsonOnboard.setUserId("TestUser3");
- jsonOnboard.setPassword("TestPassword3");
- Map<String, Object> resultMap = (Map<String, Object>) admin.updateOnboardApp(jsonOnboard).getEntity();
- System.out.println("--->" + resultMap.toString());
- resultMap.containsKey("success");
- assertEquals("Please make sure Aid is present", resultMap.get("Exception"));
- }
-
- // Appname not null
- @Test
- public void Test8_onboardUpdate2() throws Exception {
- JsonOnboard jsonOnboard = new JsonOnboard();
- jsonOnboard.setAppname("TestApp2");
- jsonOnboard.setIsAAF("false");
- jsonOnboard.setUserId("TestUser3");
- jsonOnboard.setPassword("TestPassword3");
- jsonOnboard.setAid(onboardUUID);
- Map<String, Object> resultMap = (Map<String, Object>) admin.updateOnboardApp(jsonOnboard).getEntity();
- resultMap.containsKey("success");
- System.out.println("--->" + resultMap.toString());
- assertEquals("Application TestApp2 has already been onboarded. Please contact admin.", resultMap.get("Exception"));
- }
-
- // All null
- @Test
- public void Test8_onboardUpdate3() throws Exception {
- JsonOnboard jsonOnboard = new JsonOnboard();
- jsonOnboard.setAid(onboardUUID);
- Map<String, Object> resultMap = (Map<String, Object>) admin.updateOnboardApp(jsonOnboard).getEntity();
- assertTrue(resultMap.containsKey("Exception") );
- }
-
- @Test
- public void Test9_onboardDelete() throws Exception {
- JsonOnboard jsonOnboard = new JsonOnboard();
- jsonOnboard.setAppname("TestApp2");
- jsonOnboard.setAid(onboardUUID);
- Map<String, Object> resultMap = (Map<String, Object>) admin.deleteOnboardApp(jsonOnboard).getEntity();
- resultMap.containsKey("success");
- assertEquals("Your application has been deleted successfully", resultMap.get("Success"));
- }
-
- @Test
- public void Test9_onboardDelete1() throws Exception {
- JsonOnboard jsonOnboard = new JsonOnboard();
- Map<String, Object> resultMap = (Map<String, Object>) admin.deleteOnboardApp(jsonOnboard).getEntity();
- assertTrue(resultMap.containsKey("Exception"));
- }
-
- @Test
- public void Test3_createLockReference() throws Exception {
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Map<String, Object> resultMap = (Map<String, Object>) lock.createLockReference(lockName,"1","1",authorization, null, appName).getEntity();
- @SuppressWarnings("unchecked")
- Map<String, Object> resultMap1 = (Map<String, Object>) resultMap.get("lock");
- lockId = (String) resultMap1.get("lock");
- assertEquals(ResultType.SUCCESS, resultMap.get("status"));
- }
-
- @Test
- public void Test4_accquireLock() throws Exception {
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Map<String, Object> resultMap = (Map<String, Object>) lock.accquireLock(lockId,"1","1",authorization, null, appName).getEntity();
- assertEquals(ResultType.SUCCESS, resultMap.get("status"));
- }
-
- @Test
- public void Test5_currentLockHolder() throws Exception {
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Map<String, Object> resultMap = (Map<String, Object>) lock.currentLockHolder(lockName,"1","1",authorization, null, appName).getEntity();
- assertEquals(ResultType.SUCCESS, resultMap.get("status"));
- }
-
- @Test
- public void Test7_unLock() throws Exception {
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Map<String, Object> resultMap = (Map<String, Object>) lock.unLock(lockId,"1","1",authorization, null, appName).getEntity();
- assertEquals(ResultType.SUCCESS, resultMap.get("status"));
- }
-
- @Test
- public void Test8_delete() throws Exception {
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Map<String, Object> resultMap = (Map<String, Object>) lock.deleteLock(lockName,"1","1", null,authorization, appName).getEntity();
- assertEquals(ResultType.SUCCESS, resultMap.get("status"));
- }
-
- // Version api
- @Test
- public void Test1_version( ) {
- RestMusicVersionAPI versionapi = new RestMusicVersionAPI();
- HttpServletResponse servletResponse = Mockito.mock(HttpServletResponse.class);
- Map<String, Object> resultMap = versionapi.version(servletResponse);
- assertEquals(ResultType.SUCCESS, resultMap.get("status"));
- }
-
- //Music Test Api
- @Test
- public void Test2_testAPI() {
- RestMusicTestAPI musicTest = new RestMusicTestAPI();
- HttpServletResponse servletResponse = Mockito.mock(HttpServletResponse.class);
- Map<String, HashMap<String, String>> resultMap = musicTest.simpleTests(servletResponse);
- assertNotNull(resultMap);
- }
-
- //Music Health Check
- @Test
- public void Test3_HealthCheck_cassandra() {
- String consistency = "ONE";
- RestMusicHealthCheckAPI healthCheck = new RestMusicHealthCheckAPI();
- HttpServletResponse servletResponse = Mockito.mock(HttpServletResponse.class);
- Response response = healthCheck.cassandraStatus(servletResponse, consistency);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test3_HealthCheck_cassandra_cosistencyQuorum() {
- String consistency = "QUORUM";
- RestMusicHealthCheckAPI healthCheck = new RestMusicHealthCheckAPI();
- HttpServletResponse servletResponse = Mockito.mock(HttpServletResponse.class);
- Response response = healthCheck.cassandraStatus(servletResponse, consistency);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test3_HealthCheck_zookeeper() {
- RestMusicHealthCheckAPI healthCheck = new RestMusicHealthCheckAPI();
- HttpServletResponse servletResponse = Mockito.mock(HttpServletResponse.class);
- Response response = healthCheck.ZKStatus(servletResponse);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test4_pureZKcreate() throws Exception {
- RestMusicBmAPI bmApi = new RestMusicBmAPI();
- bmApi.pureZkCreate("sample");
- }
-
- @Test
- public void Test4_pureZKUpdate() throws Exception {
- RestMusicBmAPI bmApi = new RestMusicBmAPI();
- bmApi.pureZkCreate("sample1");
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> values = new HashMap<>();
- values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
- values.put("emp_name", "testName_create");
- values.put("emp_salary", 500);
- consistencyInfo.put("type", "eventual");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- jsonInsert.setKeyspaceName(keyspaceName);
- jsonInsert.setTableName(tableName);
- jsonInsert.setValues(values);
- bmApi.pureZkUpdate(jsonInsert, "sampleNode1");
- }
-
- @Test
- public void Test4_pureZKGet() throws Exception {
- RestMusicBmAPI bmApi = new RestMusicBmAPI();
- bmApi.pureZkGet("sample");
- }
-
- @Test
- public void Test5_ZKAtomicPut_atomic() throws Exception {
- RestMusicBmAPI bmApi = new RestMusicBmAPI();
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> values = new HashMap<>();
- values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
- values.put("emp_name", "testName_create");
- values.put("emp_salary", 1500);
- consistencyInfo.put("type", "atomic");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- jsonInsert.setKeyspaceName(keyspaceName);
- jsonInsert.setTableName(tableName);
- jsonInsert.setValues(values);
- bmApi.pureZkAtomicPut(jsonInsert, "lockname", "sampleNode1");
- }
-
- @Test
- public void Test5_ZKAtomicPut_atomic_with_delete() throws Exception {
- RestMusicBmAPI bmApi = new RestMusicBmAPI();
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> values = new HashMap<>();
- values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
- values.put("emp_name", "testName_create");
- values.put("emp_salary", 1500);
- consistencyInfo.put("type", "atomic_delete_lock");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- jsonInsert.setKeyspaceName(keyspaceName);
- jsonInsert.setTableName(tableName);
- jsonInsert.setValues(values);
- bmApi.pureZkAtomicPut(jsonInsert, "lockname", "sampleNode1");
- }
-
- @Test
- public void Test5_ZKAtomicGet_atomic() throws Exception {
- RestMusicBmAPI bmApi = new RestMusicBmAPI();
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> values = new HashMap<>();
- values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
- values.put("emp_name", "testName_create");
- values.put("emp_salary", 1500);
- consistencyInfo.put("type", "atomic_delete_lock");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- jsonInsert.setKeyspaceName(keyspaceName);
- jsonInsert.setTableName(tableName);
- jsonInsert.setValues(values);
- bmApi.pureZkAtomicGet(jsonInsert, "lockname", "sampleNode1");
- }
-
- @Test
- public void Test5_ZKAtomicGet_atomic_with_delete() throws Exception {
- RestMusicBmAPI bmApi = new RestMusicBmAPI();
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> values = new HashMap<>();
- values.put("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
- values.put("emp_name", "testName_create");
- values.put("emp_salary", 1500);
- consistencyInfo.put("type", "atomic_delete_lock");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- jsonInsert.setKeyspaceName(keyspaceName);
- jsonInsert.setTableName(tableName);
- jsonInsert.setValues(values);
- bmApi.pureZkAtomicGet(jsonInsert, "lockname", "sampleNode1");
- }
-
- @Test
- public void Test5_updateCassa() throws Exception {
- RestMusicBmAPI bmApi = new RestMusicBmAPI();
- JsonInsert jsonInsert = new JsonInsert();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, Object> values = new HashMap<>();
- values.put("emp_salary", 1500);
- consistencyInfo.put("type", "eventual");
- jsonInsert.setConsistencyInfo(consistencyInfo);
- jsonInsert.setKeyspaceName(keyspaceName);
- jsonInsert.setTableName(tableName);
- jsonInsert.setValues(values);
- MultivaluedMap<String, String> row = new MultivaluedMapImpl();
- row.add("emp_name", "testName_create");
- Mockito.when(info.getQueryParameters()).thenReturn(row);
- bmApi.updateTableCassa(jsonInsert, keyspaceName, tableName, info);
- }
-
- // RestMusicConditional
- @Test
- public void Test5_createTable_conditional() throws Exception {
- JsonTable jsonTable = new JsonTable();
- Map<String, String> consistencyInfo = new HashMap<>();
- Map<String, String> fields = new HashMap<>();
- fields.put("id", "text");
- fields.put("plans", "Map<text,text>");
- fields.put("PRIMARY KEY", "(id)");
- consistencyInfo.put("type", "eventual");
- jsonTable.setConsistencyInfo(consistencyInfo);
- jsonTable.setKeyspaceName(keyspaceName);
- jsonTable.setPrimaryKey("id");
- jsonTable.setTableName(tableNameConditional);
- 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, tableNameConditional);
- System.out.println("#######status is " + response.getStatus());
- System.out.println("Entity" + response.getEntity());
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test6_insertConditional() throws Exception {
- RestMusicConditionalAPI conditionalApi = new RestMusicConditionalAPI();
- JsonConditional json = new JsonConditional();
- json.setPrimaryKey("id");
- json.setPrimaryKeyValue("123|abc|port");
- json.setCasscadeColumnName("plans");
- Map<String, Object> tableValues = new HashMap<>();
- tableValues.put("id", "123|abc|port");
- json.setTableValues(tableValues);
- Map<String, Object> columnData = new HashMap<>();
- Map<String, String> column = new HashMap<>();
- column.put("created", "time");
- columnData.put("key", "P2");
- columnData.put("value", column);
- json.setCasscadeColumnData(columnData);
- Map<String, String> cond = new HashMap<>();
- Map<String, String> cond1 = new HashMap<>();
- Map<String, Map<String, String>> conditions = new HashMap<String, Map<String, String>>();
- cond.put("status", "under-spin-up");
- cond1.put("status", "parked");
- conditions.put("exists", cond);
- conditions.put("nonexists", cond1);
- json.setConditions(conditions);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = conditionalApi.insertConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- appName, authorization, keyspaceName, tableNameConditional, json);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test6_insertConditional_primaryKey_null() throws Exception {
- RestMusicConditionalAPI conditionalApi = new RestMusicConditionalAPI();
- JsonConditional json = new JsonConditional();
- json.setPrimaryKeyValue("123|abc|port");
- json.setCasscadeColumnName("plans");
- Map<String, Object> tableValues = new HashMap<>();
- tableValues.put("id", "123|abc|port");
- json.setTableValues(tableValues);
- Map<String, Object> columnData = new HashMap<>();
- Map<String, String> column = new HashMap<>();
- column.put("created", "time");
- columnData.put("key", "P2");
- columnData.put("value", column);
- json.setCasscadeColumnData(columnData);
- Map<String, String> cond = new HashMap<>();
- Map<String, String> cond1 = new HashMap<>();
- Map<String, Map<String, String>> conditions = new HashMap<String, Map<String, String>>();
- cond.put("status", "under-spin-up");
- cond1.put("status", "parked");
- conditions.put("exists", cond);
- conditions.put("nonexists", cond1);
- json.setConditions(conditions);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = conditionalApi.insertConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- appName, authorization, keyspaceName, tableNameConditional, json);
- assertEquals(401, response.getStatus());
- }
-
- @Test
- public void Test6_insertConditional_wrongAuth() throws Exception {
- RestMusicConditionalAPI conditionalApi = new RestMusicConditionalAPI();
- JsonConditional json = new JsonConditional();
- json.setPrimaryKey("id");
- json.setPrimaryKeyValue("123|abc|port");
- json.setCasscadeColumnName("plans");
- Map<String, Object> tableValues = new HashMap<>();
- tableValues.put("id", "123|abc|port");
- json.setTableValues(tableValues);
- Map<String, Object> columnData = new HashMap<>();
- Map<String, String> column = new HashMap<>();
- column.put("created", "time");
- columnData.put("key", "P2");
- columnData.put("value", column);
- json.setCasscadeColumnData(columnData);
- Map<String, String> cond = new HashMap<>();
- Map<String, String> cond1 = new HashMap<>();
- Map<String, Map<String, String>> conditions = new HashMap<String, Map<String, String>>();
- cond.put("status", "under-spin-up");
- cond1.put("status", "parked");
- conditions.put("exists", cond);
- conditions.put("nonexists", cond1);
- json.setConditions(conditions);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = conditionalApi.insertConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- appName, wrongAuthorization, keyspaceName, tableNameConditional, json);
- assertEquals(401, response.getStatus());
- }
-
- @Test
- public void Test7_updateConditional() throws Exception {
- RestMusicConditionalAPI conditionalApi = new RestMusicConditionalAPI();
- JsonConditional json = new JsonConditional();
- json.setPrimaryKey("id");
- json.setPrimaryKeyValue("123|abc|port");
- json.setCasscadeColumnName("plans");
- Map<String, Object> tableValues = new HashMap<>();
- tableValues.put("id", "123|abc|port");
- json.setTableValues(tableValues);
- Map<String, Object> columnData = new HashMap<>();
- Map<String, String> column = new HashMap<>();
- column.put("created", "time");
- columnData.put("key", "P2");
- columnData.put("value", column);
- json.setCasscadeColumnData(columnData);
- Map<String, String> cond = new HashMap<>();
- Map<String, String> cond1 = new HashMap<>();
- Map<String, Map<String, String>> conditions = new HashMap<String, Map<String, String>>();
- cond.put("updated", "new time");
- conditions.put("exists", cond);
- conditions.put("nonexists", cond1);
- json.setConditions(conditions);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = conditionalApi.updateConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- appName, authorization, keyspaceName, tableNameConditional, json);
- assertEquals(200, response.getStatus());
- }
-
- @Test
- public void Test7_updateConditional_wrongAuth() throws Exception {
- RestMusicConditionalAPI conditionalApi = new RestMusicConditionalAPI();
- JsonConditional json = new JsonConditional();
- json.setPrimaryKey("id");
- json.setPrimaryKeyValue("123|abc|port");
- json.setCasscadeColumnName("plans");
- Map<String, Object> tableValues = new HashMap<>();
- tableValues.put("id", "123|abc|port");
- json.setTableValues(tableValues);
- Map<String, Object> columnData = new HashMap<>();
- Map<String, String> column = new HashMap<>();
- column.put("created", "time");
- columnData.put("key", "P2");
- columnData.put("value", column);
- json.setCasscadeColumnData(columnData);
- Map<String, String> cond = new HashMap<>();
- Map<String, String> cond1 = new HashMap<>();
- Map<String, Map<String, String>> conditions = new HashMap<String, Map<String, String>>();
- cond.put("updated", "new time");
- conditions.put("exists", cond);
- conditions.put("nonexists", cond1);
- json.setConditions(conditions);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = conditionalApi.updateConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- appName, wrongAuthorization, keyspaceName, tableNameConditional, json);
- assertEquals(401, response.getStatus());
- }
-
- @Test
- public void Test7_updateConditional_primarykey_null() throws Exception {
- RestMusicConditionalAPI conditionalApi = new RestMusicConditionalAPI();
- JsonConditional json = new JsonConditional();
- json.setPrimaryKeyValue("123|abc|port");
- json.setCasscadeColumnName("plans");
- Map<String, Object> tableValues = new HashMap<>();
- tableValues.put("id", "123|abc|port");
- json.setTableValues(tableValues);
- Map<String, Object> columnData = new HashMap<>();
- Map<String, String> column = new HashMap<>();
- column.put("created", "time");
- columnData.put("key", "P2");
- columnData.put("value", column);
- json.setCasscadeColumnData(columnData);
- Map<String, String> cond = new HashMap<>();
- Map<String, String> cond1 = new HashMap<>();
- Map<String, Map<String, String>> conditions = new HashMap<String, Map<String, String>>();
- cond.put("updated", "new time");
- conditions.put("exists", cond);
- conditions.put("nonexists", cond1);
- json.setConditions(conditions);
- Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
- Response response = conditionalApi.updateConditional("1", "1", "1", "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
- appName, authorization, keyspaceName, tableNameConditional, json);
- assertEquals(401, response.getStatus());
- }
-} \ No newline at end of file
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 69403cc7..00000000
--- a/src/test/java/org/onap/music/unittests/jsonobjects/JsonInsertTest.java
+++ /dev/null
@@ -1,86 +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.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<String,String> 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<String,Object> cons = new HashMap<>();
- cons.put("val1","one");
- cons.put("val2","two");
- ji.setValues(cons);
- assertEquals("one",ji.getValues().get("val1"));
- }
-
- @Test
- public void testGetRow_specification() {
- Map<String,Object> cons = new HashMap<>();
- cons.put("val1","one");
- cons.put("val2","two");
- ji.setRow_specification(cons);
- assertEquals("two",ji.getRow_specification().get("val2"));
- }
-
-
-}
diff --git a/version.properties b/version.properties
index 0b918c88..246c08f5 100755
--- a/version.properties
+++ b/version.properties
@@ -3,8 +3,8 @@
# because they are used in Jenkins, whose plug-in doesn't support
major=3
-minor=0
-patch=19
+minor=2
+patch=40
base_version=${major}.${minor}.${patch}