aboutsummaryrefslogtreecommitdiffstats
path: root/music-rest/src/test
diff options
context:
space:
mode:
Diffstat (limited to 'music-rest/src/test')
-rw-r--r--music-rest/src/test/java/LICENSE.txt24
-rw-r--r--music-rest/src/test/java/org/onap/music/JerseyConfigTest.java39
-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.java247
-rw-r--r--music-rest/src/test/java/org/onap/music/unittests/JsonResponseTest.java167
-rw-r--r--music-rest/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java170
-rw-r--r--music-rest/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java975
-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
24 files changed, 5369 insertions, 0 deletions
diff --git a/music-rest/src/test/java/LICENSE.txt b/music-rest/src/test/java/LICENSE.txt
new file mode 100644
index 00000000..cc6cdea5
--- /dev/null
+++ b/music-rest/src/test/java/LICENSE.txt
@@ -0,0 +1,24 @@
+
+The following license applies to all files in this and sub-directories. Licenses
+are included in individual source files where appropriate, and if it differs
+from this text, it supersedes this. Any file that does not have license text
+defaults to being covered by this text; not all files support the addition of
+licenses.
+#
+# -------------------------------------------------------------------------
+# Copyright (c) 2017 AT&T Intellectual Property
+#
+# Licensed under the Apache License, Version 2.0 (the "License");
+# you may not use this file except in compliance with the License.
+# You may obtain a copy of the License at
+#
+# http://www.apache.org/licenses/LICENSE-2.0
+#
+# Unless required by applicable law or agreed to in writing, software
+# distributed under the License is distributed on an "AS IS" BASIS,
+# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+# See the License for the specific language governing permissions and
+# limitations under the License.
+#
+# -------------------------------------------------------------------------
+# \ No newline at end of file
diff --git a/music-rest/src/test/java/org/onap/music/JerseyConfigTest.java b/music-rest/src/test/java/org/onap/music/JerseyConfigTest.java
new file mode 100644
index 00000000..d7475a9d
--- /dev/null
+++ b/music-rest/src/test/java/org/onap/music/JerseyConfigTest.java
@@ -0,0 +1,39 @@
+/*******************************************************************************
+ * ============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 org.junit.Before;
+import org.junit.Test;
+
+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/music-rest/src/test/java/org/onap/music/unittests/CassandraCQL.java b/music-rest/src/test/java/org/onap/music/unittests/CassandraCQL.java
new file mode 100644
index 00000000..7b116bc8
--- /dev/null
+++ b/music-rest/src/test/java/org/onap/music/unittests/CassandraCQL.java
@@ -0,0 +1,247 @@
+/*
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ * Copyright (c) 2017 AT&T Intellectual Property
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=============================================
+ * ====================================================================
+ */
+
+package org.onap.music.unittests;
+
+/**
+ * @author srupane
+ *
+ */
+
+import java.math.BigInteger;
+import java.net.InetAddress;
+import java.net.NetworkInterface;
+import java.net.SocketException;
+import java.util.ArrayList;
+import java.util.Enumeration;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+
+//import org.apache.thrift.transport.TTransportException;
+import org.cassandraunit.utils.EmbeddedCassandraServerHelper;
+import org.onap.music.datastore.MusicDataStore;
+import org.onap.music.datastore.PreparedQueryObject;
+import org.onap.music.lockingservice.cassandra.LockType;
+import com.datastax.driver.core.Cluster;
+import com.datastax.driver.core.Session;
+import com.datastax.driver.extras.codecs.enums.EnumNameCodec;
+
+public class CassandraCQL {
+ public static final String createAdminKeyspace = "CREATE KEYSPACE admin WITH REPLICATION = "
+ + "{'class' : 'SimpleStrategy' , 'replication_factor': 1} AND DURABLE_WRITES = true";
+
+ public static final String createAdminTable = "CREATE TABLE admin.keyspace_master (" + " uuid uuid, keyspace_name text,"
+ + " application_name text, is_api boolean,"
+ + " password text, username text,"
+ + " is_aaf boolean, PRIMARY KEY (uuid)\n" + ");";
+
+ public static final String createKeySpace =
+ "CREATE KEYSPACE IF NOT EXISTS testcassa WITH replication = "
+ +"{'class':'SimpleStrategy','replication_factor':1} AND durable_writes = true;";
+
+ public static final String dropKeyspace = "DROP KEYSPACE IF EXISTS testcassa";
+
+ public static final String createTableEmployees =
+ "CREATE TABLE IF NOT EXISTS testcassa.employees "
+ + "(vector_ts text,empid uuid,empname text,empsalary varint,address Map<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 (?,?,?,?); ";
+
+ public static final String insertIntoTablePrepared2 =
+ "INSERT INTO testcassa.employees (vector_ts,empid,empname,empsalary,address) VALUES (?,?,?,?,?);";
+
+ public static final String selectALL = "SELECT * FROM testcassa.employees;";
+
+ public static final String selectSpecific =
+ "SELECT * FROM testcassa.employees WHERE empname= ?;";
+
+ public static final String updatePreparedQuery =
+ "UPDATE testcassa.employees SET vector_ts=?,address= ? WHERE empname= ?;";
+
+ public static final String deleteFromTable = " ";
+
+ public static final String deleteFromTablePrepared = " ";
+
+ // Set Values for Prepared Query
+
+ public static List<Object> setPreparedInsertValues1() {
+
+ List<Object> preppreparedInsertValues1 = new ArrayList<>();
+ String vectorTs =
+ String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
+ UUID empId = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40cd6");
+ BigInteger empSalary = BigInteger.valueOf(23443);
+ String empName = "Mr Test one";
+ preppreparedInsertValues1.add(vectorTs);
+ preppreparedInsertValues1.add(empId);
+ preppreparedInsertValues1.add(empName);
+ preppreparedInsertValues1.add(empSalary);
+ return preppreparedInsertValues1;
+ }
+
+ public static List<Object> setPreparedInsertValues2() {
+
+ List<Object> preparedInsertValues2 = new ArrayList<>();
+ String vectorTs =
+ String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
+ UUID empId = UUID.fromString("abc434cc-d657-4e90-b4e5-df4223d40cd6");
+ BigInteger empSalary = BigInteger.valueOf(45655);
+ String empName = "Mr Test two";
+ Map<String, String> address = new HashMap<>();
+ preparedInsertValues2.add(vectorTs);
+ preparedInsertValues2.add(empId);
+ preparedInsertValues2.add(empName);
+ preparedInsertValues2.add(empSalary);
+ address.put("Street", "1 some way");
+ address.put("City", "Some town");
+ preparedInsertValues2.add(address);
+ return preparedInsertValues2;
+ }
+
+ public static List<Object> setPreparedUpdateValues() {
+
+ List<Object> preparedUpdateValues = new ArrayList<>();
+ String vectorTs =
+ String.valueOf(Thread.currentThread().getId() + System.currentTimeMillis());
+ Map<String, String> address = new HashMap<>();
+ preparedUpdateValues.add(vectorTs);
+ String empName = "Mr Test one";
+ address.put("Street", "101 Some Way");
+ address.put("City", "New York");
+ preparedUpdateValues.add(address);
+ preparedUpdateValues.add(empName);
+ return preparedUpdateValues;
+ }
+
+ // Generate Different Prepared Query Objects
+ /**
+ * Query Object for Get.
+ *
+ * @return
+ */
+ public static PreparedQueryObject setPreparedGetQuery() {
+
+ PreparedQueryObject queryObject = new PreparedQueryObject();
+ String empName1 = "Mr Test one";
+ queryObject.appendQueryString(selectSpecific);
+ queryObject.addValue(empName1);
+ return queryObject;
+ }
+
+ /**
+ * Query Object 1 for Insert.
+ *
+ * @return {@link PreparedQueryObject}
+ */
+ public static PreparedQueryObject setPreparedInsertQueryObject1() {
+
+ PreparedQueryObject queryobject = new PreparedQueryObject();
+ queryobject.appendQueryString(insertIntoTablePrepared1);
+ List<Object> values = setPreparedInsertValues1();
+ if (!values.isEmpty() || values != null) {
+ for (Object o : values) {
+ queryobject.addValue(o);
+ }
+ }
+ return queryobject;
+
+ }
+
+ /**
+ * Query Object 2 for Insert.
+ *
+ * @return {@link PreparedQueryObject}
+ */
+ public static PreparedQueryObject setPreparedInsertQueryObject2() {
+
+ PreparedQueryObject queryobject = new PreparedQueryObject();
+ queryobject.appendQueryString(insertIntoTablePrepared2);
+ List<Object> values = setPreparedInsertValues2();
+ if (!values.isEmpty() || values != null) {
+ for (Object o : values) {
+ queryobject.addValue(o);
+ }
+ }
+ return queryobject;
+
+ }
+
+ /**
+ * Query Object for Update.
+ *
+ * @return {@link PreparedQueryObject}
+ */
+ public static PreparedQueryObject setPreparedUpdateQueryObject() {
+
+ PreparedQueryObject queryobject = new PreparedQueryObject();
+ queryobject.appendQueryString(updatePreparedQuery);
+ List<Object> values = setPreparedUpdateValues();
+ if (!values.isEmpty() || values != null) {
+ for (Object o : values) {
+ queryobject.addValue(o);
+ }
+ }
+ return queryobject;
+
+ }
+
+ private static 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) {
+ System.out.println(e.getMessage());
+ }
+ return allPossibleIps;
+ }
+
+ public static MusicDataStore connectToEmbeddedCassandra() throws Exception {
+ System.setProperty("log4j.configuration", "log4j.properties");
+
+ String address = "localhost";
+
+ EmbeddedCassandraServerHelper.startEmbeddedCassandra();
+ Cluster cluster = new Cluster.Builder().withoutJMXReporting().withoutMetrics().addContactPoint(address).withPort(9142).build();
+ cluster.getConfiguration().getSocketOptions().setReadTimeoutMillis(5000);
+ EnumNameCodec<LockType> lockTypeCodec = new EnumNameCodec<LockType>(LockType.class);
+ cluster.getConfiguration().getCodecRegistry().register(lockTypeCodec);
+
+ Session session = cluster.connect();
+
+ return new MusicDataStore(cluster, session);
+ }
+
+}
diff --git a/music-rest/src/test/java/org/onap/music/unittests/JsonResponseTest.java b/music-rest/src/test/java/org/onap/music/unittests/JsonResponseTest.java
new file mode 100644
index 00000000..6af8c0d9
--- /dev/null
+++ b/music-rest/src/test/java/org/onap/music/unittests/JsonResponseTest.java
@@ -0,0 +1,167 @@
+/*
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ * Copyright (c) 2017 AT&T Intellectual Property
+ * ===================================================================
+ * Modifications Copyright (c) 2018-2019 IBM.
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=============================================
+ * ====================================================================
+ */
+
+package org.onap.music.unittests;
+
+import static org.junit.Assert.*;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+import org.junit.Test;
+import org.onap.music.lockingservice.cassandra.MusicLockState.LockStatus;
+import org.onap.music.main.ResultType;
+import org.onap.music.response.jsonobjects.JsonResponse;
+
+public class JsonResponseTest {
+
+ JsonResponse result = null;
+
+ @Test
+ public void testJsonResponseBooleanStringString() {
+ result = new JsonResponse(ResultType.SUCCESS).setError("error").setMusicVersion("version");
+ assertEquals("error",result.getError());
+ }
+
+ @Test
+ public void testStatus() {
+ result = new JsonResponse(ResultType.SUCCESS);
+ result.setStatus(ResultType.SUCCESS);
+ assertEquals(ResultType.SUCCESS, result.getStatus());
+ result = new JsonResponse(ResultType.FAILURE).setError("error").setMusicVersion("version");
+ assertEquals(ResultType.FAILURE, result.getStatus());
+ }
+
+ @Test
+ public void testError() {
+ result = new JsonResponse(ResultType.FAILURE);
+ result.setError("error");
+ assertTrue(result.getError().equals("error"));
+ result.setError("");
+ assertFalse(result.getError().equals("error"));
+ }
+
+ @Test
+ public void testVersion() {
+ result = new JsonResponse(ResultType.SUCCESS);
+ result.setMusicVersion("version");
+ assertTrue(result.getMusicVersion().equals("version"));
+ result.setMusicVersion("");
+ assertFalse(result.getMusicVersion().equals("version"));
+ }
+
+ @Test
+ public void testToMap() {
+ result = new JsonResponse(ResultType.SUCCESS).setError("error").setMusicVersion("1.0");
+ Map<String,Object> myMap = result.toMap();
+ assertTrue(myMap.containsKey("status"));
+ assertEquals(ResultType.SUCCESS, myMap.get("status"));
+ assertEquals("error", myMap.get("error"));
+ assertEquals("1.0", myMap.get("version"));
+
+ result = new JsonResponse(ResultType.FAILURE);
+ myMap = result.toMap();
+ assertTrue(myMap.containsKey("status"));
+ assertEquals(ResultType.FAILURE, myMap.get("status"));
+ }
+
+ @Test
+ public void testMessage() {
+ result = new JsonResponse(ResultType.SUCCESS);
+ result.setMessage("message");
+ assertEquals("message", result.getMessage());
+
+ }
+
+ @Test
+ public void testDataResult() {
+ result = new JsonResponse(ResultType.SUCCESS);
+ Map<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/music-rest/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java b/music-rest/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java
new file mode 100644
index 00000000..68e6f3dc
--- /dev/null
+++ b/music-rest/src/test/java/org/onap/music/unittests/MusicDataStoreTest.java
@@ -0,0 +1,170 @@
+/*
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ * Copyright (c) 2017 AT&T Intellectual Property
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=============================================
+ * ====================================================================
+ */
+
+package org.onap.music.unittests;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.FixMethodOrder;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
+import org.mockito.Mock;
+import org.onap.music.exceptions.MusicQueryException;
+import org.onap.music.exceptions.MusicServiceException;
+import org.springframework.test.context.ActiveProfiles;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
+import org.onap.music.datastore.MusicDataStore;
+import org.onap.music.datastore.PreparedQueryObject;
+
+import com.datastax.driver.core.DataType;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.datastax.driver.core.TableMetadata;
+
+@RunWith(SpringJUnit4ClassRunner.class)
+//@ActiveProfiles(profiles = "OrderRepositoryTest")
+@ContextConfiguration
+public class MusicDataStoreTest {
+
+ static MusicDataStore dataStore;
+ static PreparedQueryObject testObject;
+
+ @BeforeClass
+ public static void init()throws Exception {
+ dataStore = CassandraCQL.connectToEmbeddedCassandra();
+ //CachingUtil.resetStatementBank();
+
+ }
+
+ @AfterClass
+ public static void close() throws MusicServiceException, MusicQueryException {
+
+ testObject = new PreparedQueryObject();
+ testObject.appendQueryString(CassandraCQL.dropKeyspace);
+ dataStore.executePut(testObject, "eventual");
+ //dataStore.close();
+ //CachingUtil.resetStatementBank();
+ }
+
+ @Test
+ public void Test1_SetUp() throws MusicServiceException, MusicQueryException {
+ boolean result = false;
+ //CachingUtil.resetStatementBank();
+ testObject = new PreparedQueryObject();
+ testObject.appendQueryString(CassandraCQL.createKeySpace);
+ result = dataStore.executePut(testObject, "eventual");;
+ testObject = new PreparedQueryObject();
+ testObject.appendQueryString(CassandraCQL.createTableEmployees);
+ result = dataStore.executePut(testObject, "eventual");
+ assertEquals(true, result);
+
+ }
+
+ @Test
+ public void Test2_ExecutePut_eventual_insert() throws MusicServiceException, MusicQueryException {
+ testObject = CassandraCQL.setPreparedInsertQueryObject1();
+ boolean result = dataStore.executePut(testObject, "eventual");
+ assertEquals(true, result);
+ }
+
+ @Test
+ public void Test3_ExecutePut_critical_insert() throws MusicServiceException, MusicQueryException {
+ testObject = CassandraCQL.setPreparedInsertQueryObject2();
+ boolean result = dataStore.executePut(testObject, "Critical");
+ assertEquals(true, result);
+ }
+
+ @Test
+ public void Test4_ExecutePut_eventual_update() throws MusicServiceException, MusicQueryException {
+ testObject = CassandraCQL.setPreparedUpdateQueryObject();
+ boolean result = false;
+ result = dataStore.executePut(testObject, "eventual");
+ assertEquals(true, result);
+ }
+
+ @Test
+ public void Test5_ExecuteEventualGet() throws MusicServiceException, MusicQueryException {
+ testObject = new PreparedQueryObject();
+ testObject.appendQueryString(CassandraCQL.selectALL);
+ boolean result = false;
+ int count = 0;
+ ResultSet output = null;
+ output = dataStore.executeOneConsistencyGet(testObject);
+ System.out.println(output);
+ ;
+ for (Row row : output) {
+ count++;
+ System.out.println(row.toString());
+ }
+ if (count == 2) {
+ result = true;
+ }
+ assertEquals(false, result);
+ }
+
+ @Test
+ public void Test6_ExecuteCriticalGet() throws MusicServiceException, MusicQueryException {
+ testObject = CassandraCQL.setPreparedGetQuery();
+ boolean result = false;
+ int count = 0;
+ ResultSet output = null;
+ output = dataStore.executeQuorumConsistencyGet(testObject);
+ System.out.println(output);
+ ;
+ for (Row row : output) {
+ count++;
+ System.out.println(row.toString());
+ }
+ if (count == 1) {
+ result = true;
+ }
+ assertEquals(false, result);
+ }
+
+ @Test(expected = NullPointerException.class)
+ public void Test7_exception() {
+ PreparedQueryObject queryObject = null;
+ try {
+ dataStore.executePut(queryObject, "critical");
+ } catch (MusicQueryException | MusicServiceException e) {
+ System.out.println(e.getMessage());
+ }
+ }
+
+ @Test
+ public void Test8_columnDataType() {
+ DataType data = dataStore.returnColumnDataType("testCassa", "employees", "empName");
+ String datatype = data.toString();
+ assertEquals("text",datatype);
+ }
+
+ @Test
+ public void Test8_columnMetdaData() {
+ TableMetadata data = dataStore.returnColumnMetadata("testCassa", "employees");
+ assertNotNull(data);
+ }
+}
diff --git a/music-rest/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java b/music-rest/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java
new file mode 100644
index 00000000..385a4698
--- /dev/null
+++ b/music-rest/src/test/java/org/onap/music/unittests/TestRestMusicQAPI.java
@@ -0,0 +1,975 @@
+/*
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ * Copyright (c) 2017 AT&T Intellectual Property
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=============================================
+ * ====================================================================
+ */
+
+package org.onap.music.unittests;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertNotEquals;
+import static org.junit.Assert.assertTrue;
+//cjc import static org.junit.Assert.assertTrue;
+import java.io.File;
+import java.net.URI;
+import java.net.URISyntaxException;
+import java.util.HashMap;
+import java.util.List;
+//cjc import java.util.List;
+import java.util.Map;
+import java.util.UUID;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.Response;
+import javax.ws.rs.core.UriInfo;
+import org.junit.After;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.FixMethodOrder;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.MethodSorters;
+import org.mindrot.jbcrypt.BCrypt;
+//cjcimport org.mindrot.jbcrypt.BCrypt;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.mockito.junit.MockitoJUnitRunner;
+import org.onap.music.datastore.MusicDataStore;
+import org.onap.music.datastore.MusicDataStoreHandle;
+import org.onap.music.datastore.PreparedQueryObject;
+import org.onap.music.datastore.jsonobjects.JsonDelete;
+import org.onap.music.datastore.jsonobjects.JsonInsert;
+import org.onap.music.datastore.jsonobjects.JsonKeySpace;
+//cjc import org.onap.music.datastore.jsonobjects.JsonKeySpace;
+//import org.onap.music.datastore.jsonobjects.JsonOnboard;
+import org.onap.music.datastore.jsonobjects.JsonSelect;
+import org.onap.music.datastore.jsonobjects.JsonTable;
+import org.onap.music.datastore.jsonobjects.JsonUpdate;
+import org.onap.music.lockingservice.cassandra.CassaLockStore;
+import org.onap.music.main.MusicCore;
+import org.onap.music.main.MusicUtil;
+//import org.onap.music.main.ResultType;
+//import org.onap.music.rest.RestMusicAdminAPI;
+import org.onap.music.rest.RestMusicDataAPI;
+import org.onap.music.rest.RestMusicQAPI;
+import org.springframework.test.util.ReflectionTestUtils;
+import org.onap.music.rest.RestMusicLocksAPI;
+import com.datastax.driver.core.DataType;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.sun.jersey.core.util.Base64;
+//import com.datastax.driver.core.DataType;
+//import com.datastax.driver.core.ResultSet;
+//import com.datastax.driver.core.Row;
+import com.sun.jersey.core.util.MultivaluedMapImpl;
+
+@FixMethodOrder(MethodSorters.NAME_ASCENDING)
+@RunWith(MockitoJUnitRunner.class)
+public class TestRestMusicQAPI {
+
+
+ //RestMusicAdminAPI admin = new RestMusicAdminAPI();
+ RestMusicLocksAPI lock = new RestMusicLocksAPI();
+ RestMusicQAPI qData = new RestMusicQAPI();
+ static PreparedQueryObject testObject;
+
+ @Mock
+ static HttpServletResponse http;
+
+ @Mock
+ UriInfo info;
+
+ static String appName = "TestApp";
+ static String userId = "TestUser";
+ static String password = "TestPassword";
+ /*
+ static String appName = "com.att.ecomp.portal.demeter.aid";//"TestApp";
+ static String userId = "m00468@portal.ecomp.att.com";//"TestUser";
+ static String password = "happy123";//"TestPassword";
+ */
+ static String authData = userId+":"+password;
+ static String wrongAuthData = userId+":"+"pass";
+ static String authorization = new String(Base64.encode(authData.getBytes()));
+ static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes()));
+
+ static boolean isAAF = false;
+ static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6");
+ static String uuidS = "abc66ccc-d857-4e90-b1e5-df98a3d40ce6";
+ static String keyspaceName = "testkscjc";
+ static String tableName = "employees";
+ static String xLatestVersion = "X-latestVersion";
+ static String onboardUUID = null;
+ static String lockId = null;
+ static String lockName = "testkscjc.employees.sample3";
+ static String majorV="3";
+ static String minorV="0";
+ static String patchV="1";
+ static String aid=null;
+ static JsonKeySpace kspObject=null;
+ static RestMusicDataAPI data = new RestMusicDataAPI();
+ static Response resp;
+
+ @BeforeClass
+ public static void init() throws Exception {
+ try {
+ ReflectionTestUtils.setField(MusicDataStoreHandle.class, "mDstoreHandle",
+ CassandraCQL.connectToEmbeddedCassandra());
+ MusicCore.setmLockHandle(new CassaLockStore(MusicDataStoreHandle.getDSHandle()));
+
+ // System.out.println("before class keysp");
+ //resp=data.createKeySpace(majorV,minorV,patchV,aid,appName,userId,password,kspObject,keyspaceName);
+ //System.out.println("after keyspace="+keyspaceName);
+ } catch (Exception e) {
+ System.out.println("before class exception ");
+ e.printStackTrace();
+ }
+ // admin keyspace and table
+ testObject = new PreparedQueryObject();
+ testObject.appendQueryString("CREATE KEYSPACE admin WITH REPLICATION = "
+ + "{'class' : 'SimpleStrategy' , "
+ + "'replication_factor': 1} AND DURABLE_WRITES = true");
+ MusicCore.eventualPut(testObject);
+ testObject = new PreparedQueryObject();
+ testObject.appendQueryString(
+ "CREATE TABLE admin.keyspace_master (" + " uuid uuid, keyspace_name text,"
+ + " application_name text, is_api boolean,"
+ + " password text, username text,"
+ + " is_aaf boolean, PRIMARY KEY (uuid)\n" + ");");
+ MusicCore.eventualPut(testObject);
+
+ testObject = new PreparedQueryObject();
+ testObject.appendQueryString(
+ "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
+ + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)");
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(),
+ MusicUtil.DEFAULTKEYSPACENAME));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt())));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
+ MusicCore.eventualPut(testObject);
+
+ testObject = new PreparedQueryObject();
+ testObject.appendQueryString(
+ "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
+ + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)");
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(),
+ UUID.fromString("bbc66ccc-d857-4e90-b1e5-df98a3d40de6")));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(),
+ MusicUtil.DEFAULTKEYSPACENAME));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), "TestApp1"));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt())));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), "TestUser1"));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
+ MusicCore.eventualPut(testObject);
+
+ testObject = new PreparedQueryObject();
+ testObject.appendQueryString(
+ "select uuid from admin.keyspace_master where application_name = ? allow filtering");
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
+ ResultSet rs = MusicCore.get(testObject);
+ List<Row> rows = rs.all();
+ 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<>();
+ consistencyInfo.put("type", "eventual");
+ replicationInfo.put("class", "SimpleStrategy");
+ replicationInfo.put("replication_factor", 1);
+ jsonKeyspace.setConsistencyInfo(consistencyInfo);
+ jsonKeyspace.setDurabilityOfWrites("true");
+ jsonKeyspace.setKeyspaceName(keyspaceName);
+ jsonKeyspace.setReplicationInfo(replicationInfo);
+ Response response = data.createKeySpace(majorV, minorV, patchV, null, authorization, appName,
+ jsonKeyspace, keyspaceName);
+ System.out.println("#######status is " + response.getStatus()+" keyspace="+keyspaceName);
+
+ }
+
+ @AfterClass
+ public static void tearDownAfterClass() throws Exception {
+ System.out.println("After class");
+ testObject = new PreparedQueryObject();
+ testObject.appendQueryString("DROP KEYSPACE IF EXISTS " + keyspaceName);
+ MusicCore.eventualPut(testObject);
+ testObject = new PreparedQueryObject();
+ testObject.appendQueryString("DROP KEYSPACE IF EXISTS admin");
+ MusicCore.eventualPut(testObject);
+ MusicDataStore mds = (MusicDataStore) ReflectionTestUtils.getField(MusicDataStoreHandle.class, "mDstoreHandle");
+ if (mds != null)
+ mds.close();
+ }
+
+
+/* @Test
+ public void Test1_createQ_good() throws Exception {
+ JsonTable jsonTable = new JsonTable();
+ Map<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.setTableName(tableName);
+ jsonTable.setFields(fields);
+ jsonTable.setPartitionKey("emp_name");
+ jsonTable.setClusteringKey("uuid");
+ jsonTable.setClusteringOrder("uuid ASC");
+ //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion);
+ Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableName);
+ // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
+ System.out.println("#######status is " + response.getStatus());
+ System.out.println("Entity" + response.getEntity());
+ assertEquals(200, response.getStatus());
+ }*/
+
+ @Test
+ public void Test1_createQ_FieldsEmpty() throws Exception {
+ JsonTable jsonTable = new JsonTable();
+ Map<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);
+ //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion);
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableName);
+ // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
+ System.out.println("EmptyFields #######status is " + response.getStatus());
+ System.out.println("Entity" + response.getEntity());
+ assertNotEquals(200, response.getStatus());
+ }
+/* @Test
+ public void Test1_createQ_Clustergood() throws Exception {
+ String tableNameC="testcjcC";
+ JsonTable jsonTable = new JsonTable();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> fields = new HashMap<>();
+ fields.put("uuid", "text");
+ fields.put("emp_name", "text");
+ fields.put("emp_id", "text");
+ fields.put("emp_salary", "varint");
+ consistencyInfo.put("type", "eventual");
+ jsonTable.setConsistencyInfo(consistencyInfo);
+ jsonTable.setKeyspaceName(keyspaceName);
+ jsonTable.setPartitionKey("emp_name");
+ jsonTable.setClusteringKey("emp_id");
+ jsonTable.setClusteringOrder("emp_id DESC");
+ jsonTable.setTableName(tableNameC);
+ jsonTable.setFields(fields);
+ Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableNameC);
+ // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
+ System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
+ System.out.println("Entity" + response.getEntity());
+ assertEquals(200, response.getStatus());
+ }*/
+
+/* @Test
+ public void Test1_createQ_ClusterOrderGood1() throws Exception {
+ String tableNameC="testcjcO";
+ JsonTable jsonTable = new JsonTable();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> fields = new HashMap<>();
+ fields.put("uuid", "text");
+ fields.put("emp_name", "text");
+ fields.put("emp_id", "text");
+ fields.put("emp_salary", "varint");
+ fields.put("PRIMARY KEY", "(emp_name,emp_id)");
+ consistencyInfo.put("type", "eventual");
+ jsonTable.setConsistencyInfo(consistencyInfo);
+ jsonTable.setKeyspaceName(keyspaceName);
+ jsonTable.setTableName(tableNameC);
+ jsonTable.setClusteringOrder("emp_id DESC");
+ jsonTable.setFields(fields);
+ Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableNameC);
+ // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
+ System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
+ System.out.println("Entity" + response.getEntity());
+ assertEquals(200, response.getStatus());
+ } */
+
+/* @Test
+ public void Test1_createQ_PartitionKeygood() throws Exception {
+ String tableNameP="testcjcP";
+ JsonTable jsonTable = new JsonTable();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> fields = new HashMap<>();
+ fields.put("uuid", "text");
+ fields.put("emp_name", "text");
+ fields.put("emp_id", "text");
+ fields.put("emp_salary", "varint");
+ fields.put("PRIMARY KEY", "((emp_name,emp_salary),emp_id)");
+ consistencyInfo.put("type", "eventual");
+ jsonTable.setConsistencyInfo(consistencyInfo);
+ jsonTable.setKeyspaceName(keyspaceName);
+ jsonTable.setTableName(tableNameP);
+ jsonTable.setClusteringOrder("emp_id DESC");
+ jsonTable.setFields(fields);
+ Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableNameP);
+ // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
+ System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameP);
+ System.out.println("Entity" + response.getEntity());
+ assertEquals(200, response.getStatus());
+ } */
+
+ @Test
+ public void Test1_createQ_PartitionKeybadclose() throws Exception {
+ String tableNameC="testcjcP1";
+ JsonTable jsonTable = new JsonTable();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> fields = new HashMap<>();
+ fields.put("uuid", "text");
+ fields.put("emp_name", "text");
+ fields.put("emp_id", "text");
+ fields.put("emp_salary", "varint");
+ fields.put("PRIMARY KEY", "((emp_name,emp_salary),emp_id))");
+ consistencyInfo.put("type", "eventual");
+ jsonTable.setConsistencyInfo(consistencyInfo);
+ jsonTable.setKeyspaceName(keyspaceName);
+ jsonTable.setPrimaryKey("emp_name,emp_id");
+ jsonTable.setTableName(tableNameC);
+ jsonTable.setClusteringOrder("emp_id DESC");
+ jsonTable.setFields(fields);
+ //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion);
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableNameC);
+ // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
+ System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
+ System.out.println("Entity" + response.getEntity());
+ //assertEquals(400, response.getStatus());
+ assertTrue(200 != response.getStatus());
+ }
+
+/* @Test
+ public void Test1_createQ_ClusterOrderGood2() throws Exception {
+ String tableNameC="testcjcO1g";
+ JsonTable jsonTable = new JsonTable();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> fields = new HashMap<>();
+ fields.put("uuid", "text");
+ fields.put("emp_name", "text");
+ fields.put("emp_id", "text");
+ fields.put("emp_salary", "varint");
+ fields.put("PRIMARY KEY", "(emp_name,emp_salary,emp_id)");
+ consistencyInfo.put("type", "eventual");
+ jsonTable.setConsistencyInfo(consistencyInfo);
+ jsonTable.setKeyspaceName(keyspaceName);
+ jsonTable.setPrimaryKey("emp_name,emp_id");
+ jsonTable.setTableName(tableNameC);
+ jsonTable.setClusteringOrder("emp_salary ASC,emp_id DESC");
+ jsonTable.setFields(fields);
+ //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion);
+ Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableNameC);
+ // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
+ System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
+ System.out.println("Entity" + response.getEntity());
+ assertEquals(200, response.getStatus());
+ } */
+
+ /* @Test
+ public void Test1_createQ_ColPkeyoverridesPrimaryKeyGood() throws Exception {
+ String tableNameC="testcjcPr";
+ JsonTable jsonTable = new JsonTable();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> fields = new HashMap<>();
+ fields.put("uuid", "text");
+ fields.put("emp_name", "text");
+ fields.put("emp_id", "text");
+ fields.put("emp_salary", "varint");
+ fields.put("PRIMARY KEY", "((emp_name),emp_salary,emp_id)");
+ consistencyInfo.put("type", "eventual");
+ jsonTable.setConsistencyInfo(consistencyInfo);
+ jsonTable.setKeyspaceName(keyspaceName);
+ jsonTable.setPrimaryKey("emp_name,emp_id");
+ jsonTable.setTableName(tableNameC);
+ jsonTable.setClusteringOrder("emp_salary ASC,emp_id DESC");
+ jsonTable.setFields(fields);
+ //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion);
+ Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableNameC);
+ // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
+ System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
+ System.out.println("Entity" + response.getEntity());
+ assertEquals(200, response.getStatus());
+ //assertTrue(200 != response.getStatus());
+ } */
+
+ @Test
+ public void Test1_createQ_ClusterOrderBad() throws Exception {
+ String tableNameC="testcjcO1b";
+ JsonTable jsonTable = new JsonTable();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> fields = new HashMap<>();
+ fields.put("uuid", "text");
+ fields.put("emp_name", "text");
+ fields.put("emp_id", "text");
+ fields.put("emp_salary", "varint");
+ fields.put("PRIMARY KEY", "(emp_name,emp_id)");
+ consistencyInfo.put("type", "eventual");
+ jsonTable.setConsistencyInfo(consistencyInfo);
+ jsonTable.setKeyspaceName(keyspaceName);
+ jsonTable.setPrimaryKey("emp_name,emp_id");
+ jsonTable.setTableName(tableNameC);
+ jsonTable.setClusteringOrder("emp_id DESCx");
+ jsonTable.setFields(fields);
+ //System.out.println("cjc before print version, xLatestVersion="+xLatestVersion);
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableNameC);
+ // "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, userId, password,
+ System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
+ System.out.println("Entity" + response.getEntity());
+ assertEquals(400, response.getStatus());
+ }
+
+
+ @Test
+ public void Test3_createQ_0() throws Exception {
+ //duplicate testing ...
+ JsonTable jsonTable = new JsonTable();
+ Map<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 = qData.createQ(majorV, minorV,patchV,
+ "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
+ jsonTable, keyspaceName, tableNameDup);
+ System.out.println("#######status for 1st time " + response.getStatus());
+ System.out.println("Entity" + response.getEntity());
+
+ Response response0 = qData.createQ(majorV, minorV,patchV,
+ "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
+ jsonTable, keyspaceName, tableNameDup);
+ // 400 is the duplicate status found in response
+ // Music 113 duplicate testing
+ //import static org.junit.Assert.assertNotEquals;
+ System.out.println("#######status for 2nd time " + response0.getStatus());
+ System.out.println("Entity" + response0.getEntity());
+
+ assertFalse("Duplicate table not created for "+tableNameDup, 200==response0.getStatus());
+ //assertEquals(400, response0.getStatus());
+ //assertNotEquals(200,response0.getStatus());
+ }
+
+
+ // Improper keyspace
+ @Ignore
+ @Test
+ public void Test3_createQ2() throws Exception {
+ JsonTable jsonTable = new JsonTable();
+ Map<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.setTableName(tableName);
+ jsonTable.setClusteringKey("emp_salary");
+ jsonTable.setClusteringOrder("emp_salary DESC");
+ jsonTable.setFields(fields);
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
+ jsonTable, "wrong", tableName);
+ System.out.println("#######status is " + response.getStatus());
+ System.out.println("Entity" + response.getEntity());
+ assertEquals(401, response.getStatus());
+ }
+
+
+
+/* @Test
+ public void Test4_insertIntoQ() throws Exception {
+ JsonInsert jsonInsert = new JsonInsert();
+ Map<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 = qData.insertIntoQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
+ appName, authorization, jsonInsert, keyspaceName, tableName);
+ assertEquals(200, response.getStatus());
+ }*/
+
+
+ @Test
+ public void Test4_insertIntoQ_valuesEmpty() throws Exception {
+ JsonInsert jsonInsert = new JsonInsert();
+ Map<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 = qData.insertIntoQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
+ appName, authorization, jsonInsert, keyspaceName, tableName);
+ assertNotEquals(200, response.getStatus());
+ }
+
+/* @Test
+ public void Test4_insertIntoQ2() throws Exception {
+ JsonInsert jsonInsert = new JsonInsert();
+ Map<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, tableName);
+ assertEquals(200, response.getStatus());
+ }*/
+
+
+
+/* @Test
+ public void Test5_updateQ() 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");
+ row.add("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
+ values.put("emp_salary", "2500");
+ consistencyInfo.put("type", "atomic");
+ jsonUpdate.setConsistencyInfo(consistencyInfo);
+ jsonUpdate.setKeyspaceName(keyspaceName);
+ jsonUpdate.setTableName(tableName);
+ jsonUpdate.setValues(values);
+ Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Mockito.when(info.getQueryParameters()).thenReturn(row);
+ Response response = qData.updateQ(majorV, minorV,patchV, "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName,
+ authorization, jsonUpdate, keyspaceName, tableName, info);
+ assertEquals(200, response.getStatus());
+ }*/
+
+ @Test
+ public void Test5_updateQEmptyValues() throws Exception {
+ JsonUpdate jsonUpdate = new JsonUpdate();
+ Map<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<>();
+ MultivaluedMap<String, String> row = new MultivaluedMapImpl();
+ row.add("emp_name", "testName");
+ row.add("uuid", "cfd66ccc-d857-4e90-b1e5-df98a3d40cd6");
+ consistencyInfo.put("type", "atomic");
+ jsonSelect.setConsistencyInfo(consistencyInfo);
+ Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Mockito.when(info.getQueryParameters()).thenReturn(row);
+ Response response = qData.filter(majorV, minorV,patchV,"abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
+ appName, authorization, keyspaceName, tableName, info);
+ HashMap<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_peekQ() throws Exception { //select
+ 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 = qData.peek(majorV, minorV,patchV,"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");
+ 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
+ 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());
+ UriInfo infoe= mockUriInfo("/peek?");//empty queryParam: cause exception
+ // infoe.setQueryParameters("");
+ System.out.println("uriinfo="+infoe.getQueryParameters());
+ Mockito.when(infoe.getQueryParameters()).thenReturn(row);
+ Response response = qData.peek(majorV, minorV,patchV,"abc66ccc-d857-4e90-b1e5-df98a3d40ce6",
+ appName, authorization, keyspaceName, tableName, infoe);
+ HashMap<String,HashMap<String,Object>> map = (HashMap<String, HashMap<String, Object>>) response.getEntity();
+ HashMap<String, Object> result = map.get("result");
+ 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_deleteFromQ1() 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 = qData.deleteFromQ(majorV, minorV,patchV,
+ "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
+ jsonDelete, keyspaceName, tableName, info);
+ assertEquals(200, response.getStatus());
+ }*/
+
+ // Values
+ @Test
+ @Ignore
+ public void Test6_deleteFromQ() throws Exception {
+ JsonDelete jsonDelete = new JsonDelete();
+ Map<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 = qData.deleteFromQ(majorV, minorV,patchV,
+ "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
+ jsonDelete, keyspaceName, tableName, info);
+ assertEquals(400, response.getStatus());
+ }
+
+ // delObj
+ @Test
+ public void Test6_deleteFromQ2() throws Exception {
+ JsonDelete jsonDelete = new JsonDelete();
+ Map<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 = qData.deleteFromQ(majorV, minorV,patchV,
+ "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
+ null, keyspaceName, tableName, info);
+ assertEquals(400, response.getStatus());
+ }
+/*
+ @Test
+ public void Test7_dropQ() throws Exception {
+ JsonTable jsonTable = new JsonTable();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ consistencyInfo.put("type", "atomic");
+ jsonTable.setConsistencyInfo(consistencyInfo);
+ Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.dropQ(majorV, minorV,patchV,
+ "abc66ccc-d857-4e90-b1e5-df98a3d40ce6", appName, authorization,
+ keyspaceName, tableName);
+ assertEquals(200, response.getStatus());
+ }*/
+
+ private UriInfo mockUriInfo(String urix) throws URISyntaxException {
+ String uri="http://localhost:8080/MUSIC/rest/v"+majorV+"/priorityq/keyspaces/"+keyspaceName+"/"+tableName+urix;
+ UriInfo uriInfo = Mockito.mock(UriInfo.class);
+ System.out.println("mock urix="+urix+" uri="+uri);
+ Mockito.when(uriInfo.getRequestUri()).thenReturn(new URI(uri));
+ return uriInfo;
+ }
+
+
+ //Empty Fields
+ @Test
+ public void Test8_createQ_fields_empty() throws Exception {
+ String tableNameC="testcjcC";
+ JsonTable jsonTable = new JsonTable();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ consistencyInfo.put("type", "eventual");
+ jsonTable.setConsistencyInfo(consistencyInfo);
+ jsonTable.setKeyspaceName(keyspaceName);
+ jsonTable.setPartitionKey("emp_name");
+ jsonTable.setClusteringKey("emp_id");
+ jsonTable.setClusteringOrder("emp_id DESC");
+ jsonTable.setTableName(tableNameC);
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableNameC);
+ System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
+ System.out.println("Entity" + response.getEntity());
+ assertEquals(400, response.getStatus());
+ }
+
+ //Partition key null
+ @Test
+ public void Test8_createQ_partitionKey_empty() throws Exception {
+ String tableNameC="testcjcC";
+ JsonTable jsonTable = new JsonTable();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> fields = new HashMap<>();
+ fields.put("uuid", "text");
+ fields.put("emp_name", "text");
+ fields.put("emp_id", "text");
+ fields.put("emp_salary", "varint");
+ consistencyInfo.put("type", "eventual");
+ jsonTable.setConsistencyInfo(consistencyInfo);
+ jsonTable.setKeyspaceName(keyspaceName);
+ jsonTable.setClusteringKey("emp_id");
+ jsonTable.setClusteringOrder("emp_id DESC");
+ jsonTable.setTableName(tableNameC);
+ jsonTable.setFields(fields);
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableNameC);
+ System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
+ System.out.println("Entity" + response.getEntity());
+ assertEquals(400, response.getStatus());
+ }
+
+ //Clustering key null
+ @Test
+ public void Test8_createQ_ClusteringKey_empty() throws Exception {
+ String tableNameC="testcjcC";
+ JsonTable jsonTable = new JsonTable();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> fields = new HashMap<>();
+ fields.put("uuid", "text");
+ fields.put("emp_name", "text");
+ fields.put("emp_id", "text");
+ fields.put("emp_salary", "varint");
+ consistencyInfo.put("type", "eventual");
+ jsonTable.setConsistencyInfo(consistencyInfo);
+ jsonTable.setKeyspaceName(keyspaceName);
+ jsonTable.setPartitionKey("emp_name");
+ jsonTable.setClusteringOrder("emp_id DESC");
+ jsonTable.setTableName(tableNameC);
+ jsonTable.setFields(fields);
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableNameC);
+ System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
+ System.out.println("Entity" + response.getEntity());
+ assertEquals(400, response.getStatus());
+ }
+
+ //Clustering Order null
+ @Test
+ public void Test8_createQ_ClusteringOrder_empty() throws Exception {
+ String tableNameC="testcjcC";
+ JsonTable jsonTable = new JsonTable();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> fields = new HashMap<>();
+ fields.put("uuid", "text");
+ fields.put("emp_name", "text");
+ fields.put("emp_id", "text");
+ fields.put("emp_salary", "varint");
+ consistencyInfo.put("type", "eventual");
+ jsonTable.setConsistencyInfo(consistencyInfo);
+ jsonTable.setKeyspaceName(keyspaceName);
+ jsonTable.setPartitionKey("emp_name");
+ jsonTable.setClusteringKey("emp_id");
+ jsonTable.setTableName(tableNameC);
+ jsonTable.setFields(fields);
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableNameC);
+ System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
+ System.out.println("Entity" + response.getEntity());
+ assertEquals(400, response.getStatus());
+ }
+
+ //Invalid primary key
+ @Test
+ public void Test8_createQ_primaryKey_invalid() throws Exception {
+ String tableNameC="testcjcC";
+ JsonTable jsonTable = new JsonTable();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> fields = new HashMap<>();
+ fields.put("uuid", "text");
+ fields.put("emp_name", "text");
+ fields.put("emp_id", "text");
+ fields.put("emp_salary", "varint");
+ consistencyInfo.put("type", "eventual");
+ jsonTable.setConsistencyInfo(consistencyInfo);
+ jsonTable.setPrimaryKey("(emp_name");
+ jsonTable.setKeyspaceName(keyspaceName);
+ jsonTable.setClusteringKey("emp_id");
+ jsonTable.setClusteringOrder("emp_id ASC");
+ jsonTable.setTableName(tableNameC);
+ jsonTable.setFields(fields);
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableNameC);
+ System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
+ System.out.println("Entity" + response.getEntity());
+ assertEquals(400, response.getStatus());
+ }
+
+ //Primary key with no clustering key
+ @Test
+ public void Test8_createQ_primaryKey_with_empty_clusteringKey() throws Exception {
+ String tableNameC="testcjcC";
+ JsonTable jsonTable = new JsonTable();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> fields = new HashMap<>();
+ fields.put("uuid", "text");
+ fields.put("emp_name", "text");
+ fields.put("emp_id", "text");
+ fields.put("emp_salary", "varint");
+ consistencyInfo.put("type", "eventual");
+ jsonTable.setConsistencyInfo(consistencyInfo);
+ jsonTable.setKeyspaceName(keyspaceName);
+ jsonTable.setPrimaryKey("emp_name");
+ jsonTable.setTableName(tableNameC);
+ jsonTable.setFields(fields);
+ jsonTable.setClusteringOrder("emp_id ASC");
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableNameC);
+ System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
+ System.out.println("Entity" + response.getEntity());
+ assertEquals(400, response.getStatus());
+
+ }
+
+ //Primary key with no partition key
+ @Test
+ public void Test8_createQ_primaryKey_with_empty_partitionKey() throws Exception {
+ String tableNameC="testcjcC";
+ JsonTable jsonTable = new JsonTable();
+ Map<String, String> consistencyInfo = new HashMap<>();
+ Map<String, String> fields = new HashMap<>();
+ fields.put("uuid", "text");
+ fields.put("emp_name", "text");
+ fields.put("emp_id", "text");
+ fields.put("emp_salary", "varint");
+ consistencyInfo.put("type", "eventual");
+ jsonTable.setConsistencyInfo(consistencyInfo);
+ jsonTable.setKeyspaceName(keyspaceName);
+ jsonTable.setPrimaryKey(" ");
+ jsonTable.setTableName(tableNameC);
+ jsonTable.setFields(fields);
+ jsonTable.setClusteringOrder("emp_id ASC");
+
+ //Mockito.doNothing().when(http).addHeader(xLatestVersion, MusicUtil.getVersion());
+ Response response = qData.createQ(majorV, minorV,patchV,
+ aid, appName, authorization,
+ jsonTable, keyspaceName, tableNameC);
+ System.out.println("#######status is " + response.getStatus()+"table namec="+tableNameC);
+ System.out.println("Entity" + response.getEntity());
+ assertEquals(400, response.getStatus());
+ }
+
+}
diff --git a/music-rest/src/test/java/org/onap/music/unittests/TestsUsingCassandra.java b/music-rest/src/test/java/org/onap/music/unittests/TestsUsingCassandra.java
new file mode 100644
index 00000000..cc7c5146
--- /dev/null
+++ b/music-rest/src/test/java/org/onap/music/unittests/TestsUsingCassandra.java
@@ -0,0 +1,116 @@
+/*
+ * ============LICENSE_START==========================================
+ * org.onap.music
+ * ===================================================================
+ * Copyright (c) 2019 AT&T Intellectual Property
+ * ===================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ *
+ * ============LICENSE_END=============================================
+ * ====================================================================
+ */
+
+package org.onap.music.unittests;
+
+import java.util.List;
+import java.util.UUID;
+import org.junit.AfterClass;
+import org.junit.BeforeClass;
+import org.junit.runner.RunWith;
+import org.junit.runners.Suite;
+import org.junit.runners.Suite.SuiteClasses;
+import org.mindrot.jbcrypt.BCrypt;
+import org.onap.music.datastore.MusicDataStore;
+import org.onap.music.datastore.MusicDataStoreHandle;
+import org.onap.music.datastore.PreparedQueryObject;
+import org.onap.music.lockingservice.cassandra.CassaLockStore;
+import org.onap.music.main.MusicCore;
+import org.onap.music.main.MusicUtil;
+import org.springframework.test.util.ReflectionTestUtils;
+import com.datastax.driver.core.DataType;
+import com.datastax.driver.core.ResultSet;
+import com.datastax.driver.core.Row;
+import com.sun.jersey.core.util.Base64;
+
+@RunWith(Suite.class)
+@SuiteClasses({ TstRestMusicDataAPI.class, TstRestMusicLockAPI.class,
+ TstRestMusicConditionalAPI.class})
+public class TestsUsingCassandra {
+
+ static String appName = "TestApp";
+ static String userId = "TestUser";
+ static String password = "TestPassword";
+ static String authData = userId+":"+password;
+ static String wrongAuthData = userId+":"+"pass";
+ static String authorization = new String(Base64.encode(authData.getBytes()));
+ static String wrongAuthorization = new String(Base64.encode(wrongAuthData.getBytes()));
+ static boolean isAAF = false;
+ static UUID uuid = UUID.fromString("abc66ccc-d857-4e90-b1e5-df98a3d40ce6");
+ static String keyspaceName = "testcassa";
+ static String tableName = "employees";
+ static String xLatestVersion = "X-latestVersion";
+ static String onboardUUID = null;
+ static String aid = "abc66ccc-d857-4e90-b1e5-df98a3d40ce6";
+
+ @BeforeClass
+ public static void beforeClass() throws Exception {
+ ReflectionTestUtils.setField(MusicDataStoreHandle.class, "mDstoreHandle",
+ CassandraCQL.connectToEmbeddedCassandra());
+ MusicCore.setmLockHandle(new CassaLockStore(MusicDataStoreHandle.getDSHandle()));
+ createAdminTable();
+ }
+
+ @AfterClass
+ public static void afterClass() {
+ PreparedQueryObject testObject = new PreparedQueryObject();
+ testObject.appendQueryString("DROP KEYSPACE IF EXISTS admin");
+ MusicCore.eventualPut(testObject);
+ MusicDataStore mds = (MusicDataStore) ReflectionTestUtils.getField(MusicDataStoreHandle.class, "mDstoreHandle");
+ if (mds != null)
+ mds.close();
+ }
+
+ private static void createAdminTable() throws Exception {
+ PreparedQueryObject testObject = new PreparedQueryObject();
+ testObject.appendQueryString(CassandraCQL.createAdminKeyspace);
+ MusicCore.eventualPut(testObject);
+ testObject = new PreparedQueryObject();
+ testObject.appendQueryString(CassandraCQL.createAdminTable);
+ MusicCore.eventualPut(testObject);
+
+ testObject = new PreparedQueryObject();
+ testObject.appendQueryString(
+ "INSERT INTO admin.keyspace_master (uuid, keyspace_name, application_name, is_api, "
+ + "password, username, is_aaf) VALUES (?,?,?,?,?,?,?)");
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.uuid(), uuid));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(),
+ keyspaceName));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), "True"));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), BCrypt.hashpw(password, BCrypt.gensalt())));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), userId));
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.cboolean(), isAAF));
+ MusicCore.eventualPut(testObject);
+
+ testObject = new PreparedQueryObject();
+ testObject.appendQueryString(
+ "select uuid from admin.keyspace_master where application_name = ? allow filtering");
+ testObject.addValue(MusicUtil.convertToActualDataType(DataType.text(), appName));
+ ResultSet rs = MusicCore.get(testObject);
+ List<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>