diff options
author | dave.adams (da490c) <dave.adams@amdocs.com> | 2017-12-19 18:02:57 -0500 |
---|---|---|
committer | dave.adams (da490c) <dave.adams@amdocs.com> | 2017-12-19 23:13:38 -0500 |
commit | 9eb9e258f0ab06a516f6d88d1aedc36fc22aeeaf (patch) | |
tree | 7894072e9da7cc6dc557126df7bf27f2ee08a183 /src/test/java/org/onap | |
parent | 05e74c6879ab564181e7cf92e4444d17cc7e25d4 (diff) |
UI Exensibility config cleanup
Change-Id: I65cd9c92a04bad3ea4858fd70a697373671727b5
Signed-off-by: dave.adams (da490c) <dave.adams@amdocs.com>
Issue-ID: AAI-542
Diffstat (limited to 'src/test/java/org/onap')
72 files changed, 3337 insertions, 4940 deletions
diff --git a/src/test/java/org/onap/aai/sparky/analytics/HistoricalCounterTest.java b/src/test/java/org/onap/aai/sparky/analytics/HistoricalCounterTest.java index aa0b0b0..e375979 100644 --- a/src/test/java/org/onap/aai/sparky/analytics/HistoricalCounterTest.java +++ b/src/test/java/org/onap/aai/sparky/analytics/HistoricalCounterTest.java @@ -8,64 +8,63 @@ import org.junit.Test; import org.onap.aai.sparky.analytics.HistoricalCounter;
public class HistoricalCounterTest {
-
-
- private HistoricalCounter historicalCounter;
- private HistoricalCounter historicalCount;
-
- @Before
- public void init() throws Exception {
- historicalCounter = new HistoricalCounter(true);
- historicalCount = new HistoricalCounter(false);
- }
-
- @Test
- public void successfullInitialization() {
- assertEquals(-1, historicalCounter.getMin(), 0);
- assertEquals(0, historicalCounter.getMax(), 0);
- assertEquals(0, historicalCounter.getNumSamples(), 0);
- assertEquals(0, historicalCounter.getNumSamples(), 0);
- assertEquals(0.0, historicalCounter.getValue(), 0);
- assertEquals(0, historicalCounter.getAvg(), 0);
- assertTrue(historicalCounter.isSingleValue());
-
- }
-
- @Test
- public void updateValuesAndReset() {
- historicalCounter.update(-1);
- assertEquals(0, historicalCounter.getValue(), 0);
- historicalCounter.update(10);
- assertEquals(10, historicalCounter.getValue(), 0);
- historicalCounter.reset();
- assertEquals(-1, historicalCounter.getMin(), 0);
- assertEquals(0, historicalCounter.getMax(), 0);
- assertEquals(0, historicalCounter.getNumSamples(), 0);
- assertEquals(0, historicalCounter.getNumSamples(), 0);
- assertEquals(0.0, historicalCounter.getValue(), 0);
-
- }
-
- @Test
- public void updateValues() {
- historicalCount.update(2);
- assertEquals(2, historicalCount.getMin(), 0);
- historicalCount.setMin(10);
- historicalCount.update(3);
- assertEquals(3, historicalCount.getMin(), 0);
- historicalCount.setMax(1);
- historicalCount.update(4);
- assertEquals(4, historicalCount.getMax(), 0);
- historicalCount.setTotalOfSamples(10);
- historicalCount.setNumSamples(2);
- assertEquals(5, historicalCount.getAvg(), 0);
- historicalCount.setTotalOfSamples(10);
- assertEquals(10, historicalCount.getTotalOfSamples(), 0);
- historicalCount.setMaintainSingleValue(true);
- assertTrue(historicalCounter.isSingleValue());
-
- }
-
-
+
+
+ private HistoricalCounter historicalCounter;
+ private HistoricalCounter historicalCount;
+ @Before
+ public void init() throws Exception {
+ historicalCounter = new HistoricalCounter(true);
+ historicalCount = new HistoricalCounter(false);
+ }
+
+ @Test
+ public void successfullInitialization() {
+ assertEquals(-1, historicalCounter.getMin(),0);
+ assertEquals(0, historicalCounter.getMax(),0);
+ assertEquals(0, historicalCounter.getNumSamples(),0);
+ assertEquals(0, historicalCounter.getNumSamples(),0);
+ assertEquals(0.0, historicalCounter.getValue(),0);
+ assertEquals(0, historicalCounter.getAvg(),0);
+ assertTrue(historicalCounter.isSingleValue());
+
+ }
+
+ @Test
+ public void updateValuesAndReset() {
+ historicalCounter.update(-1);
+ assertEquals(0, historicalCounter.getValue(),0);
+ historicalCounter.update(10);
+ assertEquals(10, historicalCounter.getValue(),0);
+ historicalCounter.reset();
+ assertEquals(-1, historicalCounter.getMin(),0);
+ assertEquals(0, historicalCounter.getMax(),0);
+ assertEquals(0, historicalCounter.getNumSamples(),0);
+ assertEquals(0, historicalCounter.getNumSamples(),0);
+ assertEquals(0.0, historicalCounter.getValue(),0);
+
+ }
+
+ @Test
+ public void updateValues() {
+ historicalCount.update(2);
+ assertEquals(2, historicalCount.getMin(),0);
+ historicalCount.setMin(10);
+ historicalCount.update(3);
+ assertEquals(3, historicalCount.getMin(),0);
+ historicalCount.setMax(1);
+ historicalCount.update(4);
+ assertEquals(4, historicalCount.getMax(),0);
+ historicalCount.setTotalOfSamples(10);
+ historicalCount.setNumSamples(2);
+ assertEquals(5, historicalCount.getAvg(),0);
+ historicalCount.setTotalOfSamples(10);
+ assertEquals(10, historicalCount.getTotalOfSamples(),0);
+ historicalCount.setMaintainSingleValue(true);
+ assertTrue(historicalCounter.isSingleValue());
+
+ }
+
+
}
diff --git a/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryConfigTest.java b/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryConfigTest.java deleted file mode 100644 index 8a162a9..0000000 --- a/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryConfigTest.java +++ /dev/null @@ -1,160 +0,0 @@ -/** - * ============LICENSE_START=================================================== SPARKY (AAI UI - * service) ============================================================================ Copyright © - * 2017 AT&T Intellectual Property. Copyright © 2017 Amdocs All rights reserved. - * ============================================================================ Licensed under the - * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. ============LICENSE_END===================================================== - * - * ECOMP and OpenECOMP are trademarks and service marks of AT&T Intellectual Property. - */ -package org.onap.aai.sparky.dal.aai.config; -/* - * import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import - * static org.junit.Assert.assertNull; import static org.junit.Assert.assertTrue; - * - * import org.junit.Before; import org.junit.Test; import - * org.onap.aai.sparky.dal.aai.config.ActiveInventoryConfig; import - * org.onap.aai.sparky.dal.aai.config.ActiveInventoryRestConfig; import - * org.onap.aai.sparky.dal.aai.config.ActiveInventorySslConfig; import - * org.onap.aai.sparky.dal.aai.enums.RestAuthenticationMode; - * - * public class ActiveInventoryConfigTest { - * - * /** Test case initialization - * - * @throws Exception the exception - * - * @Before public void init() throws Exception {} - * - * @Test public void validateBasicConstruction_emptyProperties() throws Exception { - * - * ActiveInventoryConfig config = new - * ActiveInventoryConfig(ActiveInventoryConfigUtil.getValidTestProperties()); - * - * assertNotNull(config); - * - * } - * - * @Test public void validateAccessors() throws Exception { - * - * ActiveInventoryConfig config = new - * ActiveInventoryConfig(ActiveInventoryConfigUtil.getValidTestProperties()); - * - * ActiveInventoryRestConfig airc = config.getAaiRestConfig(); ActiveInventorySslConfig sslConfig = - * config.getAaiSslConfig(); - * - * assertNotNull(airc); assertNotNull(sslConfig); - * - * assertTrue(config.toString().contains("ActiveInventoryConfig")); - * - * config.setAaiRestConfig(null); config.setAaiSslConfig(null); - * - * assertNull(config.getAaiRestConfig()); assertNull(config.getAaiSslConfig()); - * - * config.setAaiRestConfig(airc); config.setAaiSslConfig(sslConfig); - * - * - * } - * - * @Test public void validateRepairSelfLink_nullLink() throws Exception { - * - * ActiveInventoryConfig config = new - * ActiveInventoryConfig(ActiveInventoryConfigUtil.getValidTestProperties()); - * - * ActiveInventoryRestConfig restConfig = config.getAaiRestConfig(); - * - * restConfig.setAuthenticationMode(RestAuthenticationMode.UNKNOWN_MODE); - * restConfig.setHost("aai-host"); restConfig.setPort("9191"); - * - * - * } - * - * @Test public void validateRepairSelfLink_emptyString() throws Exception { - * - * ActiveInventoryConfig config = new - * ActiveInventoryConfig(ActiveInventoryConfigUtil.getValidTestProperties()); - * - * ActiveInventoryRestConfig restConfig = config.getAaiRestConfig(); - * - * restConfig.setAuthenticationMode(RestAuthenticationMode.UNKNOWN_MODE); - * restConfig.setHost("aai-host"); restConfig.setPort("9191"); - * - * - * } - * - * @Test public void validateRepairSelfLink_withSpacesAndSlashesInUrl() throws Exception { - * - * ActiveInventoryConfig config = new - * ActiveInventoryConfig(ActiveInventoryConfigUtil.getValidTestProperties()); - * - * ActiveInventoryRestConfig restConfig = config.getAaiRestConfig(); - * - * restConfig.setAuthenticationMode(RestAuthenticationMode.SSL_CERT); - * restConfig.setHost("aai-host"); restConfig.setPort("9191"); - * - * /* assertEquals( - * "https://aai-host:9191/aai/v11/network/logical-links/logical-link/alrga392ve2%20-%20xe-%2010%2F3%2F2.270%7Car4ga01pbg", - * config.repairSelfLink( - * "/aai/v11/network/logical-links/logical-link/alrga392ve2%20-%20xe-%2010%2F3%2F2.270%7Car4ga01pbg" - * ));* } - * - * @Test public void validateRepairSelfLink_withResourceUrl() throws Exception { - * - * ActiveInventoryConfig config = new - * ActiveInventoryConfig(ActiveInventoryConfigUtil.getValidTestProperties()); - * - * ActiveInventoryRestConfig restConfig = config.getAaiRestConfig(); - * - * restConfig.setAuthenticationMode(RestAuthenticationMode.SSL_CERT); - * restConfig.setHost("aai-host"); restConfig.setPort("9191"); - * - * /* assertEquals("https://aai-host:9191/aai/v11/business/customers/customer/1234", - * config.repairSelfLink("/aai/v11/business/customers/customer/1234"));* } - * - * @Test public void validateRepairSelfLink_withQueryParametersInUrl() throws Exception { - * ActiveInventoryConfig config = new - * ActiveInventoryConfig(ActiveInventoryConfigUtil.getValidTestProperties()); - * - * ActiveInventoryRestConfig restConfig = config.getAaiRestConfig(); - * - * restConfig.setAuthenticationMode(RestAuthenticationMode.SSL_CERT); - * restConfig.setHost("aai-host"); restConfig.setPort("9191"); - * - * /* - * assertEquals("https://aai-host:9191/aai/v11/business/customers/customer/1234?depth=0&nodes-only", - * config.repairSelfLink("/aai/v11/business/customers/customer/1234", "?depth=0&nodes-only"));* } - * - * @Test public void validateResourcePathExtraction() throws Exception { // https with API version - * assertEquals("/aai/v11/business/customers/customer/1234", ActiveInventoryConfig - * .extractResourcePath("https://aai-host:9191/aai/v11/business/customers/customer/1234")); - * - * // https without API version assertEquals("/business/customers/customer/1234", - * ActiveInventoryConfig - * .extractResourcePath("https://aai-host:9191/business/customers/customer/1234")); - * - * // http with API version assertEquals("/aai/v11/business/customers/customer/1234", - * ActiveInventoryConfig - * .extractResourcePath("http://aai-host:9191/aai/v11/business/customers/customer/1234")); - * - * // http without API verison assertEquals("/business/customers/customer/1234", - * ActiveInventoryConfig - * .extractResourcePath("http://aai-host:9191/business/customers/customer/1234")); - * - * // no scheme, host, or port assertEquals("business/customers/customer/1234", - * ActiveInventoryConfig .extractResourcePath("business/customers/customer/1234")); - * - * // no scheme, host, or port with API version - * assertEquals("/aai/v11/business/customers/customer/1234", ActiveInventoryConfig - * .extractResourcePath("/aai/v11/business/customers/customer/1234")); - * - * // no scheme, host, or port with API version assertEquals("", ActiveInventoryConfig - * .extractResourcePath("")); } } - */ diff --git a/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryConfigUtil.java b/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryConfigUtil.java deleted file mode 100644 index 5453852..0000000 --- a/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryConfigUtil.java +++ /dev/null @@ -1,87 +0,0 @@ -package org.onap.aai.sparky.dal.aai.config; - -import java.util.Properties; - -public class ActiveInventoryConfigUtil { - - public static Properties getinvalidTestProperties() { - - Properties props = new Properties(); - - props.put("aai.idle.host", "aai-host"); - - return props; - } - - public static Properties getValidTestProperties() { - - Properties props = new Properties(); - - props.put("aai.rest.host", "aai-host"); - props.put("aai.rest.port", "8443"); - props.put("aai.rest.connectTimeoutInMs", "30000"); - props.put("aai.rest.readTimeoutInMs", "60000"); - props.put("aai.rest.numRequestRetries", "5"); - props.put("aai.rest.numResolverWorkers", "15"); - - props.put("aai.rest.cache.enabled", "false"); - props.put("aai.rest.cache.numWorkers", "10"); - props.put("aai.rest.cache.cacheFailures", "false"); - props.put("aai.rest.cache.useCacheOnly", "false"); - props.put("aai.rest.cache.storageFolderOverride", ""); - props.put("aai.rest.cache.maxTimeToLiveInMs", "-1"); - - props.put("aai.rest.shallowEntities", "cloud-region,complex,vnf-image,att-aic,image"); - - props.put("aai.ssl.truststore.filename", "synchronizer.jks"); - props.put("aai.ssl.truststore.type", "jks"); - - props.put("aai.ssl.keystore.filename", "aai-client-cert.p12"); - props.put("aai.ssl.keystore.pass", "70c87528c88dcd9f9c2558d30e817868"); - props.put("aai.ssl.keystore.type", "pkcs12"); - - props.put("aai.ssl.enableDebug", "false"); - props.put("aai.ssl.validateServerHostName", "false"); - props.put("aai.ssl.validateServerCertificateChain", "false"); - - props.put("aai.rest.authenticationMode", "SSL_CERT"); - props.put("aai.ssl.basicAuth.username", ""); - props.put("aai.ssl.basicAuth.password", ""); - - props.put("aai.taskProcessor.maxConcurrentWorkers", "5"); - - props.put("aai.taskProcessor.transactionRateControllerEnabled", "false"); - props.put("aai.taskProcessor.numSamplesPerThreadForRunningAverage", "100"); - props.put("aai.taskProcessor.targetTPS", "100"); - - props.put("aai.taskProcessor.bytesHistogramLabel", "[Response Size In Bytes]"); - props.put("aai.taskProcessor.bytesHistogramMaxYAxis", "1000000"); - props.put("aai.taskProcessor.bytesHistogramNumBins", "20"); - props.put("aai.taskProcessor.bytesHistogramNumDecimalPoints", "2"); - - props.put("aai.taskProcessor.queueLengthHistogramLabel", "[Queue Item Length]"); - props.put("aai.taskProcessor.queueLengthHistogramMaxYAxis", "20000"); - props.put("aai.taskProcessor.queueLengthHistogramNumBins", "20"); - props.put("aai.taskProcessor.queueLengthHistogramNumDecimalPoints", "2"); - - props.put("aai.taskProcessor.taskAgeHistogramLabel", "[Task Age In Ms]"); - props.put("aai.taskProcessor.taskAgeHistogramMaxYAxis", "600000"); - props.put("aai.taskProcessor.taskAgeHistogramNumBins", "20"); - props.put("aai.taskProcessor.taskAgeHistogramNumDecimalPoints", "2"); - - props.put("aai.taskProcessor.responseTimeHistogramLabel", "[Response Time In Ms]"); - props.put("aai.taskProcessor.responseTimeHistogramMaxYAxis", "10000"); - props.put("aai.taskProcessor.responseTimeHistogramNumBins", "20"); - props.put("aai.taskProcessor.responseTimeHistogramNumDecimalPoints", "2"); - - props.put("aai.taskProcessor.tpsHistogramLabel", "[Transactions Per Second]"); - props.put("aai.taskProcessor.tpsHistogramMaxYAxis", "100"); - props.put("aai.taskProcessor.tpsHistogramNumBins", "20"); - props.put("aai.taskProcessor.tpsHistogramNumDecimalPoints", "2"); - - - return props; - - - } -} diff --git a/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryRestConfigTest.java b/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryRestConfigTest.java deleted file mode 100644 index 77e268b..0000000 --- a/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventoryRestConfigTest.java +++ /dev/null @@ -1,194 +0,0 @@ -/** - * ============LICENSE_START=================================================== SPARKY (AAI UI - * service) ============================================================================ Copyright © - * 2017 AT&T Intellectual Property. Copyright © 2017 Amdocs All rights reserved. - * ============================================================================ Licensed under the - * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. ============LICENSE_END===================================================== - * - * ECOMP and OpenECOMP are trademarks and service marks of AT&T Intellectual Property. - */ - -package org.onap.aai.sparky.dal.aai.config; -/* - * import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertFalse; import - * static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static - * org.junit.Assert.assertTrue; - * - * import java.util.ArrayList; import java.util.List; import java.util.Properties; - * - * import org.junit.Before; import org.junit.Test; import - * org.onap.aai.sparky.dal.aai.config.ActiveInventoryRestConfig; import - * org.onap.aai.sparky.dal.aai.enums.RestAuthenticationMode; - * - * - * public class ActiveInventoryRestConfigTest { - * - * /** Test case initialization - * - * @throws Exception the exception - * - * @Before public void init() throws Exception {} - * - * private Properties buildExpectedPropertyDefinition() throws Exception { - * - * Properties props = new Properties(); - * - * props.put("aai.rest.resourceBasePath", "/aai/v9"); props.put("aai.rest.host", "1.2.3.4"); - * props.put("aai.rest.port", "4321"); props.put("aai.rest.numRequestRetries", "100"); - * props.put("aai.rest.numResolverWorkers", "50"); props.put("aai.rest.maxConcurrentWorkers", "50"); - * props.put("aai.rest.connectTimeoutInMs", "1000"); props.put("aai.rest.readTimeoutInMs", "1500"); - * props.put("aai.rest.shallowEntities", "a,b,c,d"); props.put("aai.rest.authenticationMode", - * "HTTP_NOAUTH"); - * - * props.put("aai.rest.cache.enabled", "true"); props.put("aai.rest.cache.storageFolderOverride", - * "folderOverride"); props.put("aai.rest.cache.cacheFailures", "true"); - * props.put("aai.rest.cache.useCacheOnly", "true"); props.put("aai.rest.cache.numWorkers", "50"); - * props.put("aai.rest.cache.maxTimeToLiveInMs", "500"); - * - * - * return props; } - * - * /** Success path initialization and validation of accessors - * - * @throws Exception - * - * @Test public void successfulInitialization() throws Exception { - * - * ActiveInventoryRestConfig config = new - * ActiveInventoryRestConfig(buildExpectedPropertyDefinition()); - * - * /* Now verify that all the internal members have been set to default values - * - * - * assertEquals(config.getHost(), "1.2.3.4"); assertEquals(config.getPort(), "4321"); - * assertEquals(config.getNumRequestRetries(), 100); assertEquals(config.getNumResolverWorkers(), - * 50); assertEquals(config.getConnectTimeoutInMs(), 1000); - * assertEquals(config.getReadTimeoutInMs(), 1500); - * - * List<String> expectedEntities = new ArrayList<String>(); expectedEntities.add("a"); - * expectedEntities.add("b"); expectedEntities.add("c"); expectedEntities.add("d"); - * - * assertEquals(config.getShallowEntities().size(), 4); - * assertTrue(config.getShallowEntities().containsAll(expectedEntities)); - * assertEquals(config.getAuthenticationMode(), RestAuthenticationMode.HTTP_NOAUTH); - * - * } - * - * /** Failed path initialization - * - * @throws Exception - * - * @Test public void validateInitializationWithNullProperties() throws Exception { - * - * /* Setup encryptor expectations - * - * - * ActiveInventoryRestConfig config = new ActiveInventoryRestConfig(null); - * - * /* Now verify that all the internal members have been set to default values - * - * - * assertNull(config.getHost()); assertNull(config.getPort()); - * assertEquals(config.getNumRequestRetries(), 0); assertEquals(config.getNumResolverWorkers(), 0); - * assertEquals(config.getConnectTimeoutInMs(), 0); assertEquals(config.getReadTimeoutInMs(), 0); - * - * assertNull(config.getShallowEntities()); assertNull(config.getAuthenticationMode()); - * - * } - * - * /** Failed path initialization - * - * @throws Exception - * - * @Test public void validateInitializationWithInvalidProperties() throws Exception { - * - * /* Setup encryptor expectations - * - * - * ActiveInventoryRestConfig config = new - * ActiveInventoryRestConfig(ActiveInventoryConfigUtil.getinvalidTestProperties()); - * - * /* Now verify that all the internal members have been set to default values - * - * - * assertEquals(config.getHost(), "localhost"); assertEquals(config.getPort(), "8443"); - * assertEquals(config.getNumRequestRetries(), 5); assertEquals(config.getNumResolverWorkers(), 15); - * assertEquals(config.getConnectTimeoutInMs(), 5000); assertEquals(config.getReadTimeoutInMs(), - * 10000); - * - * assertEquals(config.getShallowEntities().size(), 1); assertEquals(config.getAuthenticationMode(), - * RestAuthenticationMode.SSL_CERT); - * - * } - * - * /** Class accessor validator - * - * @throws Exception - * - * @Test public void validateClassAccessors() throws Exception { - * - * /* Setup encryptor expectations - * - * - * ActiveInventoryRestConfig config = new - * ActiveInventoryRestConfig(buildExpectedPropertyDefinition()); - * - * /* Now verify that all the internal members have been set to default values - * - * - * config.setAuthenticationMode(RestAuthenticationMode.SSL_BASIC); - * config.setConnectTimeoutInMs(1000); config.setHost("myhost"); config.setNumRequestRetries(1500); - * config.setNumResolverWorkers(150); config.setPort("11223344"); config.setReadTimeoutInMs(54321); - * - * assertEquals(config.getHost(), "myhost"); assertEquals(config.getPort(), "11223344"); - * assertEquals(config.getNumRequestRetries(), 1500); assertEquals(config.getNumResolverWorkers(), - * 150); assertEquals(config.getConnectTimeoutInMs(), 1000); - * assertEquals(config.getReadTimeoutInMs(), 54321); - * - * List<String> expectedEntities = new ArrayList<String>(); expectedEntities.add("a"); - * expectedEntities.add("b"); expectedEntities.add("c"); expectedEntities.add("d"); - * - * assertEquals(config.getShallowEntities().size(), 4); - * assertTrue(config.getShallowEntities().containsAll(expectedEntities)); - * assertTrue(config.isShallowEntity("b")); assertFalse(config.isShallowEntity("f")); - * assertFalse(config.isShallowEntity(null)); assertEquals(config.getAuthenticationMode(), - * RestAuthenticationMode.SSL_BASIC); - * - * assertTrue(config.toString().contains("ActiveInventoryRestConfig")); - * - * } - * - * - * /** Validate auth mode edge cases - * - * @throws Exception - * - * @Test public void validateUnknownAuthModeDefaultsToSslCert() throws Exception { - * - * /* Setup encryptor expectations - * - * - * Properties props = buildExpectedPropertyDefinition(); - * props.setProperty("aai.rest.authenticationMode", "invalid mode"); - * props.setProperty("aai.rest.storageFolderOverride", ""); - * - * ActiveInventoryRestConfig config = new ActiveInventoryRestConfig(props); - * - * /* Now verify that all the internal members have been set to default values - * - * - * assertNotNull(config.getShallowEntities()); assertEquals(RestAuthenticationMode.SSL_CERT, - * config.getAuthenticationMode()); - * - * } - * - * } - */ diff --git a/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventorySslConfigTest.java b/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventorySslConfigTest.java deleted file mode 100644 index 1e180af..0000000 --- a/src/test/java/org/onap/aai/sparky/dal/aai/config/ActiveInventorySslConfigTest.java +++ /dev/null @@ -1,266 +0,0 @@ -/** - * ============LICENSE_START=================================================== - * SPARKY (AAI UI service) - * ============================================================================ - * Copyright © 2017 AT&T Intellectual Property. - * Copyright © 2017 Amdocs - * All rights reserved. - * ============================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END===================================================== - * - * ECOMP and OpenECOMP are trademarks - * and service marks of AT&T Intellectual Property. - */ - -package org.onap.aai.sparky.dal.aai.config; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; - -import java.util.Properties; - -import org.eclipse.jetty.util.security.Password; -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.aai.sparky.dal.aai.config.ActiveInventorySslConfig; -import org.onap.aai.sparky.util.Encryptor; - -public class ActiveInventorySslConfigTest { - - private Encryptor encryptorMock = Mockito.mock(Encryptor.class); - - /** - * Test case initialization - * - * @throws Exception the exception - */ - @Before - public void init() throws Exception { - System.setProperty("javax.net.debug", "invalid"); - } - - private Properties buildExpectedPropertyDefinition() throws Exception { - - Properties props = new Properties(); - - props.put("aai.ssl.enableDebug", "false"); - props.put("aai.ssl.validateServerHostName", "false"); - props.put("aai.ssl.validateServiceCertificateChain", "false"); - props.put("aai.ssl.keystore.type", "pkcs12"); - props.put("aai.ssl.keystore.filename", "/opt/app/applocal/etc/cert.crt"); - props.put("aai.ssl.keystore.pass", "OBF:1i9a1u2a1unz1lr61wn51wn11lss1unz1u301i6o"); - props.put("aai.ssl.truststore.type", "jks"); - props.put("aai.ssl.truststore.filename", "/opt/app/applocal/etc/cert.crt"); - props.put("aai.ssl.basicAuth.username", "username"); - props.put("aai.ssl.basicAuth.password", Password.obfuscate("password")); - - return props; - } - - private Properties buildInvalidPropertyDefinition() { - Properties props = new Properties(); - - props.put("aai.ssl.enableDebug", "true"); - props.put("aai.ssl.validateServerHostName", "invalid"); - props.put("aai.ssl.validateServiceCertificateChain", "invalid"); - props.put("aai.ssl.keystore.type", "invalid"); - // props.put("aai.ssl.keystore.filename", ); - props.put("aai.ssl.keystore.pass", "invalid"); - props.put("aai.ssl.truststore.type", "invalid"); - // props.put("aai.ssl.truststore.filename", "/opt/app/applocal/etc/cert.crt"); - props.put("aai.ssl.basicAuth.username", "invalid"); - props.put("aai.ssl.basicAuth.password", "invalid"); - - return props; - } - - private String generateAuthorizationHeaderValue(String username, String password) { - String usernameAndPassword = username + ":" + password; - return "Basic " + java.util.Base64.getEncoder().encodeToString(usernameAndPassword.getBytes()); - } - - /** - * Success path initialization and validation of accessors - * - * @throws Exception - */ - @Test - public void successfulInitialization() throws Exception { - - /* - * Setup encryptor expectations - */ - Mockito.when(encryptorMock.decryptValue(Mockito.anyString())).thenReturn("password"); - - ActiveInventorySslConfig config = - new ActiveInventorySslConfig(buildExpectedPropertyDefinition(), encryptorMock); - - /* - * Now verify that all the internal members have been set to default values - */ - - assertEquals(System.getProperty("javax.net.debug"), ""); - assertFalse(config.isValidateServerHostName()); - assertFalse(config.isValidateServerCertificateChain()); - - assertEquals(config.getKeystoreType(), "pkcs12"); - assertTrue(config.getKeystoreFilename().contains("/opt/app/applocal/etc/cert.crt")); - assertEquals(config.getKeystorePassword(), "password"); - - assertEquals(config.getTruststoreType(), "jks"); - assertTrue(config.getTruststoreFilename().contains("/opt/app/applocal/etc/cert.crt")); - - assertEquals(config.getBasicAuthUsername(), "username"); - assertEquals(config.getBasicAuthPassword(), "password"); - assertEquals(config.getBasicAuthenticationCredentials(), - generateAuthorizationHeaderValue("username", "password")); - - } - - /** - * Failed path initialization - * - * @throws Exception - */ - @Test - public void validateInitializationWithNullProperties() throws Exception { - - /* - * Setup encryptor expectations - */ - Mockito.when(encryptorMock.decryptValue(Mockito.anyString())).thenReturn(""); - - ActiveInventorySslConfig config = new ActiveInventorySslConfig(null, encryptorMock); - - /* - * Now verify that all the internal members have been set to default values - */ - - assertEquals(System.getProperty("javax.net.debug"), "invalid"); - assertFalse(config.isValidateServerHostName()); - assertFalse(config.isValidateServerCertificateChain()); - - assertNull(config.getKeystoreType()); - assertNull(config.getKeystoreFilename()); - assertNull(config.getKeystorePassword()); - - assertNull(config.getTruststoreType()); - assertNull(config.getTruststoreFilename()); - - assertNull(config.getBasicAuthUsername()); - assertNull(config.getBasicAuthPassword()); - assertEquals(config.getBasicAuthenticationCredentials(), - generateAuthorizationHeaderValue("null", "null")); - - } - - /** - * Failed path initialization - * - * @throws Exception - */ - @Test - public void validateInitializationWithInvalidProperties() throws Exception { - - /* - * Setup encryptor expectations - */ - Mockito.when(encryptorMock.decryptValue(Mockito.anyString())).thenReturn(""); - - ActiveInventorySslConfig config = - new ActiveInventorySslConfig(buildInvalidPropertyDefinition(), encryptorMock); - - /* - * Now verify that all the internal members have been set to default values - */ - - assertEquals(System.getProperty("javax.net.debug"), "ssl"); - assertFalse(config.isValidateServerHostName()); - assertFalse(config.isValidateServerCertificateChain()); - - assertEquals(config.getKeystoreType(), "invalid"); - assertTrue(config.getKeystoreFilename().contains("null")); - assertEquals(config.getKeystorePassword(), ""); - - assertEquals(config.getTruststoreType(), "invalid"); - assertTrue(config.getTruststoreFilename().contains("null")); - - assertEquals(config.getBasicAuthUsername(), "invalid"); - assertEquals(config.getBasicAuthPassword(), "invalid"); - assertEquals(config.getBasicAuthenticationCredentials(), - generateAuthorizationHeaderValue("invalid", "invalid")); - - } - - /** - * Class accessor validator - * - * @throws Exception - */ - @Test - public void validateClassAccessors() throws Exception { - - /* - * Setup encryptor expectations - */ - Mockito.when(encryptorMock.decryptValue(Mockito.anyString())).thenReturn("password"); - - ActiveInventorySslConfig config = - new ActiveInventorySslConfig(buildInvalidPropertyDefinition(), encryptorMock); - - /* - * Now verify that all the internal members have been set to default values - */ - - config.setBasicAuthPassword("test"); - config.setBasicAuthUsername("test"); - config.setKeystoreFilename("test"); - config.setKeystorePassword("test"); - config.setKeystoreType("test"); - config.setTruststoreFilename("test"); - config.setTruststoreType("test"); - config.setEncryptor(encryptorMock); - config.setValidateServerCertificateChain(true); - config.setValidateServerHostName(true); - - assertEquals(System.getProperty("javax.net.debug"), "ssl"); - assertTrue(config.isValidateServerHostName()); - assertTrue(config.isValidateServerCertificateChain()); - - assertEquals(config.getKeystoreType(), "test"); - assertTrue(config.getKeystoreFilename().contains("test")); - assertEquals(config.getKeystorePassword(), "test"); - - assertEquals(config.getTruststoreType(), "test"); - assertTrue(config.getTruststoreFilename().contains("test")); - - assertEquals(config.getBasicAuthUsername(), "test"); - assertEquals(config.getBasicAuthPassword(), "test"); - assertEquals(config.getBasicAuthenticationCredentials(), - generateAuthorizationHeaderValue("test", "test")); - - assertNotNull(config.getEncryptor()); - - assertTrue(config.toString().contains("ActiveInventorySslConfig")); - - - } - - - -} diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchConfigTest.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchConfigTest.java deleted file mode 100644 index 6f9fde9..0000000 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/ElasticSearchConfigTest.java +++ /dev/null @@ -1,119 +0,0 @@ -/**
- * ============LICENSE_START===================================================
- * SPARKY (AAI UI service)
- * ============================================================================
- * Copyright © 2017 AT&T Intellectual Property.
- * Copyright © 2017 Amdocs
- * All rights reserved.
- * ============================================================================
- * Licensed under the Apache License, Version 2.0 (the "License");
- * you may not use this file except in compliance with the License.
- * You may obtain a copy of the License at
- *
- * http://www.apache.org/licenses/LICENSE-2.0
- *
- * Unless required by applicable law or agreed to in writing, software
- * distributed under the License is distributed on an "AS IS" BASIS,
- * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
- * See the License for the specific language governing permissions and
- * limitations under the License.
- * ============LICENSE_END=====================================================
- *
- * ECOMP and OpenECOMP are trademarks
- * and service marks of AT&T Intellectual Property.
- */
-
-package org.onap.aai.sparky.dal.elasticsearch;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-
-import java.io.File;
-import java.io.IOException;
-
-import javax.servlet.ServletException;
-
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.onap.aai.sparky.dal.elasticsearch.config.ElasticSearchConfig;
-import org.onap.aai.sparky.dal.exception.ElasticSearchOperationException;
-
-/**
- * The Class ElasticSearchConfigTest.
- */
-public class ElasticSearchConfigTest {
-
- private static final String GOOD_MAPPINGS_FILE =
- "{" + "\"properties\": {" + "\"entityType\": {" + "\"type\": \"string\"" + "},"
- + "\"edgeTagQueryEntityFieldName\": {" + "\"type\": \"string\"," + "\"index\": \"no\""
- + "}," + "\"edgeTagQueryEntityFieldValue\": {" + "\"type\": \"string\","
- + "\"index\": \"no\"" + "}," + "\"searchTagIDs\" : {" + "\"type\" : \"string\"" + "},"
- + "\"searchTags\": {" + "\"type\": \"string\"," + "\"analyzer\": \"nGram_analyzer\","
- + "\"search_analyzer\": \"whitespace_analyzer\"}" + "}" + "}";
-
- private static final String GOOD_SETTINGS_FILE = "{\"analysis\": {" + "\"filter\": {"
- + "\"nGram_filter\": {" + "\"type\": \"nGram\"," + "\"min_gram\": 1," + "\"max_gram\": 50,"
- + "\"token_chars\": [" + "\"letter\"," + "\"digit\"," + "\"punctuation\"," + "\"symbol\""
- + "]}}," + "\"analyzer\": {" + "\"nGram_analyzer\": {" + "\"type\": \"custom\","
- + "\"tokenizer\": \"whitespace\"," + "\"filter\": [" + "\"lowercase\"," + "\"asciifolding\","
- + "\"nGram_filter\"]}," + "\"whitespace_analyzer\": {" + "\"type\": \"custom\","
- + "\"tokenizer\": \"whitespace\"," + "\"filter\": [" + "\"lowercase\","
- + "\"asciifolding\"]}}}}";
-
- private static final String BAD_SETTINGS_FILE = "{\"analysis\": {" + "\"filter\": {"
- + "\"nGram_filter\": {" + "\"type\": \"nGram\"," + "\"min_gram\": 1," + "\"max_gram\": 50,"
- + "\"token_chars\": [" + "\"letter\"," + "\"digit\"," + "\"punctuation\"," + "\"symbol\""
- + "]}}," + "\"analyzer\": {" + "\"nGram_analyzer\": {" + "\"type\": \"custom\","
- + "\"tokenizer\": \"whitespace\"," + "\"filter\": [" + "\"lowercase\"," + "\"asciifolding\","
- + "\"nGram_filter\"]}," + "\"whitespace_analyzer\": {" + "\"type\": \"custom\","
- + "\"tokenizer\": \"whitespace\"," + "\"filter\": [" + "\"lowercase\","
- + "\"asciifolding\"]}}";
-
- /**
- * Inits the.
- *
- * @throws Exception the exception
- */
- @Before
- public void init() throws Exception {}
-
- /**
- * Validate accessors.
- *
- * @throws IOException Signals that an I/O exception has occurred.
- * @throws ServletException the servlet exception
- * @throws Exception the exception
- */
- @Test
- public void validateAccessors() throws IOException, ServletException, Exception {
-
- ElasticSearchConfig esConfig = new ElasticSearchConfig();
-
- esConfig.setIpAddress("47.248.10.127");
- esConfig.setHttpPort("8123");
- esConfig.setJavaApiPort("9123");
- esConfig.setIndexName("myIndexName");
- esConfig.setType("myIndexTableType");
- esConfig.setClusterName("ES_AAI_DEV");
- esConfig.setMappingsFileName("d:\\1\\mappings.json");
- esConfig.setSettingsFileName("d:\\1\\settings.json");
-
- ElasticSearchConfig.setConfig(esConfig);
-
- assertEquals(esConfig.getIpAddress(), "47.248.10.127");
- assertEquals(esConfig.getHttpPort(), "8123");
- assertEquals(esConfig.getJavaApiPort(), "9123");
- assertEquals(esConfig.getIndexName(), "myIndexName");
- assertEquals(esConfig.getType(), "myIndexTableType");
- assertEquals(esConfig.getClusterName(), "ES_AAI_DEV");
- assertEquals(esConfig.getMappingsFileName(), "d:\\1\\mappings.json");
- assertEquals(esConfig.getSettingsFileName(), "d:\\1\\settings.json");
-
- String output = esConfig.toString();
-
- assertNotEquals(output, null);
-
- }
-}
diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntity.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntity.java index 66b2021..d01a98e 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntity.java @@ -38,7 +38,7 @@ public class AutoSuggestDocumentEntity { public void setFields(AutoSuggestDocumentEntityFields fields) { this.fields = fields; } - - - + + + } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntityFields.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntityFields.java index 4f561d1..a4b7370 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntityFields.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntityFields.java @@ -37,7 +37,7 @@ public class AutoSuggestDocumentEntityFields { private List<String> input; private PayloadEntity payload; private int weight; - + public AutoSuggestDocumentEntityFields() { input = new ArrayList<String>(); } @@ -73,9 +73,9 @@ public class AutoSuggestDocumentEntityFields { public void setWeight(int weight) { this.weight = weight; } - + public void addInput(String input) { this.input.add(input); } - + } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticHitsEntity.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticHitsEntity.java index cf390a2..7efe4a4 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticHitsEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticHitsEntity.java @@ -28,9 +28,9 @@ import java.util.ArrayList; import java.util.List; public class AutoSuggestElasticHitsEntity { - + private List<AutoSuggestElasticHitEntity> hits; - + public AutoSuggestElasticHitsEntity() { hits = new ArrayList<AutoSuggestElasticHitEntity>(); } @@ -42,7 +42,7 @@ public class AutoSuggestElasticHitsEntity { public void setHits(List<AutoSuggestElasticHitEntity> hits) { this.hits = hits; } - + public void addHit(AutoSuggestElasticHitEntity hit) { this.hits.add(hit); } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticSearchResponse.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticSearchResponse.java index 55472a6..1b096cd 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticSearchResponse.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/AutoSuggestElasticSearchResponse.java @@ -30,19 +30,19 @@ import java.util.Map; import com.fasterxml.jackson.annotation.JsonProperty; public class AutoSuggestElasticSearchResponse { - + private int took; - + @JsonProperty("timed_out") private boolean timedOut; - + @JsonProperty("_shards") - private Map<String, String> shards; - + private Map<String,String> shards; + private AutoSuggestElasticHitsEntity hits; - public AutoSuggestElasticSearchResponse() { - this.shards = new HashMap<String, String>(); + public AutoSuggestElasticSearchResponse(){ + this.shards = new HashMap<String,String>(); } public int getTook() { @@ -68,7 +68,7 @@ public class AutoSuggestElasticSearchResponse { public void setShards(Map<String, String> shards) { this.shards = shards; } - + public void addShard(String name, String value) { shards.put(name, value); } @@ -80,6 +80,6 @@ public class AutoSuggestElasticSearchResponse { public void setHits(AutoSuggestElasticHitsEntity hits) { this.hits = hits; } - - + + } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/BucketEntity.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/BucketEntity.java index c1f567c..69285a2 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/BucketEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/BucketEntity.java @@ -28,19 +28,19 @@ import com.fasterxml.jackson.annotation.JsonProperty; public class BucketEntity { private String key; - + @JsonProperty("doc_count") private int docCount; public BucketEntity() { - + } - + public BucketEntity(String name, int value) { this.key = name; this.docCount = value; } - + public String getKey() { return key; } @@ -56,6 +56,6 @@ public class BucketEntity { public void setDocCount(int docCount) { this.docCount = docCount; } - - -} + + +} diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticHitsEntity.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticHitsEntity.java index e319f80..a5a71b8 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticHitsEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticHitsEntity.java @@ -30,17 +30,17 @@ import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; public class ElasticHitsEntity { - + private int total; @JsonProperty("max_score") private int maxScore; - + private List<ElasticHit> hits; - + public ElasticHitsEntity() { this.hits = new ArrayList<ElasticHit>(); } - + public void addHit(ElasticHit hit) { this.hits.add(hit); } @@ -68,7 +68,7 @@ public class ElasticHitsEntity { public void setHits(List<ElasticHit> hits) { this.hits = hits; } - - + + } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggegrationResponse.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggegrationResponse.java index 6448bf5..8e1b5f1 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggegrationResponse.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggegrationResponse.java @@ -45,7 +45,7 @@ public class ElasticSearchAggegrationResponse { public ElasticSearchAggegrationResponse() { this.shards = new HashMap<String, String>(); - this.aggregations = new HashMap<String, ElasticSearchAggregation>(); + this.aggregations = new HashMap<String,ElasticSearchAggregation>(); } @@ -89,7 +89,7 @@ public class ElasticSearchAggegrationResponse { } public void addShard(String key, String value) { - this.shards.put(key, value); + this.shards.put(key,value); } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggregation.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggregation.java index f8b4eea..a7d9ce7 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggregation.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchAggregation.java @@ -30,15 +30,15 @@ import java.util.List; import com.fasterxml.jackson.annotation.JsonProperty; public class ElasticSearchAggregation { - + @JsonProperty("doc_count_error_upper_bound") private int docCountErrorUpperBound; - + @JsonProperty("sum_other_doc_count") private int sumOtherDocCount; - + private List<BucketEntity> buckets; - + public ElasticSearchAggregation() { buckets = new ArrayList<BucketEntity>(); } @@ -66,7 +66,7 @@ public class ElasticSearchAggregation { public void setBuckets(List<BucketEntity> buckets) { this.buckets = buckets; } - + public void addBucket(BucketEntity bucket) { buckets.add(bucket); } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchCountResponse.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchCountResponse.java index 3b13f04..0d165f3 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchCountResponse.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/ElasticSearchCountResponse.java @@ -33,9 +33,9 @@ public class ElasticSearchCountResponse { private Map<String, String> shards; public ElasticSearchCountResponse() { - this.shards = new HashMap<String, String>(); + this.shards = new HashMap<String,String>(); } - + public int getCount() { return count; } @@ -51,7 +51,7 @@ public class ElasticSearchCountResponse { public void setShards(Map<String, String> shards) { this.shards = shards; } - + public void addShard(String key, String value) { this.shards.put(key, value); } diff --git a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/PayloadEntity.java b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/PayloadEntity.java index 753bbda..a74ac0f 100644 --- a/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/PayloadEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/elasticsearch/entity/PayloadEntity.java @@ -26,6 +26,7 @@ package org.onap.aai.sparky.dal.elasticsearch.entity; public class PayloadEntity { - public PayloadEntity() {} - + public PayloadEntity() { + } + } diff --git a/src/test/java/org/onap/aai/sparky/dal/proxy/processor/AaiUiProxyProcessorTest.java b/src/test/java/org/onap/aai/sparky/dal/proxy/processor/AaiUiProxyProcessorTest.java index 189900c..a783072 100644 --- a/src/test/java/org/onap/aai/sparky/dal/proxy/processor/AaiUiProxyProcessorTest.java +++ b/src/test/java/org/onap/aai/sparky/dal/proxy/processor/AaiUiProxyProcessorTest.java @@ -1,112 +1,143 @@ package org.onap.aai.sparky.dal.proxy.processor; /** - * ============LICENSE_START======================================================= SPARKY (AAI UI - * service) ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. Copyright © 2017 Amdocs All rights reserved. - * ================================================================================ Licensed under - * the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance - * with the License. You may obtain a copy of the License at + * ============LICENSE_START======================================================= + * SPARKY (AAI UI service) + * ================================================================================ + * Copyright © 2017 AT&T Intellectual Property. + * Copyright © 2017 Amdocs + * All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. ============LICENSE_END========================================================= + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= * - * ECOMP and OpenECOMP are trademarks and service marks of AT&T Intellectual Property. + * ECOMP and OpenECOMP are trademarks + * and service marks of AT&T Intellectual Property. */ -/* - * package org.openecomp.sparky.dal.proxy.processor; - * - * import static org.junit.Assert.assertEquals; - * - * import javax.servlet.http.HttpServletRequest; import javax.ws.rs.core.MediaType; - * - * import org.apache.camel.Exchange; import org.apache.camel.Message; import - * org.codehaus.groovy.grails.web.json.JSONObject; import org.junit.Before; import org.junit.Test; - * import org.mockito.AdditionalMatchers; import org.mockito.Matchers; import org.mockito.Mockito; - * import org.onap.aai.restclient.client.OperationResult; import - * org.onap.aai.restclient.client.RestClient; import - * org.openecomp.sparky.dal.proxy.config.DataRouterConfig; import org.restlet.data.Status; - * - * public class AaiUiProxyProcessorTest { - * - * private RestClient client = null; private OperationResult successResult = null; OperationResult - * failureResult = null; private Exchange mockExchange; private Message mockRequestMessage; private - * Message mockResponseMessage; - * - * private HttpServletRequest mockHttpServletRequest; - * - * private AaiUiProxyProcessor aaiUiProxyProcessor; - * - * private String goodBeTargetUrl = "https://0.0.0.0:8000/services/routerService/servicegraph"; - * private String badBeTargetUrl = "https://0.0.0.0:8000/aservicegraph"; private String - * goodDrTargetUrl = "https://0.0.0.0:9502/ui-request/servicegraph"; - * - * String successResponsePayload = "good-payload"; String failureResponsePayload = "Server Error"; - * - * @Before public void init() { client = Mockito.mock(RestClient.class); mockExchange = - * Mockito.mock(Exchange.class); mockRequestMessage = Mockito.mock(Message.class); - * mockResponseMessage = Mockito.mock(Message.class); mockHttpServletRequest = - * Mockito.mock(HttpServletRequest.class); - * - * DataRouterConfig config = new DataRouterConfig(DataRouterConfigUtil.getTestProperties()); - * aaiUiProxyProcessor = new AaiUiProxyProcessor(config); - * - * initializeMocks(getProxyRequestJson("someHashValue")); aaiUiProxyProcessor.setClient(client); } - * - * @Test public void testProxyMessage_successPath() { OperationResult successResultSpy = - * Mockito.spy(successResult); Mockito.when(client.post(Mockito.eq(goodDrTargetUrl), - * Mockito.anyString(), Mockito.anyMap(), Mockito.eq(MediaType.APPLICATION_JSON_TYPE), - * Mockito.eq(MediaType.APPLICATION_JSON_TYPE))) .thenReturn(successResultSpy); - * - * Mockito.when(mockExchange.getIn().getHeader(Exchange.HTTP_URI)).thenReturn(goodBeTargetUrl); - * Mockito.when(mockExchange.getIn().getBody(HttpServletRequest.class)).thenReturn( - * mockHttpServletRequest); aaiUiProxyProcessor.proxyMessage(mockExchange); - * - * Mockito.verify(successResultSpy).getResult(); assertEquals(Status.SUCCESS_OK.getCode(), - * aaiUiProxyProcessor.getOperationResult().getResultCode()); } - * - * @Test public void testProxyMessage_failurePath() { OperationResult failureResultSpy = - * Mockito.spy(failureResult); - * Mockito.when(client.post(AdditionalMatchers.not(Matchers.eq(goodDrTargetUrl)), - * Mockito.anyString(), Mockito.anyMap(), Mockito.eq(MediaType.APPLICATION_JSON_TYPE), - * Mockito.eq(MediaType.APPLICATION_JSON_TYPE))).thenReturn(failureResultSpy); - * - * Mockito.when(mockExchange.getIn().getHeader(Exchange.HTTP_URI)).thenReturn(badBeTargetUrl); - * Mockito.when(mockExchange.getIn().getBody(HttpServletRequest.class)).thenReturn( - * mockHttpServletRequest); aaiUiProxyProcessor.proxyMessage(mockExchange); - * - * Mockito.verify(failureResultSpy).getFailureCause(); - * assertEquals(Status.SERVER_ERROR_INTERNAL.getCode(), - * aaiUiProxyProcessor.getOperationResult().getResultCode()); } - * - * private String getProxyRequestJson(String hashId) { JSONObject root = new JSONObject(); - * root.put("hashId", hashId); return root.toString(); - * - * } - * - * @SuppressWarnings("unchecked") private void initializeMocks(String requestPayload) { - * - * client = Mockito.mock(RestClient.class); successResult = new OperationResult(200, - * successResponsePayload); failureResult = new OperationResult(500, failureResponsePayload); - * failureResult.setFailureCause(failureResponsePayload); - * - * Mockito.when(client.post(Mockito.eq(goodDrTargetUrl), Mockito.anyString(), Mockito.anyMap(), - * Mockito.eq(MediaType.APPLICATION_JSON_TYPE), Mockito.eq(MediaType.APPLICATION_JSON_TYPE))) - * .thenReturn(successResult); - * - * Mockito.when(client.post(AdditionalMatchers.not(Matchers.eq(goodDrTargetUrl)), - * Mockito.anyString(), Mockito.anyMap(), Mockito.eq(MediaType.APPLICATION_JSON_TYPE), - * Mockito.eq(MediaType.APPLICATION_JSON_TYPE))).thenReturn(failureResult); - * - * Mockito.when(mockHttpServletRequest.getRequestURI()).thenReturn("fakeUri"); - * Mockito.when(mockHttpServletRequest.getLocalPort()).thenReturn(8001); - * - * Mockito.when(mockExchange.getIn()).thenReturn(mockRequestMessage); - * Mockito.when(mockExchange.getOut()).thenReturn(mockResponseMessage); } - * - * } - */ +/*package org.openecomp.sparky.dal.proxy.processor; + +import static org.junit.Assert.assertEquals; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.core.MediaType; + +import org.apache.camel.Exchange; +import org.apache.camel.Message; +import org.codehaus.groovy.grails.web.json.JSONObject; +import org.junit.Before; +import org.junit.Test; +import org.mockito.AdditionalMatchers; +import org.mockito.Matchers; +import org.mockito.Mockito; +import org.onap.aai.restclient.client.OperationResult; +import org.onap.aai.restclient.client.RestClient; +import org.openecomp.sparky.dal.proxy.config.DataRouterConfig; +import org.restlet.data.Status; + +public class AaiUiProxyProcessorTest { + + private RestClient client = null; + private OperationResult successResult = null; + OperationResult failureResult = null; + private Exchange mockExchange; + private Message mockRequestMessage; + private Message mockResponseMessage; + + private HttpServletRequest mockHttpServletRequest; + + private AaiUiProxyProcessor aaiUiProxyProcessor; + + private String goodBeTargetUrl = "https://0.0.0.0:8000/services/routerService/servicegraph"; + private String badBeTargetUrl = "https://0.0.0.0:8000/aservicegraph"; + private String goodDrTargetUrl = "https://0.0.0.0:9502/ui-request/servicegraph"; + + String successResponsePayload = "good-payload"; + String failureResponsePayload = "Server Error"; + + @Before + public void init() { + client = Mockito.mock(RestClient.class); + mockExchange = Mockito.mock(Exchange.class); + mockRequestMessage = Mockito.mock(Message.class); + mockResponseMessage = Mockito.mock(Message.class); + mockHttpServletRequest = Mockito.mock(HttpServletRequest.class); + + DataRouterConfig config = new DataRouterConfig(DataRouterConfigUtil.getTestProperties()); + aaiUiProxyProcessor = new AaiUiProxyProcessor(config); + + initializeMocks(getProxyRequestJson("someHashValue")); + aaiUiProxyProcessor.setClient(client); + } + + @Test + public void testProxyMessage_successPath() { + OperationResult successResultSpy = Mockito.spy(successResult); + Mockito.when(client.post(Mockito.eq(goodDrTargetUrl), Mockito.anyString(), Mockito.anyMap(), + Mockito.eq(MediaType.APPLICATION_JSON_TYPE), Mockito.eq(MediaType.APPLICATION_JSON_TYPE))) + .thenReturn(successResultSpy); + + Mockito.when(mockExchange.getIn().getHeader(Exchange.HTTP_URI)).thenReturn(goodBeTargetUrl); + Mockito.when(mockExchange.getIn().getBody(HttpServletRequest.class)).thenReturn(mockHttpServletRequest); + aaiUiProxyProcessor.proxyMessage(mockExchange); + + Mockito.verify(successResultSpy).getResult(); + assertEquals(Status.SUCCESS_OK.getCode(), aaiUiProxyProcessor.getOperationResult().getResultCode()); + } + + @Test + public void testProxyMessage_failurePath() { + OperationResult failureResultSpy = Mockito.spy(failureResult); + Mockito.when(client.post(AdditionalMatchers.not(Matchers.eq(goodDrTargetUrl)), + Mockito.anyString(), Mockito.anyMap(), Mockito.eq(MediaType.APPLICATION_JSON_TYPE), + Mockito.eq(MediaType.APPLICATION_JSON_TYPE))).thenReturn(failureResultSpy); + + Mockito.when(mockExchange.getIn().getHeader(Exchange.HTTP_URI)).thenReturn(badBeTargetUrl); + Mockito.when(mockExchange.getIn().getBody(HttpServletRequest.class)).thenReturn(mockHttpServletRequest); + aaiUiProxyProcessor.proxyMessage(mockExchange); + + Mockito.verify(failureResultSpy).getFailureCause(); + assertEquals(Status.SERVER_ERROR_INTERNAL.getCode(), aaiUiProxyProcessor.getOperationResult().getResultCode()); + } + + private String getProxyRequestJson(String hashId) { + JSONObject root = new JSONObject(); + root.put("hashId", hashId); + return root.toString(); + + } + + @SuppressWarnings("unchecked") + private void initializeMocks(String requestPayload) { + + client = Mockito.mock(RestClient.class); + successResult = new OperationResult(200, successResponsePayload); + failureResult = new OperationResult(500, failureResponsePayload); + failureResult.setFailureCause(failureResponsePayload); + + Mockito.when(client.post(Mockito.eq(goodDrTargetUrl), Mockito.anyString(), Mockito.anyMap(), + Mockito.eq(MediaType.APPLICATION_JSON_TYPE), Mockito.eq(MediaType.APPLICATION_JSON_TYPE))) + .thenReturn(successResult); + + Mockito.when(client.post(AdditionalMatchers.not(Matchers.eq(goodDrTargetUrl)), + Mockito.anyString(), Mockito.anyMap(), Mockito.eq(MediaType.APPLICATION_JSON_TYPE), + Mockito.eq(MediaType.APPLICATION_JSON_TYPE))).thenReturn(failureResult); + + Mockito.when(mockHttpServletRequest.getRequestURI()).thenReturn("fakeUri"); + Mockito.when(mockHttpServletRequest.getLocalPort()).thenReturn(8001); + + Mockito.when(mockExchange.getIn()).thenReturn(mockRequestMessage); + Mockito.when(mockExchange.getOut()).thenReturn(mockResponseMessage); + } + +} +*/ diff --git a/src/test/java/org/onap/aai/sparky/dal/proxy/processor/DataRouterConfigUtil.java b/src/test/java/org/onap/aai/sparky/dal/proxy/processor/DataRouterConfigUtil.java deleted file mode 100644 index ec57f53..0000000 --- a/src/test/java/org/onap/aai/sparky/dal/proxy/processor/DataRouterConfigUtil.java +++ /dev/null @@ -1,50 +0,0 @@ -/** - * ============LICENSE_START======================================================= - * SPARKY (AAI UI service) - * ================================================================================ - * Copyright © 2017 AT&T Intellectual Property. - * Copyright © 2017 Amdocs - * All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - * - * ECOMP and OpenECOMP are trademarks - * and service marks of AT&T Intellectual Property. - */ - -package org.onap.aai.sparky.dal.proxy.processor; - -import java.util.Properties; - -import org.onap.aai.sparky.util.Encryptor; - -public class DataRouterConfigUtil { - - public static Properties getTestProperties() { - Encryptor encryptor = new Encryptor(); - Properties props = new Properties(); - - props.put("data-router.rest.ipAddress", "0.0.0.0"); - props.put("data-router.rest.httpPort", "9999"); - props.put("data-router.rest.uriSuffix", "ui-request"); - props.put("data-router.rest.connectTimeoutMs", "30000"); - props.put("data-router.rest.readTimeoutMs", "60000"); - props.put("data-router.ssl.cert-name", "some-cert-name"); - - props.put("data-router.ssl.keystore-password", - encryptor.encryptValue("some-password-that-is-long")); - props.put("data-router.ssl.keystore", "some-keystore"); - return props; - } -} diff --git a/src/test/java/org/onap/aai/sparky/dal/rest/RestClientBuilderTest.java b/src/test/java/org/onap/aai/sparky/dal/rest/RestClientBuilderTest.java deleted file mode 100644 index b8dcfc9..0000000 --- a/src/test/java/org/onap/aai/sparky/dal/rest/RestClientBuilderTest.java +++ /dev/null @@ -1,178 +0,0 @@ -/** - * ============LICENSE_START=================================================== - * SPARKY (AAI UI service) - * ============================================================================ - * Copyright © 2017 AT&T Intellectual Property. - * Copyright © 2017 Amdocs - * All rights reserved. - * ============================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END===================================================== - * - * ECOMP and OpenECOMP are trademarks - * and service marks of AT&T Intellectual Property. - */ - -package org.onap.aai.sparky.dal.rest; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertFalse; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doReturn; - -import javax.net.ssl.SSLContext; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.Mockito; -import org.mockito.runners.MockitoJUnitRunner; -import org.onap.aai.sparky.dal.rest.RestClientBuilder; -import org.onap.aai.sparky.security.SecurityContextFactory; - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.client.urlconnection.HTTPSProperties; - -/** - * The Class RestClientBuilderTest. - */ -@RunWith(MockitoJUnitRunner.class) -public class RestClientBuilderTest { - - - /** - * Inits the. - * - * @throws Exception the exception - */ - @Before - public void init() throws Exception {} - - /** - * Basic construction test. - * - * @throws Exception the exception - */ - @Test - public void basicConstructionTest() throws Exception { - - RestClientBuilder clientBuilder = new RestClientBuilder(); - - // test constructor defaults - - assertFalse(clientBuilder.isValidateServerHostname()); - assertEquals(60000L, clientBuilder.getConnectTimeoutInMs()); - assertEquals(60000L, clientBuilder.getReadTimeoutInMs()); - assertTrue(clientBuilder.isUseHttps()); - - } - - /** - * Validate accessors. - * - * @throws Exception the exception - */ - @Test - public void validateAccessors() throws Exception { - - RestClientBuilder clientBuilder = new RestClientBuilder(); - - clientBuilder.setConnectTimeoutInMs(12345); - clientBuilder.setReadTimeoutInMs(54321); - clientBuilder.setUseHttps(true); - clientBuilder.setValidateServerHostname(true); - - assertEquals(12345, clientBuilder.getConnectTimeoutInMs()); - assertEquals(54321, clientBuilder.getReadTimeoutInMs()); - assertTrue(clientBuilder.isUseHttps()); - assertTrue(clientBuilder.isValidateServerHostname()); - - } - - /** - * Validate simple client construction. - * - * @throws Exception the exception - */ - @Test - public void validateSimpleClientConstruction() throws Exception { - - RestClientBuilder clientBuilder = new RestClientBuilder(); - clientBuilder.setUseHttps(false); - Client client = clientBuilder.getClient(); - - /* - * Simple client context should not contain HTTPS properties - */ - assertNull(client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES)); - - } - - /** - * Validate secure client construction without host name validation. - * - * @throws Exception the exception - */ - @Test - public void validateSecureClientConstruction_WithoutHostNameValidation() throws Exception { - - RestClientBuilder clientBuilder = new RestClientBuilder(); - clientBuilder.setUseHttps(true); - - SecurityContextFactory sslContextFactory = Mockito.mock(SecurityContextFactory.class); - clientBuilder.setSslContextFactory(sslContextFactory); - - SSLContext sslContext = Mockito.mock(SSLContext.class); - doReturn(sslContext).when(sslContextFactory).getSecureContext(); - - Client client = clientBuilder.getClient(); - - /* - * Secure client context should contain HTTPS properties - */ - assertNotNull(client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES)); - assertNotNull(clientBuilder.getSslContextFactory()); - - } - - /** - * Validate secure client construction with host name validation. - * - * @throws Exception the exception - */ - @Test - public void validateSecureClientConstruction_WithHostNameValidation() throws Exception { - - RestClientBuilder clientBuilder = new RestClientBuilder(); - clientBuilder.setUseHttps(true); - clientBuilder.setValidateServerHostname(true); - - SecurityContextFactory sslContextFactory = Mockito.mock(SecurityContextFactory.class); - clientBuilder.setSslContextFactory(sslContextFactory); - - SSLContext sslContext = Mockito.mock(SSLContext.class); - doReturn(sslContext).when(sslContextFactory).getSecureContext(); - - Client client = clientBuilder.getClient(); - - /* - * Secure client context should contain HTTPS properties - */ - assertNotNull(client.getProperties().get(HTTPSProperties.PROPERTY_HTTPS_PROPERTIES)); - assertNotNull(clientBuilder.getSslContextFactory()); - - } - -} diff --git a/src/test/java/org/onap/aai/sparky/dal/rest/RestfulDataAccessorTest.java b/src/test/java/org/onap/aai/sparky/dal/rest/RestfulDataAccessorTest.java deleted file mode 100644 index 56acc7a..0000000 --- a/src/test/java/org/onap/aai/sparky/dal/rest/RestfulDataAccessorTest.java +++ /dev/null @@ -1,229 +0,0 @@ -/** - * ============LICENSE_START=================================================== - * SPARKY (AAI UI service) - * ============================================================================ - * Copyright © 2017 AT&T Intellectual Property. - * Copyright © 2017 Amdocs - * All rights reserved. - * ============================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END===================================================== - * - * ECOMP and OpenECOMP are trademarks - * and service marks of AT&T Intellectual Property. - */ - -package org.onap.aai.sparky.dal.rest; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Matchers.anyObject; -import static org.mockito.Matchers.anyString; -import static org.mockito.Matchers.same; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.doThrow; -import static org.mockito.Mockito.mock; - -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.runners.MockitoJUnitRunner; -import org.onap.aai.sparky.dal.rest.OperationResult; -import org.onap.aai.sparky.dal.rest.RestClientBuilder; -import org.onap.aai.sparky.dal.rest.RestfulDataAccessor; - -import com.sun.jersey.api.client.Client; -import com.sun.jersey.api.client.ClientResponse; -import com.sun.jersey.api.client.WebResource; -import com.sun.jersey.api.client.WebResource.Builder; - -/** - * The Class RestfulDataAccessorTest. - */ -@RunWith(MockitoJUnitRunner.class) -public class RestfulDataAccessorTest { - - private RestClientBuilder clientBuilderMock; - private Client mockClient; - private ClientResponse mockClientResponse; - private WebResource mockWebResource; - private Builder mockBuilder; - - - /** - * Inits the. - * - * @throws Exception the exception - */ - @Before - public void init() throws Exception { - - /* - * common collaborator mocking setup - */ - - clientBuilderMock = mock(RestClientBuilder.class); - mockClient = mock(Client.class); - mockClientResponse = mock(ClientResponse.class); - mockWebResource = mock(WebResource.class); - mockBuilder = mock(Builder.class); - - doReturn(mockClient).when(clientBuilderMock).getClient(); - doReturn(mockWebResource).when(mockClient).resource(anyString()); - doReturn(mockBuilder).when(mockWebResource).accept(anyString()); - doReturn(mockBuilder).when(mockBuilder).header(anyString(), anyObject()); - - doReturn(mockClientResponse).when(mockBuilder).get(same(ClientResponse.class)); - doReturn(mockClientResponse).when(mockBuilder).put(same(ClientResponse.class), anyObject()); - doReturn(mockClientResponse).when(mockBuilder).post(same(ClientResponse.class), anyObject()); - doReturn(mockClientResponse).when(mockBuilder).delete(same(ClientResponse.class)); - } - - /** - * Successful do put. - * - * @throws Exception the exception - */ - @Test - public void successfulDoPut() throws Exception { - - /* - * set test mocking expectations - */ - - doReturn(200).when(mockClientResponse).getStatus(); - doReturn("Success").when(mockClientResponse).getEntity(String.class); - - // test code - RestfulDataAccessor dataAccessor = new RestfulDataAccessor(clientBuilderMock); - OperationResult actualResult = dataAccessor.doPut("myUrl", "jsonPayload", "acceptContentType"); - - assertEquals("Unexpected result", 200, actualResult.getResultCode()); - } - - /** - * Successful do get. - * - * @throws Exception the exception - */ - @Test - public void successfulDoGet() throws Exception { - - /* - * set test mocking expectations - */ - - doReturn(200).when(mockClientResponse).getStatus(); - doReturn("Success").when(mockClientResponse).getEntity(String.class); - - // test code - RestfulDataAccessor dataAccessor = new RestfulDataAccessor(clientBuilderMock); - OperationResult actualResult = dataAccessor.doGet("myUrl", "anyContentType"); - - assertEquals("Unexpected result", 200, actualResult.getResultCode()); - - } - - /** - * Successful do post. - * - * @throws Exception the exception - */ - @Test - public void successfulDoPost() throws Exception { - - /* - * set test mocking expectations - */ - - doReturn(200).when(mockClientResponse).getStatus(); - doReturn("Success").when(mockClientResponse).getEntity(String.class); - - // test code - RestfulDataAccessor dataAccessor = new RestfulDataAccessor(clientBuilderMock); - OperationResult actualResult = dataAccessor.doPost("myUrl", "jsonPayload", "anyContentType"); - - assertEquals("Unexpected result", 200, actualResult.getResultCode()); - - } - - /** - * Successful do delete. - * - * @throws Exception the exception - */ - @Test - public void successfulDoDelete() throws Exception { - - /* - * set test mocking expectations - */ - - doReturn(200).when(mockClientResponse).getStatus(); - doReturn("Success").when(mockClientResponse).getEntity(String.class); - - // test code - RestfulDataAccessor dataAccessor = new RestfulDataAccessor(clientBuilderMock); - OperationResult actualResult = dataAccessor.doDelete("myUrl", "anyContentType"); - - assertEquals("Unexpected result", 200, actualResult.getResultCode()); - - } - - /** - * Operation results in null pointer exception. - * - * @throws Exception the exception - */ - @Test - public void operationResultsInNullPointerException() throws Exception { - - /* - * set test mocking expectations - */ - - - doThrow(new NullPointerException("Parameter can't be null")).when(clientBuilderMock) - .getClient(); - - // test code - RestfulDataAccessor dataAccessor = new RestfulDataAccessor(clientBuilderMock); - OperationResult actualResult = dataAccessor.doDelete("myUrl", "anyContentType"); - - assertEquals("Unexpected result", 500, actualResult.getResultCode()); - - } - - /** - * Operation results in null client response. - * - * @throws Exception the exception - */ - @Test - public void operationResultsInNullClientResponse() throws Exception { - - /* - * set test mocking expectations - */ - // return null client response - doReturn(null).when(mockBuilder).delete(same(ClientResponse.class)); - - // test code - RestfulDataAccessor dataAccessor = new RestfulDataAccessor(clientBuilderMock); - OperationResult actualResult = dataAccessor.doDelete("myUrl", "anyContentType"); - - assertEquals("Unexpected result", 500, actualResult.getResultCode()); - - } - - -} diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/DocumentEntity.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/DocumentEntity.java index a5c0247..b9349a9 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/DocumentEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/DocumentEntity.java @@ -30,14 +30,14 @@ import java.util.Map; public class DocumentEntity { private String etag; private String url; - private Map<String, String> content; + private Map<String,String> content; public DocumentEntity() { - content = new HashMap<String, String>(); + content = new HashMap<String,String>(); } - - - public String getEtag() { + + + public String getEtag() { return etag; } @@ -60,7 +60,7 @@ public class DocumentEntity { public void setContent(Map<String, String> content) { this.content = content; } - + public void addContent(String key, String value) { content.put(key, value); } diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/EntityCountResponse.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/EntityCountResponse.java index c58fb81..20002d2 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/EntityCountResponse.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/EntityCountResponse.java @@ -28,12 +28,12 @@ import java.util.HashMap; import java.util.Map; public class EntityCountResponse { - - private Map<String, String> shards; + + private Map<String,String> shards; private int count; - + public EntityCountResponse() { - this.shards = new HashMap<String, String>(); + this.shards = new HashMap<String,String>(); } public Map<String, String> getShards() { @@ -51,5 +51,5 @@ public class EntityCountResponse { public void setCount(int count) { this.count = count; } - + } diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationEntity.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationEntity.java index 05e95fe..4a3bbf4 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationEntity.java @@ -32,7 +32,7 @@ import org.onap.aai.sparky.dal.elasticsearch.entity.BucketEntity; public class GroupByAggregationEntity { private int totalChartHits; List<BucketEntity> buckets; - + public GroupByAggregationEntity() { this.buckets = new ArrayList<BucketEntity>(); } diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationResponseEntity.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationResponseEntity.java index 8ad3928..fd2e17d 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationResponseEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/GroupByAggregationResponseEntity.java @@ -30,9 +30,9 @@ public class GroupByAggregationResponseEntity { @JsonProperty("groupby_aggregation") private GroupByAggregationEntity aggEntity; - + public GroupByAggregationResponseEntity() { - + } public GroupByAggregationEntity getAggEntity() { @@ -42,7 +42,7 @@ public class GroupByAggregationResponseEntity { public void setAggEntity(GroupByAggregationEntity aggEntity) { this.aggEntity = aggEntity; } - - - + + + } diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/HitEntity.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/HitEntity.java index eea0437..73b2d12 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/HitEntity.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/HitEntity.java @@ -30,7 +30,7 @@ public class HitEntity { private DocumentEntity document; public String getScore() { - return score; + return score; } public void setScore(String score) { diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionEntityBuilder.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionEntityBuilder.java index f32cbe5..7cfd9c9 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionEntityBuilder.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionEntityBuilder.java @@ -29,9 +29,9 @@ import java.util.List; public class SearchAbstractionEntityBuilder { - + public static HitEntity getHitSample1() { - + HitEntity hitEntity = new HitEntity(); DocumentEntity doc = new DocumentEntity(); @@ -39,23 +39,20 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("17.073963"); doc.addContent("entityPrimaryKeyValue", "example-vnf-id-val-4394"); - doc.addContent("entityType", "vpe"); - doc.addContent("searchTags", - "example-vnf-id-val-4394;example-vnf-name-val-4394;example-vnf-name2-val-4394"); - doc.addContent("link", - "https://aai-ext1.test.att.com:8443/aai/v9/network/vpes/vpe/example-vnf-id-val-4394"); - doc.addContent("searchTagIDs", "0;1;2"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:20:48.072-0400"); - - doc.setUrl( - "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/e317a35256717f10e88d1b2c995efcdddfc911bf350c73e37e8afca6dfb11553"); + doc.addContent("entityType", "vpe"); + doc.addContent("searchTags", "example-vnf-id-val-4394;example-vnf-name-val-4394;example-vnf-name2-val-4394"); + doc.addContent("link", "https://aai-ext1.test.att.com:8443/aai/v9/network/vpes/vpe/example-vnf-id-val-4394"); + doc.addContent("searchTagIDs", "0;1;2"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:20:48.072-0400"); + + doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/e317a35256717f10e88d1b2c995efcdddfc911bf350c73e37e8afca6dfb11553"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample2() { HitEntity hitEntity = new HitEntity(); @@ -65,23 +62,20 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("17.073963"); doc.addContent("entityPrimaryKeyValue", "vpe-vnf-id-team4-11"); - doc.addContent("entityType", "vpe"); - doc.addContent("searchTags", - "vpe-vnf-id-team4-11;example-vnf-name-val-9512;example-vnf-name2-val-9512"); - doc.addContent("link", - "https://aai-ext1.test.att.com:8443/aai/v9/network/vpes/vpe/vpe-vnf-id-team4-11"); - doc.addContent("searchTagIDs", "0;1;2"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:20:48.175-0400"); - - doc.setUrl( - "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/80f6d1a252e047e50e0adbeb90ad30876bb5b63cf70c9dd53f3fe46aeb50c74b"); + doc.addContent("entityType", "vpe"); + doc.addContent("searchTags", "vpe-vnf-id-team4-11;example-vnf-name-val-9512;example-vnf-name2-val-9512"); + doc.addContent("link", "https://aai-ext1.test.att.com:8443/aai/v9/network/vpes/vpe/vpe-vnf-id-team4-11"); + doc.addContent("searchTagIDs", "0;1;2"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:20:48.175-0400"); + + doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/80f6d1a252e047e50e0adbeb90ad30876bb5b63cf70c9dd53f3fe46aeb50c74b"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample3() { HitEntity hitEntity = new HitEntity(); @@ -91,23 +85,20 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("17.030035"); doc.addContent("entityPrimaryKeyValue", "example-vnf-id-val-6176"); - doc.addContent("entityType", "generic-vnf"); - doc.addContent("searchTags", - "example-vnf-id-val-6176;example-vnf-name-val-6176;example-vnf-name2-val-6176"); - doc.addContent("link", - "https://aai-ext1.test.att.com:8443/aai/v9/network/generic-vnfs/generic-vnf/example-vnf-id-val-6176"); - doc.addContent("searchTagIDs", "0;1;2"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:29:39.889-0400"); - - doc.setUrl( - "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/8dfd1136f943296508fee11efcda35a0719aa490aa60e9abffecce0b220d8c94"); + doc.addContent("entityType", "generic-vnf"); + doc.addContent("searchTags", "example-vnf-id-val-6176;example-vnf-name-val-6176;example-vnf-name2-val-6176"); + doc.addContent("link", "https://aai-ext1.test.att.com:8443/aai/v9/network/generic-vnfs/generic-vnf/example-vnf-id-val-6176"); + doc.addContent("searchTagIDs", "0;1;2"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:29:39.889-0400"); + + doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/8dfd1136f943296508fee11efcda35a0719aa490aa60e9abffecce0b220d8c94"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample4() { HitEntity hitEntity = new HitEntity(); @@ -117,23 +108,20 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("17.01174"); doc.addContent("entityPrimaryKeyValue", "vnf-id-team4-11"); - doc.addContent("entityType", "newvce"); - doc.addContent("searchTags", - "vnf-id-team4-11;example-vnf-name-val-5313;example-vnf-name2-val-5313"); - doc.addContent("link", - "https://aai-ext1.test.att.com:8443/aai/v9/network/newvces/newvce/vnf-id-team4-11"); - doc.addContent("searchTagIDs", "0;1;2"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:21:08.142-0400"); - - doc.setUrl( - "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/83dcab92d75b20eb94578039c8cec5e7b6b4717791e3c367d8af5069ce76dc90"); + doc.addContent("entityType", "newvce"); + doc.addContent("searchTags", "vnf-id-team4-11;example-vnf-name-val-5313;example-vnf-name2-val-5313"); + doc.addContent("link", "https://aai-ext1.test.att.com:8443/aai/v9/network/newvces/newvce/vnf-id-team4-11"); + doc.addContent("searchTagIDs", "0;1;2"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:21:08.142-0400"); + + doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/83dcab92d75b20eb94578039c8cec5e7b6b4717791e3c367d8af5069ce76dc90"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample5() { HitEntity hitEntity = new HitEntity(); @@ -143,23 +131,20 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("17.01174"); doc.addContent("entityPrimaryKeyValue", "example-vnf-id2-val-9501"); - doc.addContent("entityType", "newvce"); - doc.addContent("searchTags", - "example-vnf-id2-val-9501;example-vnf-name-val-9501;example-vnf-name2-val-9501"); - doc.addContent("link", - "https://aai-ext1.test.att.com:8443/aai/v9/network/newvces/newvce/example-vnf-id2-val-9501"); - doc.addContent("searchTagIDs", "0;1;2"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:21:23.323-0400"); - - doc.setUrl( - "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/461816ba8aa94d01f2c978999b843dbaf10e0509db58d1945d6f5999d6db8f5e"); + doc.addContent("entityType", "newvce"); + doc.addContent("searchTags", "example-vnf-id2-val-9501;example-vnf-name-val-9501;example-vnf-name2-val-9501"); + doc.addContent("link", "https://aai-ext1.test.att.com:8443/aai/v9/network/newvces/newvce/example-vnf-id2-val-9501"); + doc.addContent("searchTagIDs", "0;1;2"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:21:23.323-0400"); + + doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/461816ba8aa94d01f2c978999b843dbaf10e0509db58d1945d6f5999d6db8f5e"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample6() { HitEntity hitEntity = new HitEntity(); @@ -169,23 +154,20 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("17.01174"); doc.addContent("entityPrimaryKeyValue", "vnf-id-dm-auto-10"); - doc.addContent("entityType", "vce"); - doc.addContent("searchTags", - "vpe-id-dm-auto-10;vnf-id-dm-auto-10;vnf-name-dm-auto-10;vnf-name2-dm-auto-10"); - doc.addContent("link", - "https://aai-ext1.test.att.com:8443/aai/v9/network/vces/vce/vnf-id-dm-auto-10"); - doc.addContent("searchTagIDs", "0;1;2;3"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:24:57.209-0400"); - - doc.setUrl( - "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/1ead4512e65ee0eafb24e0156cc1abdf97368f08dfe065f02580aa09661bbcd8"); + doc.addContent("entityType", "vce"); + doc.addContent("searchTags", "vpe-id-dm-auto-10;vnf-id-dm-auto-10;vnf-name-dm-auto-10;vnf-name2-dm-auto-10"); + doc.addContent("link", "https://aai-ext1.test.att.com:8443/aai/v9/network/vces/vce/vnf-id-dm-auto-10"); + doc.addContent("searchTagIDs", "0;1;2;3"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:24:57.209-0400"); + + doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/1ead4512e65ee0eafb24e0156cc1abdf97368f08dfe065f02580aa09661bbcd8"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample7() { HitEntity hitEntity = new HitEntity(); @@ -195,22 +177,20 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("13.940832"); doc.addContent("entityPrimaryKeyValue", "e3e59c5b-ad48-44d0-b3e4-80eacdcee4c7"); - doc.addContent("entityType", "generic-vnf"); - doc.addContent("searchTags", "e3e59c5b-ad48-44d0-b3e4-80eacdcee4c7;VNF_Test_vNF_modules_01"); - doc.addContent("link", - "https://aai-ext1.test.att.com:8443/aai/v9/network/generic-vnfs/generic-vnf/e3e59c5b-ad48-44d0-b3e4-80eacdcee4c7"); - doc.addContent("searchTagIDs", "0;1"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:26:34.603-0400"); - - doc.setUrl( - "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/1462582e8fd7786f72f26548e4247b72ab6cd101cca0bbb68a60dd3ad16500d0"); + doc.addContent("entityType", "generic-vnf"); + doc.addContent("searchTags", "e3e59c5b-ad48-44d0-b3e4-80eacdcee4c7;VNF_Test_vNF_modules_01"); + doc.addContent("link", "https://aai-ext1.test.att.com:8443/aai/v9/network/generic-vnfs/generic-vnf/e3e59c5b-ad48-44d0-b3e4-80eacdcee4c7"); + doc.addContent("searchTagIDs", "0;1"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:26:34.603-0400"); + + doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/1462582e8fd7786f72f26548e4247b72ab6cd101cca0bbb68a60dd3ad16500d0"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample8() { HitEntity hitEntity = new HitEntity(); @@ -220,22 +200,20 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("13.940832"); doc.addContent("entityPrimaryKeyValue", "fusion-jitsi-vnf-001"); - doc.addContent("entityType", "generic-vnf"); - doc.addContent("searchTags", "fusion-jitsi-vnf-001;fusion-jitsi-vnf"); - doc.addContent("link", - "https://aai-ext1.test.att.com:8443/aai/v9/network/generic-vnfs/generic-vnf/fusion-jitsi-vnf-001"); - doc.addContent("searchTagIDs", "0;1"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:28:14.293-0400"); - - doc.setUrl( - "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/b79ddfec9a00184445174c91e7490a0d407f351983bba4ae53bfec0584f73ee3"); + doc.addContent("entityType", "generic-vnf"); + doc.addContent("searchTags", "fusion-jitsi-vnf-001;fusion-jitsi-vnf"); + doc.addContent("link", "https://aai-ext1.test.att.com:8443/aai/v9/network/generic-vnfs/generic-vnf/fusion-jitsi-vnf-001"); + doc.addContent("searchTagIDs", "0;1"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:28:14.293-0400"); + + doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/b79ddfec9a00184445174c91e7490a0d407f351983bba4ae53bfec0584f73ee3"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample9() { HitEntity hitEntity = new HitEntity(); @@ -245,22 +223,20 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("13.940832"); doc.addContent("entityPrimaryKeyValue", "vnfm0003v"); - doc.addContent("entityType", "generic-vnf"); - doc.addContent("searchTags", "vnfm0003v;vnfm0003v"); - doc.addContent("link", - "https://aai-ext1.test.att.com:8443/aai/v9/network/generic-vnfs/generic-vnf/vnfm0003v"); - doc.addContent("searchTagIDs", "0;1"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:29:39.594-0400"); - - doc.setUrl( - "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/52ae232ea5506d6de8ef35c4f46a1ceafe35f3717ff578b83531bc7615870b12"); + doc.addContent("entityType", "generic-vnf"); + doc.addContent("searchTags", "vnfm0003v;vnfm0003v"); + doc.addContent("link", "https://aai-ext1.test.att.com:8443/aai/v9/network/generic-vnfs/generic-vnf/vnfm0003v"); + doc.addContent("searchTagIDs", "0;1"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:29:39.594-0400"); + + doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/52ae232ea5506d6de8ef35c4f46a1ceafe35f3717ff578b83531bc7615870b12"); doc.setEtag("1"); return hitEntity; } - + public static HitEntity getHitSample10() { HitEntity hitEntity = new HitEntity(); @@ -270,35 +246,33 @@ public class SearchAbstractionEntityBuilder { hitEntity.setScore("13.928098"); doc.addContent("entityPrimaryKeyValue", "amist456vnf"); - doc.addContent("entityType", "generic-vnf"); - doc.addContent("searchTags", "amist456vnf;amist456vnf"); - doc.addContent("link", - "https://aai-ext1.test.att.com:8443/aai/v9/network/generic-vnfs/generic-vnf/amist456vnf"); - doc.addContent("searchTagIDs", "0;1"); - doc.addContent("lastmodTimestamp", "2017-04-18T17:28:28.163-0400"); - - doc.setUrl( - "services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/3424afea5963696380a0fdc78ee5320cf5fa9bc0459f1f9376db208d31196434"); + doc.addContent("entityType", "generic-vnf"); + doc.addContent("searchTags", "amist456vnf;amist456vnf"); + doc.addContent("link", "https://aai-ext1.test.att.com:8443/aai/v9/network/generic-vnfs/generic-vnf/amist456vnf"); + doc.addContent("searchTagIDs", "0;1"); + doc.addContent("lastmodTimestamp", "2017-04-18T17:28:28.163-0400"); + + doc.setUrl("services/search-data-service/v1/search/indexes/entitysearchindex-localhost-ist-apr18/documents/3424afea5963696380a0fdc78ee5320cf5fa9bc0459f1f9376db208d31196434"); doc.setEtag("1"); return hitEntity; } - - - + + + public static SearchAbstractionResponse getSuccessfulEntitySearchResponse() { - + SearchAbstractionResponse sasResponse = new SearchAbstractionResponse(); - + SearchResult searchResult = new SearchResult(); sasResponse.setSearchResult(searchResult); - + searchResult.setTotalHits(3257); - + List<HitEntity> hits = new ArrayList<HitEntity>(); - + hits.add(getHitSample1()); hits.add(getHitSample2()); hits.add(getHitSample3()); @@ -309,12 +283,12 @@ public class SearchAbstractionEntityBuilder { hits.add(getHitSample8()); hits.add(getHitSample9()); hits.add(getHitSample10()); - + searchResult.setHits(hits); - + return sasResponse; - + } - + } diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionResponse.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionResponse.java index f076a17..b937f66 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionResponse.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchAbstractionResponse.java @@ -25,13 +25,13 @@ package org.onap.aai.sparky.dal.sas.entity; public class SearchAbstractionResponse { - + private SearchResult searchResult; public SearchResult getSearchResult() { return searchResult; } - + public void setSearchResult(SearchResult searchResult) { this.searchResult = searchResult; } diff --git a/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchResult.java b/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchResult.java index e0bac78..a656491 100644 --- a/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchResult.java +++ b/src/test/java/org/onap/aai/sparky/dal/sas/entity/SearchResult.java @@ -30,23 +30,20 @@ public class SearchResult { private int totalHits; private List<HitEntity> hits; - + public int getTotalHits() { return totalHits; } - public void setTotalHits(int totalHits) { this.totalHits = totalHits; } - public List<HitEntity> getHits() { return hits; } - public void setHits(List<HitEntity> hits) { this.hits = hits; } - - - + + + } diff --git a/src/test/java/org/onap/aai/sparky/dataintegrity/config/DiUiConstantsTest.java b/src/test/java/org/onap/aai/sparky/dataintegrity/config/DiUiConstantsTest.java deleted file mode 100644 index b955592..0000000 --- a/src/test/java/org/onap/aai/sparky/dataintegrity/config/DiUiConstantsTest.java +++ /dev/null @@ -1,65 +0,0 @@ -package org.onap.aai.sparky.dataintegrity.config; - -import static org.junit.Assert.assertEquals; - -import org.junit.Before; -import org.junit.Test; -import org.onap.aai.sparky.dataintegrity.config.DiUiConstants; - -public class DiUiConstantsTest { - - private DiUiConstants diUiConstants; - - @Before - public void init() throws Exception { - - diUiConstants = new DiUiConstants(); - } - - - @Test - public void successfullInitializationOfConstants() { - - assertEquals("application/json", diUiConstants.APP_JSON); - assertEquals("category", diUiConstants.CATEGORY); - assertEquals("entityType", diUiConstants.ENTITY_TYPE); - assertEquals("aggregations", diUiConstants.KEY_AGG); - assertEquals("aggregationResult", diUiConstants.KEY_AGG_RESULT); - assertEquals("count", diUiConstants.KEY_AGG_RESULT_COUNT); - assertEquals("key_as_string", diUiConstants.KEY_AGG_RESULT_ID); - assertEquals("buckets", diUiConstants.KEY_BUCKETS); - assertEquals("route", diUiConstants.KEY_ROUTE); - assertEquals("filters", diUiConstants.KEY_FILTERS); - assertEquals("filterValue", diUiConstants.KEY_FILTER_VALUE); - assertEquals("filterId", diUiConstants.KEY_FILTER_ID); - assertEquals("startDate", diUiConstants.KEY_START_DATE); - assertEquals("endDate", diUiConstants.KEY_END_DATE); - assertEquals("time_zone", diUiConstants.KEY_TIME_ZONE); - assertEquals("severity", diUiConstants.WIDGET_TYPE_SEVERITY); - assertEquals("category", diUiConstants.WIDGET_TYPE_CATEGORY); - assertEquals("entityType", diUiConstants.WIDGET_TYPE_ENTITY_TYPE); - assertEquals("pagination", diUiConstants.WIDGET_TYPE_PAGINATED_TABLE); - assertEquals("dateHistogram", diUiConstants.WIDGET_TYPE_DATE_HISTOGRAM); - assertEquals("by_item", diUiConstants.KEY_BY_ITEM); - assertEquals("entityId", diUiConstants.KEY_ENTITY_ID); - assertEquals("hits", diUiConstants.KEY_HITS); - assertEquals("searchResult", diUiConstants.KEY_SEARCH_RESULT); - assertEquals("inner_hits", diUiConstants.KEY_INNER_HITS); - assertEquals("item", diUiConstants.KEY_ITEM); - assertEquals("item_aggregation", diUiConstants.KEY_ITEM_AGG); - assertEquals("violationTimestamp", diUiConstants.KEY_TIMESTAMP); - assertEquals("totalHits", diUiConstants.KEY_TOTAL_HITS); - assertEquals("violationDetails", diUiConstants.KEY_VIOLATION_DETAILS); - assertEquals("query", diUiConstants.SEARCH_API); - assertEquals("severity", diUiConstants.SEVERITY); - assertEquals("group_by_status", diUiConstants.UI_KEY_BY_CATEGORY); - assertEquals("group_by_date", diUiConstants.UI_KEY_BY_DATE); - assertEquals("group_by_entityType", diUiConstants.UI_KEY_BY_ENTITY_TYPE); - assertEquals("group_by_severity", diUiConstants.UI_KEY_BY_SEVERITY); - assertEquals("order_by_date", diUiConstants.UI_KEY_ORDER_BY_DATE); - assertEquals("violations", diUiConstants.VIOLATIONS); - assertEquals("Data Integrity", diUiConstants.KEY_VIEW_NAME); - - - } -} diff --git a/src/test/java/org/onap/aai/sparky/editattributes/AttributeUpdaterTest.java b/src/test/java/org/onap/aai/sparky/editattributes/AttributeUpdaterTest.java index d7d4679..63b3ff4 100644 --- a/src/test/java/org/onap/aai/sparky/editattributes/AttributeUpdaterTest.java +++ b/src/test/java/org/onap/aai/sparky/editattributes/AttributeUpdaterTest.java @@ -1,143 +1,164 @@ package org.onap.aai.sparky.editattributes; /** - * ============LICENSE_START=================================================== SPARKY (AAI UI - * service) ============================================================================ Copyright © - * 2017 AT&T Intellectual Property. Copyright © 2017 Amdocs All rights reserved. - * ============================================================================ Licensed under the - * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * ============LICENSE_START=================================================== + * SPARKY (AAI UI service) + * ============================================================================ + * Copyright © 2017 AT&T Intellectual Property. + * Copyright © 2017 Amdocs + * All rights reserved. + * ============================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. ============LICENSE_END===================================================== + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END===================================================== * - * ECOMP and OpenECOMP are trademarks and service marks of AT&T Intellectual Property. + * ECOMP and OpenECOMP are trademarks + * and service marks of AT&T Intellectual Property. */ /* - * package org.openecomp.sparky.editattributes; - * - * import static org.junit.Assert.assertEquals; - * - * import java.util.HashMap; import java.util.Map; - * - * import javax.ws.rs.core.Response.Status; - * - * import org.junit.Before; import org.junit.Test; import - * org.onap.aai.restclient.client.OperationResult; import - * org.onap.aai.sparky.config.oxm.OxmEntityDescriptor; import - * org.onap.aai.sparky.config.oxm.OxmEntityLookup; import - * org.onap.aai.sparky.config.oxm.OxmModelLoader; import - * org.onap.aai.sparky.dal.aai.config.ActiveInventoryConfig; import - * org.onap.aai.sparky.editattributes.AttributeUpdater; import - * org.openecomp.sparky.dal.aai.config.ActiveInventoryConfigUtil; - * - * - * /** The Class AttributeUpdaterTest. - * - * public class AttributeUpdaterTest { - * - * /** Sets the up. - * - * @throws Exception the exception - * - * @Before public void setUp() throws Exception {} - * - * /** - * - * @throws Exception - */ +package org.openecomp.sparky.editattributes; -/* - * @Test public void testUpdateObjectAttribute() throws Exception { - * - * OxmEntityDescriptor desc = new OxmEntityDescriptor(); desc.addPrimaryKeyName("hostname"); - * desc.setEntityName("pserver"); - * - * OxmEntityLookup entityLookup = OxmEntityLookup.getInstance(); - * entityLookup.addEntityDescriptor("pserver", desc); - * - * AttributeUpdater updater = new AttributeUpdater(new OxmModelLoader(), entityLookup, new - * ActiveInventoryConfig(ActiveInventoryConfigUtil.getValidTestProperties())); Map<String, Object> - * attributes = new HashMap<>(); attributes.put("prov-status", "PREPROV"); - * attributes.put("in-maint", "true"); OperationResult result = updater.updateObjectAttribute( - * "cloud-infrastructure/pservers/pserver/something", attributes, "someid"); - * assertEquals(Status.FORBIDDEN.getStatusCode(), result.getResultCode()); } - */ +import static org.junit.Assert.assertEquals; + +import java.util.HashMap; +import java.util.Map; + +import javax.ws.rs.core.Response.Status; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.restclient.client.OperationResult; +import org.onap.aai.sparky.config.oxm.OxmEntityDescriptor; +import org.onap.aai.sparky.config.oxm.OxmEntityLookup; +import org.onap.aai.sparky.config.oxm.OxmModelLoader; +import org.onap.aai.sparky.dal.aai.config.ActiveInventoryConfig; +import org.onap.aai.sparky.editattributes.AttributeUpdater; +import org.openecomp.sparky.dal.aai.config.ActiveInventoryConfigUtil; -// This needs the OXM file in place to work. -/** - * Test get edit object from uri. - * - * @throws Exception the exception - */ -// @Test -/* - * public void testGetEditObjectFromUri() throws Exception { - * - * OxmModelLoader loader = new OxmModelLoader(); loader.setLatestVersionNum(11); - * - * OxmEntityDescriptor desc = new OxmEntityDescriptor(); desc.addPrimaryKeyName("hostname"); - * desc.setEntityName("pserver"); - * - * OxmEntityLookup entityLookup = OxmEntityLookup.getInstance(); - * entityLookup.addEntityDescriptor("pserver", desc); - * - * - * DynamicType mockType = Mockito.mock(DynamicType.class); Class<? extends DynamicEntity> - * mockDynamicEntity = Mockito.mock(DynamicEntity.class); - * - * Mockito.when(mockType.getJavaClass()).thenReturn(mockDynamicEntity); - * - * - * - * - * HashMap<String, DynamicType> typeLookup = new HashMap<String,DynamicType>(); - * typeLookup.put("pserver", mockType); - * - * entityLookup.setEntityTypeLookup(typeLookup); - * - * - * AttributeUpdater updater = new AttributeUpdater(new OxmModelLoader(), entityLookup, new - * ActiveInventoryConfig(ActiveInventoryConfigUtil.getValidTestProperties())); AaiEditObject result - * = updater.getEditObjectFromUri("cloud-infrastructure/pservers/pserver/mtznjtax101"); - * assertEquals("Pserver", result.getObjectType()); assertEquals("pserver", - * result.getRootElement()); assertEquals("hostname", result.getKeyName()); - * assertEquals("mtznjtax101", result.getKeyValue()); } - */ /** - * Test get relative uri. + * The Class AttributeUpdaterTest. * - * @throws Exception the exception - */ -/* - * @Test public void testGetRelativeUri() throws Exception { - * - * OxmEntityDescriptor desc = new OxmEntityDescriptor(); desc.addPrimaryKeyName("hostname"); - * desc.setEntityName("pserver"); - * - * OxmEntityLookup entityLookup = OxmEntityLookup.getInstance(); - * entityLookup.addEntityDescriptor("pserver", desc); - * - * AttributeUpdater updater = new AttributeUpdater(new OxmModelLoader(), entityLookup, new - * ActiveInventoryConfig(ActiveInventoryConfigUtil.getValidTestProperties())); // Test entity uri - * without "/aai/version/" String result = - * updater.getRelativeUri("cloud-infrastructure/pservers/pserver/mtznjtax101"); - * assertEquals("/cloud-infrastructure/pservers/pserver/mtznjtax101", result); result = - * updater.getRelativeUri("/aai/v8/cloud-infrastructure/pservers/pserver/mtznjtax101"); - * assertEquals("/cloud-infrastructure/pservers/pserver/mtznjtax101", result); - * - * result = updater.getRelativeUri("/v8/cloud-infrastructure/pservers/pserver/mtznjtax101"); - * assertEquals("/cloud-infrastructure/pservers/pserver/mtznjtax101", result); - * - * result = updater.getRelativeUri("aai/v88/cloud-infrastructure/pservers/pserver/mtznjtax101"); - * assertEquals("/cloud-infrastructure/pservers/pserver/mtznjtax101", result); - * - * result = updater.getRelativeUri("/cloud-infrastructure/pservers/pserver/mtznjtax101"); - * assertEquals("/cloud-infrastructure/pservers/pserver/mtznjtax101", result); } - * - * } - */ +public class AttributeUpdaterTest { + + /** + * Sets the up. + * + * @throws Exception the exception + * + @Before + public void setUp() throws Exception {} + + /** + * @throws Exception + */ + /* + @Test + public void testUpdateObjectAttribute() throws Exception { + + OxmEntityDescriptor desc = new OxmEntityDescriptor(); + desc.addPrimaryKeyName("hostname"); + desc.setEntityName("pserver"); + + OxmEntityLookup entityLookup = OxmEntityLookup.getInstance(); + entityLookup.addEntityDescriptor("pserver", desc); + + AttributeUpdater updater = new AttributeUpdater(new OxmModelLoader(), entityLookup, + new ActiveInventoryConfig(ActiveInventoryConfigUtil.getValidTestProperties())); + Map<String, Object> attributes = new HashMap<>(); + attributes.put("prov-status", "PREPROV"); + attributes.put("in-maint", "true"); + OperationResult result = updater.updateObjectAttribute( + "cloud-infrastructure/pservers/pserver/something", attributes, "someid"); + assertEquals(Status.FORBIDDEN.getStatusCode(), result.getResultCode()); + } + */ + + // This needs the OXM file in place to work. + /** + * Test get edit object from uri. + * + * @throws Exception the exception + */ + //@Test + /*public void testGetEditObjectFromUri() throws Exception { + + OxmModelLoader loader = new OxmModelLoader(); + loader.setLatestVersionNum(11); + + OxmEntityDescriptor desc = new OxmEntityDescriptor(); + desc.addPrimaryKeyName("hostname"); + desc.setEntityName("pserver"); + + OxmEntityLookup entityLookup = OxmEntityLookup.getInstance(); + entityLookup.addEntityDescriptor("pserver", desc); + + + DynamicType mockType = Mockito.mock(DynamicType.class); + Class<? extends DynamicEntity> mockDynamicEntity = Mockito.mock(DynamicEntity.class); + + Mockito.when(mockType.getJavaClass()).thenReturn(mockDynamicEntity); + + + + + HashMap<String, DynamicType> typeLookup = new HashMap<String,DynamicType>(); + typeLookup.put("pserver", mockType); + + entityLookup.setEntityTypeLookup(typeLookup); + + + AttributeUpdater updater = new AttributeUpdater(new OxmModelLoader(), entityLookup, + new ActiveInventoryConfig(ActiveInventoryConfigUtil.getValidTestProperties())); + AaiEditObject result = + updater.getEditObjectFromUri("cloud-infrastructure/pservers/pserver/mtznjtax101"); + assertEquals("Pserver", result.getObjectType()); + assertEquals("pserver", result.getRootElement()); + assertEquals("hostname", result.getKeyName()); + assertEquals("mtznjtax101", result.getKeyValue()); + }*/ + + /** + * Test get relative uri. + * + * @throws Exception the exception + */ + /* + @Test + public void testGetRelativeUri() throws Exception { + + OxmEntityDescriptor desc = new OxmEntityDescriptor(); + desc.addPrimaryKeyName("hostname"); + desc.setEntityName("pserver"); + + OxmEntityLookup entityLookup = OxmEntityLookup.getInstance(); + entityLookup.addEntityDescriptor("pserver", desc); + + AttributeUpdater updater = new AttributeUpdater(new OxmModelLoader(), entityLookup, + new ActiveInventoryConfig(ActiveInventoryConfigUtil.getValidTestProperties())); + // Test entity uri without "/aai/version/" + String result = updater.getRelativeUri("cloud-infrastructure/pservers/pserver/mtznjtax101"); + assertEquals("/cloud-infrastructure/pservers/pserver/mtznjtax101", result); + result = updater.getRelativeUri("/aai/v8/cloud-infrastructure/pservers/pserver/mtznjtax101"); + assertEquals("/cloud-infrastructure/pservers/pserver/mtznjtax101", result); + + result = updater.getRelativeUri("/v8/cloud-infrastructure/pservers/pserver/mtznjtax101"); + assertEquals("/cloud-infrastructure/pservers/pserver/mtznjtax101", result); + + result = updater.getRelativeUri("aai/v88/cloud-infrastructure/pservers/pserver/mtznjtax101"); + assertEquals("/cloud-infrastructure/pservers/pserver/mtznjtax101", result); + + result = updater.getRelativeUri("/cloud-infrastructure/pservers/pserver/mtznjtax101"); + assertEquals("/cloud-infrastructure/pservers/pserver/mtznjtax101", result); + } + +} +*/
\ No newline at end of file diff --git a/src/test/java/org/onap/aai/sparky/editattributes/EditAttributesTest.java b/src/test/java/org/onap/aai/sparky/editattributes/EditAttributesTest.java index 488c53b..0d65dad 100644 --- a/src/test/java/org/onap/aai/sparky/editattributes/EditAttributesTest.java +++ b/src/test/java/org/onap/aai/sparky/editattributes/EditAttributesTest.java @@ -62,8 +62,8 @@ import com.att.aft.dme2.internal.jettison.json.JSONObject; public class EditAttributesTest { String sampleJsonRequest = "{ \"entity-uri\" : \"some/uri/value/here\", \"entity-type\" : \"complex\"," - + " \"attributes\" : { \"prov-status\" : \"PREPROV\", \"inMaint\" : \"true\"," - + " \"isClosedLoop\" : \"false\" }}"; + + " \"attributes\" : { \"prov-status\" : \"PREPROV\", \"inMaint\" : \"true\"," + + " \"isClosedLoop\" : \"false\" }}"; /** * Sets the up before class. @@ -81,23 +81,28 @@ public class EditAttributesTest { @Before public void setUp() throws Exception {} - + /** * Test analyze edit request body. */ /* - * @Test public void testAnalyzeEditRequestBody() { AttributeEditProcessor aes = new - * AttributeEditProcessor(); EditRequest request = aes.analyzeEditRequestBody(sampleJsonRequest); - * System.out.println("JSON Body : " + sampleJsonRequest); assertNotNull(request); assertEquals( - * "URI should match", "some/uri/value/here", request.getEntityUri()); assertEquals( - * "Entity Type should match", "complex", request.getEntityType()); assertEquals( - * "Attribute ProvStatus should match", "PREPROV", request.getAttributes().get("prov-status")); - * assertEquals("Attribute inMaint should be true", "true", - * request.getAttributes().get("inMaint")); assertEquals("Attribute isClosedLoop should be false", - * "false", request.getAttributes().get("isClosedLoop")); - * - * } - */ + @Test + public void testAnalyzeEditRequestBody() { + AttributeEditProcessor aes = new AttributeEditProcessor(); + EditRequest request = aes.analyzeEditRequestBody(sampleJsonRequest); + System.out.println("JSON Body : " + sampleJsonRequest); + assertNotNull(request); + assertEquals("URI should match", "some/uri/value/here", request.getEntityUri()); + assertEquals("Entity Type should match", "complex", request.getEntityType()); + assertEquals("Attribute ProvStatus should match", "PREPROV", + request.getAttributes().get("prov-status")); + assertEquals("Attribute inMaint should be true", "true", + request.getAttributes().get("inMaint")); + assertEquals("Attribute isClosedLoop should be false", "false", + request.getAttributes().get("isClosedLoop")); + + } + */ /** @@ -108,29 +113,37 @@ public class EditAttributesTest { * @throws JSONException the JSON exception */ /* - * @Test public void testEditRequest() throws IOException, ServletException, JSONException { - * HttpServletRequest mockRequest = mock(HttpServletRequest.class); HttpServletResponse - * mockResponse = mock(HttpServletResponse.class); ServletOutputStream mockOutput = - * mock(ServletOutputStream.class); ServletInputStream mockInput = new - * MockServletInputStream(sampleJsonRequest); - * - * when(mockRequest.getRequestURI()).thenReturn("editAttributes"); - * when(mockResponse.getOutputStream()).thenReturn(mockOutput); - * - * when(mockRequest.getInputStream()).thenReturn(mockInput); - * - * Principal princip = new UserPrincipal("ds1150"); - * - * when(mockRequest.getUserPrincipal()).thenReturn(princip); - * - * PrintWriter writer = new PrintWriter("editServletTest.txt"); - * when(mockResponse.getWriter()).thenReturn(writer); AttributeEditProcessor aes = new - * AttributeEditProcessor(); aes.doPost(mockRequest, mockResponse); JSONObject result = null; try - * { writer.close(); result = new JSONObject(FileUtils.readFileToString(new - * File("editServletTest.txt"), "UTF-8")); } catch (JSONException ex) { // Nothing to catch } - * assertNotNull(result); // assertEquals("Attributes updated successfully (just need PATCH !!!)", - * result.get("result")); } - */ + @Test + public void testEditRequest() throws IOException, ServletException, JSONException { + HttpServletRequest mockRequest = mock(HttpServletRequest.class); + HttpServletResponse mockResponse = mock(HttpServletResponse.class); + ServletOutputStream mockOutput = mock(ServletOutputStream.class); + ServletInputStream mockInput = new MockServletInputStream(sampleJsonRequest); + + when(mockRequest.getRequestURI()).thenReturn("editAttributes"); + when(mockResponse.getOutputStream()).thenReturn(mockOutput); + + when(mockRequest.getInputStream()).thenReturn(mockInput); + + Principal princip = new UserPrincipal("ds1150"); + + when(mockRequest.getUserPrincipal()).thenReturn(princip); + + PrintWriter writer = new PrintWriter("editServletTest.txt"); + when(mockResponse.getWriter()).thenReturn(writer); + AttributeEditProcessor aes = new AttributeEditProcessor(); + aes.doPost(mockRequest, mockResponse); + JSONObject result = null; + try { + writer.close(); + result = new JSONObject(FileUtils.readFileToString(new File("editServletTest.txt"), "UTF-8")); + } catch (JSONException ex) { + // Nothing to catch + } + assertNotNull(result); + // assertEquals("Attributes updated successfully (just need PATCH !!!)", result.get("result")); + } + */ /** * Test get att uid. @@ -139,39 +152,43 @@ public class EditAttributesTest { * @throws ServletException the servlet exception */ /* - * @Test public void testGetAttUid() throws IOException, ServletException { HttpServletRequest - * mockRequest = mock(HttpServletRequest.class); HttpServletResponse mockResponse = - * mock(HttpServletResponse.class); ServletOutputStream mockOutput = - * mock(ServletOutputStream.class); ServletInputStream mockInput = new - * MockServletInputStream(sampleJsonRequest); - * - * when(mockRequest.getRequestURI()).thenReturn("editAttributes"); - * when(mockResponse.getOutputStream()).thenReturn(mockOutput); - * - * when(mockRequest.getInputStream()).thenReturn(mockInput); - * - * Principal princip = new UserPrincipal("ds1150"); - * - * when(mockRequest.getUserPrincipal()).thenReturn(princip); - * - * PrintWriter writer = new PrintWriter("editServletTest.txt"); - * when(mockResponse.getWriter()).thenReturn(writer); - * when(mockRequest.getCookies()).thenReturn(new Cookie[] {new Cookie("attESHr", - * "DENNIS|SEBASTIAN|dennis.sebastian@amdocs.com|||ko2649||ds1150," + - * "RBFMSKQ,Z9V2298,9762186|YNNNNNNNNNNNNNYNNYYNNNNN|DENNIS|EY6SC9000|")}); AttributeEditProcessor - * aes = new AttributeEditProcessor(); String attid = aes.getAttUid(mockRequest); assertEquals( - * " Expected ATTUID is wrong", "ds1150", attid); - * - * when(mockRequest.getCookies()).thenReturn(new Cookie[] {new Cookie("attESHr", - * "DENNIS%7cSEBASTIAN%7cdennisse%40amdocs%2ecom%7c%7c%7cko2649%7c%7cds1150%2cRDJJFLM%" + - * "2cP86NJ85%2c8127688%7cYNNNNNNNNNNNNNYNNYNYNNNN%7cDENNIS%7cEY6SC9000%7c")}); attid = - * aes.getAttUid(mockRequest); assertEquals(" Expected ATTUID is wrong", "ds1150", attid); - * - * when(mockRequest.getCookies()).thenReturn(new Cookie[] {}); attid = aes.getAttUid(mockRequest); - * assertEquals(" Expected Empty ID", "", attid); - * - * } - */ + @Test + public void testGetAttUid() throws IOException, ServletException { + HttpServletRequest mockRequest = mock(HttpServletRequest.class); + HttpServletResponse mockResponse = mock(HttpServletResponse.class); + ServletOutputStream mockOutput = mock(ServletOutputStream.class); + ServletInputStream mockInput = new MockServletInputStream(sampleJsonRequest); + + when(mockRequest.getRequestURI()).thenReturn("editAttributes"); + when(mockResponse.getOutputStream()).thenReturn(mockOutput); + + when(mockRequest.getInputStream()).thenReturn(mockInput); + + Principal princip = new UserPrincipal("ds1150"); + + when(mockRequest.getUserPrincipal()).thenReturn(princip); + + PrintWriter writer = new PrintWriter("editServletTest.txt"); + when(mockResponse.getWriter()).thenReturn(writer); + when(mockRequest.getCookies()).thenReturn(new Cookie[] {new Cookie("attESHr", + "DENNIS|SEBASTIAN|dennis.sebastian@amdocs.com|||ko2649||ds1150," + + "RBFMSKQ,Z9V2298,9762186|YNNNNNNNNNNNNNYNNYYNNNNN|DENNIS|EY6SC9000|")}); + AttributeEditProcessor aes = new AttributeEditProcessor(); + String attid = aes.getAttUid(mockRequest); + assertEquals(" Expected ATTUID is wrong", "ds1150", attid); + + when(mockRequest.getCookies()).thenReturn(new Cookie[] {new Cookie("attESHr", + "DENNIS%7cSEBASTIAN%7cdennisse%40amdocs%2ecom%7c%7c%7cko2649%7c%7cds1150%2cRDJJFLM%" + + "2cP86NJ85%2c8127688%7cYNNNNNNNNNNNNNYNNYNYNNNN%7cDENNIS%7cEY6SC9000%7c")}); + attid = aes.getAttUid(mockRequest); + assertEquals(" Expected ATTUID is wrong", "ds1150", attid); + + when(mockRequest.getCookies()).thenReturn(new Cookie[] {}); + attid = aes.getAttUid(mockRequest); + assertEquals(" Expected Empty ID", "", attid); + + } + */ /** * The Class MockServletInputStream. @@ -188,9 +205,7 @@ public class EditAttributesTest { this.inputStream = IOUtils.toInputStream(string); } - /* - * (non-Javadoc) - * + /* (non-Javadoc) * @see java.io.InputStream#read() */ @Override diff --git a/src/test/java/org/onap/aai/sparky/inventory/EntityHistoryQueryBuilderTest.java b/src/test/java/org/onap/aai/sparky/inventory/EntityHistoryQueryBuilderTest.java index 2ecdda2..12786a7 100644 --- a/src/test/java/org/onap/aai/sparky/inventory/EntityHistoryQueryBuilderTest.java +++ b/src/test/java/org/onap/aai/sparky/inventory/EntityHistoryQueryBuilderTest.java @@ -11,23 +11,23 @@ import org.junit.Test; import org.onap.aai.sparky.inventory.EntityHistoryQueryBuilder; public class EntityHistoryQueryBuilderTest { - - private EntityHistoryQueryBuilder entityHistoryQueryBuilder; - - @Before - public void init() throws Exception { - entityHistoryQueryBuilder = new EntityHistoryQueryBuilder(); - } - - @Test - public void successfullBuild() { - entityHistoryQueryBuilder.getQuery("table"); - assertNotNull(entityHistoryQueryBuilder.createTableQuery()); - entityHistoryQueryBuilder.getQuery("graph"); - assertNotNull(entityHistoryQueryBuilder.createGraphQuery()); - entityHistoryQueryBuilder.getQuery("tree"); - assertNull(entityHistoryQueryBuilder.getQuery("tree")); - - } - -} + + private EntityHistoryQueryBuilder entityHistoryQueryBuilder; + + @Before + public void init() throws Exception { + entityHistoryQueryBuilder = new EntityHistoryQueryBuilder(); + } + + @Test + public void successfullBuild() { + entityHistoryQueryBuilder.getQuery("table"); + assertNotNull(entityHistoryQueryBuilder.createTableQuery()); + entityHistoryQueryBuilder.getQuery("graph"); + assertNotNull(entityHistoryQueryBuilder.createGraphQuery()); + entityHistoryQueryBuilder.getQuery("tree"); + assertNull(entityHistoryQueryBuilder.getQuery("tree")); + + } + +}
\ No newline at end of file diff --git a/src/test/java/org/onap/aai/sparky/logging/util/LoggingUtilsTest.java b/src/test/java/org/onap/aai/sparky/logging/util/LoggingUtilsTest.java index 2db34f7..4dc30a9 100644 --- a/src/test/java/org/onap/aai/sparky/logging/util/LoggingUtilsTest.java +++ b/src/test/java/org/onap/aai/sparky/logging/util/LoggingUtilsTest.java @@ -7,20 +7,19 @@ import org.junit.Test; import org.onap.aai.sparky.logging.util.LoggingUtils; public class LoggingUtilsTest { - - private LoggingUtils durationTester; - - @Before - public void init() throws Exception { - durationTester = new LoggingUtils(); - } - - @Test - public void durationTester() { - - - assertEquals("1425", durationTester.setDuration(3575, 5000)); - - } - -} + + private LoggingUtils durationTester; + @Before + public void init() throws Exception { + durationTester = new LoggingUtils(); + } + + @Test + public void durationTester() { + + + assertEquals("1425",durationTester.setDuration(3575, 5000)); + + } + +}
\ No newline at end of file diff --git a/src/test/java/org/onap/aai/sparky/search/EntityCountHistoryProcessorTest.java b/src/test/java/org/onap/aai/sparky/search/EntityCountHistoryProcessorTest.java index ec6c3ce..9629ae8 100644 --- a/src/test/java/org/onap/aai/sparky/search/EntityCountHistoryProcessorTest.java +++ b/src/test/java/org/onap/aai/sparky/search/EntityCountHistoryProcessorTest.java @@ -1,119 +1,154 @@ /** - * ============LICENSE_START=================================================== SPARKY (AAI UI - * service) ============================================================================ Copyright © - * 2017 AT&T Intellectual Property. Copyright © 2017 Amdocs All rights reserved. - * ============================================================================ Licensed under the - * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * ============LICENSE_START=================================================== + * SPARKY (AAI UI service) + * ============================================================================ + * Copyright © 2017 AT&T Intellectual Property. + * Copyright © 2017 Amdocs + * All rights reserved. + * ============================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. ============LICENSE_END===================================================== + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END===================================================== * - * ECOMP and OpenECOMP are trademarks and service marks of AT&T Intellectual Property. + * ECOMP and OpenECOMP are trademarks + * and service marks of AT&T Intellectual Property. */ package org.onap.aai.sparky.search; /* - * import static org.junit.Assert.assertEquals; - * - * import org.apache.camel.Exchange; import org.apache.camel.Message; import - * org.apache.camel.component.restlet.RestletConstants; import org.junit.Before; import - * org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import - * org.onap.aai.restclient.client.OperationResult; import - * org.onap.aai.sparky.search.EntityCountHistoryProcessor; import - * org.onap.aai.sparky.util.RestletUtils; import org.restlet.Request; import org.restlet.Response; - * import org.restlet.data.ClientInfo; import org.restlet.data.Reference; import - * org.restlet.data.Status; - * - * import com.fasterxml.jackson.databind.ObjectMapper; import - * com.fasterxml.jackson.databind.node.ArrayNode; import - * com.fasterxml.jackson.databind.node.ObjectNode; - * - * public class EntityCountHistoryProcessorTest { private EntityCountHistoryProcessor - * entityCountHistoryProcessor; private Exchange mockExchange; private Message mockRequestMessage; - * private Message mockResponseMessage; private Request mockRestletRequest; private Response - * mockRestletResponse; private ClientInfo requestClientInfo; private RestletUtils mockRestletUtils; - * - * @Before public void init() throws Exception { mockExchange = Mockito.mock(Exchange.class); - * mockRequestMessage = Mockito.mock(Message.class); mockResponseMessage = - * Mockito.mock(Message.class); mockRestletRequest = Mockito.mock(Request.class); - * mockRestletResponse = Mockito.mock(Response.class); mockRestletUtils = - * Mockito.mock(RestletUtils.class); - * - * entityCountHistoryProcessor = new EntityCountHistoryProcessor(); - * entityCountHistoryProcessor.setRestletUtils(mockRestletUtils); - * - * requestClientInfo = new ClientInfo(); - * - * Mockito.when(mockRestletRequest.getClientInfo()).thenReturn(requestClientInfo); - * - * Mockito.when(mockRequestMessage.getHeader(RestletConstants.RESTLET_REQUEST, Request.class)) - * .thenReturn(mockRestletRequest); - * Mockito.when(mockRequestMessage.getHeader(RestletConstants.RESTLET_RESPONSE, Response.class)) - * .thenReturn(mockRestletResponse); - * Mockito.when(mockExchange.getIn()).thenReturn(mockRequestMessage); - * Mockito.when(mockExchange.getOut()).thenReturn(mockResponseMessage); } - * - * public String getStubbedData_getEntityCountHistory_success() { ObjectMapper mapper = new - * ObjectMapper(); ObjectNode entityCountEntry = mapper.createObjectNode(); - * - * entityCountEntry.put("doc_count", 2069); entityCountEntry.put("key", "complex"); - * - * ArrayNode arrayNode = mapper.createArrayNode(); arrayNode.add(entityCountEntry); - * - * ObjectNode resultNode = mapper.createObjectNode(); resultNode.set("result", arrayNode); - * - * return resultNode.toString(); } - * - * @Test public void testGetEntityCountHistory_success() { EntityCountHistoryProcessor - * spyEntityCountHistoryProcessor = Mockito.spy(entityCountHistoryProcessor); OperationResult - * operationResult = new OperationResult(); - * - * String result = getStubbedData_getEntityCountHistory_success(); - * - * operationResult.setResult(Status.SUCCESS_OK.getCode(), result); - * - * Mockito.when(mockExchange.getIn().getHeader("CamelHttpQuery", String.class)).thenReturn(""); - * - * Mockito.doReturn("table").when(spyEntityCountHistoryProcessor).getTypeParameter(Mockito.any()); - * Mockito.doReturn(operationResult).when(spyEntityCountHistoryProcessor).getResults(Mockito.any(), - * Mockito.any()); - * - * spyEntityCountHistoryProcessor.getEntityCountHistory(mockExchange); - * - * ArgumentCaptor<String> entityCaptor = ArgumentCaptor.forClass(String.class); - * Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setEntity(entityCaptor.capture(), - * Mockito.any()); assertEquals(operationResult.getResult(), entityCaptor.getValue()); } - * - * @Test public void testGetEntityCountHistory_failure_noTypeParameter() { - * Mockito.when(mockRestletRequest.getOriginalRef()).thenReturn(new Reference()); - * - * EntityCountHistoryProcessor spyEntityCountHistoryProcessor = - * Mockito.spy(entityCountHistoryProcessor); OperationResult operationResult = new - * OperationResult(); - * - * String result = getStubbedData_getEntityCountHistory_success(); - * - * operationResult.setResult(Status.SUCCESS_OK.getCode(), result); - * - * Mockito.when(mockExchange.getIn().getHeader("CamelHttpQuery", String.class)).thenReturn(""); - * - * Mockito.doReturn("").when(spyEntityCountHistoryProcessor).getTypeParameter(Mockito.any()); - * Mockito.doReturn(operationResult).when(spyEntityCountHistoryProcessor).getResults(Mockito.any(), - * Mockito.any()); - * - * spyEntityCountHistoryProcessor.getEntityCountHistory(mockExchange); - * - * ArgumentCaptor<String> entityCaptor = ArgumentCaptor.forClass(String.class); - * Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setEntity(entityCaptor.capture(), - * Mockito.any()); assertEquals("{ \"errorMessage\" : Unsupported request. Resource not found. }", - * entityCaptor.getValue()); - * - * ArgumentCaptor<Status> responseCodeCaptor = ArgumentCaptor.forClass(Status.class); - * Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture()); - * assertEquals(Status.CLIENT_ERROR_NOT_FOUND, responseCodeCaptor.getValue()); } } - */ +import static org.junit.Assert.assertEquals; + +import org.apache.camel.Exchange; +import org.apache.camel.Message; +import org.apache.camel.component.restlet.RestletConstants; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +import org.onap.aai.restclient.client.OperationResult; +import org.onap.aai.sparky.search.EntityCountHistoryProcessor; +import org.onap.aai.sparky.util.RestletUtils; +import org.restlet.Request; +import org.restlet.Response; +import org.restlet.data.ClientInfo; +import org.restlet.data.Reference; +import org.restlet.data.Status; + +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.node.ArrayNode; +import com.fasterxml.jackson.databind.node.ObjectNode; + +public class EntityCountHistoryProcessorTest { + private EntityCountHistoryProcessor entityCountHistoryProcessor; + private Exchange mockExchange; + private Message mockRequestMessage; + private Message mockResponseMessage; + private Request mockRestletRequest; + private Response mockRestletResponse; + private ClientInfo requestClientInfo; + private RestletUtils mockRestletUtils; + + @Before + public void init() throws Exception { + mockExchange = Mockito.mock(Exchange.class); + mockRequestMessage = Mockito.mock(Message.class); + mockResponseMessage = Mockito.mock(Message.class); + mockRestletRequest = Mockito.mock(Request.class); + mockRestletResponse = Mockito.mock(Response.class); + mockRestletUtils = Mockito.mock(RestletUtils.class); + + entityCountHistoryProcessor = new EntityCountHistoryProcessor(); + entityCountHistoryProcessor.setRestletUtils(mockRestletUtils); + + requestClientInfo = new ClientInfo(); + + Mockito.when(mockRestletRequest.getClientInfo()).thenReturn(requestClientInfo); + + Mockito.when(mockRequestMessage.getHeader(RestletConstants.RESTLET_REQUEST, Request.class)) + .thenReturn(mockRestletRequest); + Mockito.when(mockRequestMessage.getHeader(RestletConstants.RESTLET_RESPONSE, Response.class)) + .thenReturn(mockRestletResponse); + Mockito.when(mockExchange.getIn()).thenReturn(mockRequestMessage); + Mockito.when(mockExchange.getOut()).thenReturn(mockResponseMessage); + } + + public String getStubbedData_getEntityCountHistory_success() { + ObjectMapper mapper = new ObjectMapper(); + ObjectNode entityCountEntry = mapper.createObjectNode(); + + entityCountEntry.put("doc_count", 2069); + entityCountEntry.put("key", "complex"); + + ArrayNode arrayNode = mapper.createArrayNode(); + arrayNode.add(entityCountEntry); + + ObjectNode resultNode = mapper.createObjectNode(); + resultNode.set("result", arrayNode); + + return resultNode.toString(); + } + + @Test + public void testGetEntityCountHistory_success() { + EntityCountHistoryProcessor spyEntityCountHistoryProcessor = + Mockito.spy(entityCountHistoryProcessor); + OperationResult operationResult = new OperationResult(); + + String result = getStubbedData_getEntityCountHistory_success(); + + operationResult.setResult(Status.SUCCESS_OK.getCode(), result); + + Mockito.when(mockExchange.getIn().getHeader("CamelHttpQuery", String.class)).thenReturn(""); + + Mockito.doReturn("table").when(spyEntityCountHistoryProcessor).getTypeParameter(Mockito.any()); + Mockito.doReturn(operationResult).when(spyEntityCountHistoryProcessor).getResults(Mockito.any(), + Mockito.any()); + + spyEntityCountHistoryProcessor.getEntityCountHistory(mockExchange); + + ArgumentCaptor<String> entityCaptor = ArgumentCaptor.forClass(String.class); + Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setEntity(entityCaptor.capture(), + Mockito.any()); + assertEquals(operationResult.getResult(), entityCaptor.getValue()); + } + + @Test + public void testGetEntityCountHistory_failure_noTypeParameter() { + Mockito.when(mockRestletRequest.getOriginalRef()).thenReturn(new Reference()); + + EntityCountHistoryProcessor spyEntityCountHistoryProcessor = + Mockito.spy(entityCountHistoryProcessor); + OperationResult operationResult = new OperationResult(); + + String result = getStubbedData_getEntityCountHistory_success(); + + operationResult.setResult(Status.SUCCESS_OK.getCode(), result); + + Mockito.when(mockExchange.getIn().getHeader("CamelHttpQuery", String.class)).thenReturn(""); + + Mockito.doReturn("").when(spyEntityCountHistoryProcessor).getTypeParameter(Mockito.any()); + Mockito.doReturn(operationResult).when(spyEntityCountHistoryProcessor).getResults(Mockito.any(), Mockito.any()); + + spyEntityCountHistoryProcessor.getEntityCountHistory(mockExchange); + + ArgumentCaptor<String> entityCaptor = ArgumentCaptor.forClass(String.class); + Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setEntity(entityCaptor.capture(), + Mockito.any()); + assertEquals("{ \"errorMessage\" : Unsupported request. Resource not found. }", + entityCaptor.getValue()); + + ArgumentCaptor<Status> responseCodeCaptor = ArgumentCaptor.forClass(Status.class); + Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture()); + assertEquals(Status.CLIENT_ERROR_NOT_FOUND, responseCodeCaptor.getValue()); + } +} +*/
\ No newline at end of file diff --git a/src/test/java/org/onap/aai/sparky/search/UnifiedSearchProcessorTest.java b/src/test/java/org/onap/aai/sparky/search/UnifiedSearchProcessorTest.java index 445d0b4..e123c5d 100644 --- a/src/test/java/org/onap/aai/sparky/search/UnifiedSearchProcessorTest.java +++ b/src/test/java/org/onap/aai/sparky/search/UnifiedSearchProcessorTest.java @@ -39,14 +39,10 @@ import org.apache.camel.component.restlet.RestletConstants; import org.json.JSONArray; import org.json.JSONObject; import org.junit.Before; -import org.junit.Ignore; import org.junit.Test; import org.mockito.ArgumentCaptor; import org.mockito.Mockito; import org.onap.aai.sparky.common.search.CommonSearchSuggestion; -import org.onap.aai.sparky.dal.elasticsearch.SearchAdapter; -import org.onap.aai.sparky.search.SearchResponse; -import org.onap.aai.sparky.search.UnifiedSearchProcessor; import org.onap.aai.sparky.search.api.SearchProvider; import org.onap.aai.sparky.search.entity.QuerySearchEntity; import org.onap.aai.sparky.search.entity.SearchSuggestion; @@ -58,13 +54,14 @@ import org.restlet.data.MediaType; import org.restlet.data.Status; import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.DeserializationFeature; import com.fasterxml.jackson.databind.ObjectMapper; public class UnifiedSearchProcessorTest { public interface Suggester { - public void addSuggestion(SearchSuggestion suggestion); + public void addSuggestion( SearchSuggestion suggestion ); } private abstract class AbstractDummySearchProvider implements SearchProvider, Suggester { @@ -79,13 +76,12 @@ public class UnifiedSearchProcessorTest { return suggestions; } - public void addSuggestion(CommonSearchSuggestion suggestion) { + public void addSuggestion(SearchSuggestion suggestion) { if (suggestion != null) { suggestions.add(suggestion); } } - @Override public List<SearchSuggestion> search(QuerySearchEntity queryRequest) { return getSuggestions(); } @@ -98,12 +94,6 @@ public class UnifiedSearchProcessorTest { super(); } - @Override - public void addSuggestion(SearchSuggestion suggestion) { - // TODO Auto-generated method stub - - } - } private class BravoSearchProvider extends AbstractDummySearchProvider { @@ -112,12 +102,6 @@ public class UnifiedSearchProcessorTest { super(); } - @Override - public void addSuggestion(SearchSuggestion suggestion) { - // TODO Auto-generated method stub - - } - } private class GammaSearchProvider extends AbstractDummySearchProvider { @@ -126,44 +110,9 @@ public class UnifiedSearchProcessorTest { super(); } - @Override - public void addSuggestion(SearchSuggestion suggestion) { - // TODO Auto-generated method stub - - } - - } - - private class PerspectiveSearchProvider implements SearchProvider { - - private List<String> perspectives; - - public PerspectiveSearchProvider() { - perspectives = new ArrayList<String>(); - } - - public List<String> getPerspectives() { - return perspectives; - } - - public void setPerspectives(List<String> perspectives) { - this.perspectives = perspectives; - } - - public void addPerspective(String perspective) { - perspectives.add(perspective); - } - - @Override - public List<SearchSuggestion> search(QuerySearchEntity queryRequest) { - // TODO Auto-generated method stub - return null; - } - - } - private SearchAdapter mockSearchAdapter; + private SearchServiceAdapter mockSearchAdapter; private UnifiedSearchProcessor unifiedSearchProcessor; private Exchange mockExchange; @@ -189,8 +138,9 @@ public class UnifiedSearchProcessorTest { unifiedSearchProcessor.setUseOrderedSearchProviderKeys(true); mapper = new ObjectMapper(); + mapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false); - mockSearchAdapter = Mockito.mock(SearchAdapter.class); + mockSearchAdapter = Mockito.mock(SearchServiceAdapter.class); } @@ -271,7 +221,7 @@ public class UnifiedSearchProcessorTest { // mock env setup - initializeSearchMocks(getSearchRequestJson("vnfs", 10)); + initializeSearchMocks(getSearchRequestJson("vnfs",10)); SearchProviderRegistry searchProviderRegistry = new SearchProviderRegistry(); unifiedSearchProcessor.setSearchProviderRegistry(searchProviderRegistry); @@ -293,8 +243,7 @@ public class UnifiedSearchProcessorTest { Mockito.verify(mockResponseMessage, Mockito.atLeast(1)).setBody(responseObject.capture()); assertEquals(MediaType.APPLICATION_JSON, payloadMediaType.getValue()); - SearchResponse searchResponse = - mapper.readValue(entityPayload.getValue(), SearchResponse.class); + SearchResponse searchResponse = mapper.readValue(entityPayload.getValue(), SearchResponse.class); assertEquals(0, searchResponse.getTotalFound()); assertEquals(0, searchResponse.getSuggestions().size()); @@ -306,7 +255,7 @@ public class UnifiedSearchProcessorTest { // mock env setup - initializeSearchMocks(getSearchRequestJson("vnfs", 10)); + initializeSearchMocks(getSearchRequestJson("vnfs",10)); SearchProviderRegistry searchProviderRegistry = new SearchProviderRegistry(); @@ -342,8 +291,7 @@ public class UnifiedSearchProcessorTest { * With a null view name, an empty filter set should be returned - there should be 0 filters */ - SearchResponse searchResponse = - mapper.readValue(entityPayload.getValue(), SearchResponse.class); + SearchResponse searchResponse = mapper.readValue(entityPayload.getValue(), SearchResponse.class); assertEquals(0, searchResponse.getTotalFound()); assertEquals(0, searchResponse.getSuggestions().size()); @@ -351,8 +299,8 @@ public class UnifiedSearchProcessorTest { } private void addSuggestions(int numSuggestions, String suggestionPrefix, Suggester suggester) { - CommonSearchSuggestion suggestion = null; - for (int x = 0; x < numSuggestions; x++) { + SearchSuggestion suggestion = null; + for ( int x = 0; x < numSuggestions; x++ ){ suggestion = new CommonSearchSuggestion(); suggestion.setText(suggestionPrefix + "-" + x); suggester.addSuggestion(suggestion); @@ -360,7 +308,7 @@ public class UnifiedSearchProcessorTest { } private void addSuggestion(String perspective, String text, String hashId, Suggester suggester) { - CommonSearchSuggestion suggestion = new CommonSearchSuggestion(); + SearchSuggestion suggestion = new CommonSearchSuggestion(); suggestion.setText(text); suggestion.setHashId(hashId); suggester.addSuggestion(suggestion); @@ -370,9 +318,9 @@ public class UnifiedSearchProcessorTest { int totalFound = 0; - for (SearchSuggestion suggestion : response.getSuggestions()) { + for ( SearchSuggestion suggestion : response.getSuggestions()) { - if (suggestion.getText() != null && suggestion.getText().startsWith(suggestionPrefix)) { + if ( suggestion.getText() != null && suggestion.getText().startsWith(suggestionPrefix)) { totalFound++; } } @@ -381,66 +329,31 @@ public class UnifiedSearchProcessorTest { } - @Ignore - @Test - public void testSearch_search_when_ThreeSearchProviders_5suggestions_each() throws IOException { - - // mock env setup - - initializeSearchMocks(getSearchRequestJson("vnfs", 10)); - - SearchProviderRegistry searchProviderRegistry = new SearchProviderRegistry(); - - AlphaSearchProvider alpha = new AlphaSearchProvider(); - BravoSearchProvider bravo = new BravoSearchProvider(); - GammaSearchProvider gamma = new GammaSearchProvider(); - - searchProviderRegistry.addSearchProvider(alpha); - searchProviderRegistry.addSearchProvider(bravo); - searchProviderRegistry.addSearchProvider(gamma); + private int countSuggestions(String suggestionPrefix, JSONArray suggestions) { - unifiedSearchProcessor.setSearchProviderRegistry(searchProviderRegistry); - - addSuggestions(5, "alpha", alpha); - addSuggestions(5, "bravo", bravo); - addSuggestions(5, "gamma", gamma); - - // method under test - unifiedSearchProcessor.search(mockExchange); + int totalFound = 0; - ArgumentCaptor<Status> responseCodeCaptor = ArgumentCaptor.forClass(Status.class); - Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture()); - assertEquals(Status.SUCCESS_OK, responseCodeCaptor.getValue()); + for ( int x = 0; x < suggestions.length(); x++ ) { - ArgumentCaptor<String> entityPayload = ArgumentCaptor.forClass(String.class); - ArgumentCaptor<MediaType> payloadMediaType = ArgumentCaptor.forClass(MediaType.class); - Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setEntity(entityPayload.capture(), - payloadMediaType.capture()); - assertNotNull(entityPayload.getValue()); + JSONObject suggestion = (JSONObject)suggestions.get(x); - ArgumentCaptor<Response> responseObject = ArgumentCaptor.forClass(Response.class); - Mockito.verify(mockResponseMessage, Mockito.atLeast(1)).setBody(responseObject.capture()); - assertEquals(MediaType.APPLICATION_JSON, payloadMediaType.getValue()); - - SearchResponse searchResponse = - mapper.readValue(entityPayload.getValue(), SearchResponse.class); + String text = suggestion.getString("text"); + if ( String.valueOf(text).startsWith(suggestionPrefix)) { + totalFound++; + } - assertEquals(10, searchResponse.getTotalFound()); - assertEquals(10, searchResponse.getSuggestions().size()); + } - assertEquals(4, countSuggestions("alpha", searchResponse)); - assertEquals(3, countSuggestions("bravo", searchResponse)); - assertEquals(3, countSuggestions("gamma", searchResponse)); + return totalFound; } - @Ignore @Test - public void testSearch_search_when_ThreeSearchProviders_mixedNumSuggestions() throws IOException { + public void testSearch_search_when_ThreeSearchProviders_5suggestions_each() throws IOException { // mock env setup - initializeSearchMocks(getSearchRequestJson("vnfs", 13)); + initializeSearchMocks(getSearchRequestJson("vnfs",10)); SearchProviderRegistry searchProviderRegistry = new SearchProviderRegistry(); @@ -454,9 +367,9 @@ public class UnifiedSearchProcessorTest { unifiedSearchProcessor.setSearchProviderRegistry(searchProviderRegistry); - addSuggestions(45, "alpha", alpha); - addSuggestions(1, "bravo", bravo); - addSuggestions(99, "gamma", gamma); + addSuggestions(5,"alpha",alpha); + addSuggestions(5,"bravo",bravo); + addSuggestions(5,"gamma",gamma); // method under test unifiedSearchProcessor.search(mockExchange); @@ -475,37 +388,28 @@ public class UnifiedSearchProcessorTest { Mockito.verify(mockResponseMessage, Mockito.atLeast(1)).setBody(responseObject.capture()); assertEquals(MediaType.APPLICATION_JSON, payloadMediaType.getValue()); - SearchResponse searchResponse = - mapper.readValue(entityPayload.getValue(), SearchResponse.class); - assertEquals(13, searchResponse.getTotalFound()); - assertEquals(13, searchResponse.getSuggestions().size()); + JSONObject response = new JSONObject(entityPayload.getValue()); - /** - * There should be an even divide of suggestions per search provider relative to the suggestions - * available per search provider. Alpha has 45 suggestions Bravo has 1 suggestion Gamma has 99 - * suggestions - * - * We only asked for 13 suggestions to be returned, so based on the suggestion distribution - * algorithm we will get a fair distribution of suggestions per provider relative to what each - * provider has available. Resulting in: 6 from Alpha 1 from Bravo 6 from Gamma - * - */ + assertEquals(response.getInt("totalFound"),10); + + JSONArray suggestions = response.getJSONArray("suggestions"); + assertNotNull(suggestions); - assertEquals(6, countSuggestions("alpha", searchResponse)); - assertEquals(1, countSuggestions("bravo", searchResponse)); - assertEquals(6, countSuggestions("gamma", searchResponse)); + assertEquals(suggestions.length(),10); + + assertEquals( 4, countSuggestions("alpha", suggestions)); + assertEquals( 3, countSuggestions("bravo", suggestions)); + assertEquals( 3, countSuggestions("gamma", suggestions)); } - @Ignore @Test - public void testSearch_search_when_ThreeSearchProviders_wantedMoreSuggestionsThanAvailable() - throws IOException { + public void testSearch_search_when_ThreeSearchProviders_mixedNumSuggestions() throws IOException { // mock env setup - initializeSearchMocks(getSearchRequestJson("vnfs", 13)); + initializeSearchMocks(getSearchRequestJson("vnfs",13)); SearchProviderRegistry searchProviderRegistry = new SearchProviderRegistry(); @@ -519,9 +423,9 @@ public class UnifiedSearchProcessorTest { unifiedSearchProcessor.setSearchProviderRegistry(searchProviderRegistry); - addSuggestions(1, "alpha", alpha); - addSuggestions(4, "bravo", bravo); - addSuggestions(0, "gamma", gamma); + addSuggestions(45,"alpha",alpha); + addSuggestions(1,"bravo",bravo); + addSuggestions(99,"gamma",gamma); // method under test unifiedSearchProcessor.search(mockExchange); @@ -540,65 +444,43 @@ public class UnifiedSearchProcessorTest { Mockito.verify(mockResponseMessage, Mockito.atLeast(1)).setBody(responseObject.capture()); assertEquals(MediaType.APPLICATION_JSON, payloadMediaType.getValue()); - SearchResponse searchResponse = - mapper.readValue(entityPayload.getValue(), SearchResponse.class); - - assertEquals(5, searchResponse.getTotalFound()); - assertEquals(5, searchResponse.getSuggestions().size()); - - assertEquals(1, countSuggestions("alpha", searchResponse)); - assertEquals(4, countSuggestions("bravo", searchResponse)); - assertEquals(0, countSuggestions("gamma", searchResponse)); - - } - - private String getPerspectiveRequestJson(String hashId) { - JSONObject root = new JSONObject(); - root.put("hashId", hashId); - return root.toString(); - } - - @Ignore - @Test - public void testDiscoverPerspectives_search_with_valid_payload() throws JsonProcessingException { - initializePerspectiveMocks(getPerspectiveRequestJson("thisisahashidandyouarebeautiful")); + JSONObject response = new JSONObject(entityPayload.getValue()); - PerspectiveSearchProvider search = new PerspectiveSearchProvider(); - search.addPerspective("One"); - search.addPerspective("Two"); - search.addPerspective("Three"); - SearchProviderRegistry searchProviderRegistry = new SearchProviderRegistry(); - searchProviderRegistry.addSearchProvider(search); + assertEquals(response.getInt("totalFound"),13); - unifiedSearchProcessor.setSearchProviderRegistry(searchProviderRegistry); - // unifiedSearchProcessor.discoverPerspectives(mockExchange); + JSONArray suggestions = response.getJSONArray("suggestions"); + assertNotNull(suggestions); - ArgumentCaptor<Status> responseCodeCaptor = ArgumentCaptor.forClass(Status.class); - Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture()); - assertEquals(Status.SUCCESS_OK, responseCodeCaptor.getValue()); + assertEquals(suggestions.length(),13); - ArgumentCaptor<String> entityPayload = ArgumentCaptor.forClass(String.class); - ArgumentCaptor<MediaType> payloadMediaType = ArgumentCaptor.forClass(MediaType.class); - Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setEntity(entityPayload.capture(), - payloadMediaType.capture()); - assertNotNull(entityPayload.getValue()); + /** + * There should be an even divide of suggestions per search provider relative + * to the suggestions available per search provider. + * Alpha has 45 suggestions + * Bravo has 1 suggestion + * Gamma has 99 suggestions + * + * We only asked for 13 suggestions to be returned, so based on the suggestion + * distribution algorithm we will get a fair distribution of suggestions per provider + * relative to what each provider has available. Resulting in: + * 6 from Alpha + * 1 from Bravo + * 6 from Gamma + * + */ - ArgumentCaptor<Response> responseObject = ArgumentCaptor.forClass(Response.class); - Mockito.verify(mockResponseMessage, Mockito.atLeast(1)).setBody(responseObject.capture()); - assertEquals(MediaType.APPLICATION_JSON, payloadMediaType.getValue()); + assertEquals( 6, countSuggestions("alpha", suggestions)); + assertEquals( 1, countSuggestions("bravo", suggestions)); + assertEquals( 6, countSuggestions("gamma", suggestions)); - JSONObject response = new JSONObject(entityPayload.getValue()); - JSONArray pers = response.getJSONArray("perspectives"); - assertNotNull(pers); - assertEquals(3, pers.length()); - assertEquals("Two", pers.get(1)); } - @Ignore @Test - public void testExternalRequestEntitySearch_search_with_valid_payload() - throws JsonProcessingException { - initializeSearchMocks(getExternalSearchRequestJson()); + public void testSearch_search_when_ThreeSearchProviders_wantedMoreSuggestionsThanAvailable() throws IOException { + + // mock env setup + + initializeSearchMocks(getSearchRequestJson("vnfs",13)); SearchProviderRegistry searchProviderRegistry = new SearchProviderRegistry(); @@ -612,12 +494,12 @@ public class UnifiedSearchProcessorTest { unifiedSearchProcessor.setSearchProviderRegistry(searchProviderRegistry); - addSuggestion("testView", "testView", "ad74nw8foihdfd8", alpha); - addSuggestion("notTestView", "this is text", "dujf7s423k", bravo); - addSuggestion("superTestView", "this is text", "kjd8fuds75", gamma); + addSuggestions(1,"alpha",alpha); + addSuggestions(4,"bravo",bravo); + addSuggestions(0,"gamma",gamma); // method under test - // unifiedSearchProcessor.externalRequestEntitySearch(mockExchange); + unifiedSearchProcessor.search(mockExchange); ArgumentCaptor<Status> responseCodeCaptor = ArgumentCaptor.forClass(Status.class); Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture()); @@ -629,16 +511,19 @@ public class UnifiedSearchProcessorTest { payloadMediaType.capture()); assertNotNull(entityPayload.getValue()); - ArgumentCaptor<Response> responseObject = ArgumentCaptor.forClass(Response.class); - Mockito.verify(mockResponseMessage, Mockito.atLeast(1)).setBody(responseObject.capture()); - assertEquals(MediaType.APPLICATION_JSON, payloadMediaType.getValue()); - JSONObject response = new JSONObject(entityPayload.getValue()); + + assertEquals(response.getInt("totalFound"),5); + JSONArray suggestions = response.getJSONArray("suggestions"); + assertNotNull(suggestions); + + assertEquals(suggestions.length(),5); - assertEquals(1, suggestions.length()); + assertEquals( 1, countSuggestions("alpha", suggestions)); + assertEquals( 4, countSuggestions("bravo", suggestions)); + assertEquals( 0, countSuggestions("gamma", suggestions)); - int totalFound = response.getInt("totalFound"); - assertEquals(1, totalFound); } + } diff --git a/src/test/java/org/onap/aai/sparky/search/filters/FilterProcessorTest.java b/src/test/java/org/onap/aai/sparky/search/filters/FilterProcessorTest.java index b294d27..1a21691 100644 --- a/src/test/java/org/onap/aai/sparky/search/filters/FilterProcessorTest.java +++ b/src/test/java/org/onap/aai/sparky/search/filters/FilterProcessorTest.java @@ -24,7 +24,7 @@ */ package org.onap.aai.sparky.search.filters; - +/* import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -99,11 +99,10 @@ public class FilterProcessorTest { FiltersConfig viewFilterConfig = FiltersConfig.getInstance(); List<UiViewListItemConfig> views = new ArrayList<UiViewListItemConfig>(); - + // Default filter value to use below - UiFilterOptionsValuesConfig defaultValue = - new UiFilterOptionsValuesConfig("Today", "Last 0 hours"); - + UiFilterOptionsValuesConfig defaultValue = new UiFilterOptionsValuesConfig("Today", "Last 0 hours"); + // VNF View - 4 Filters ViewConfiguration vnfViewConfig = new ViewConfiguration("vnfSearch"); vnfViewConfig.addViewFilter(new ViewFilter("1", null)); @@ -111,7 +110,7 @@ public class FilterProcessorTest { vnfViewConfig.addViewFilter(new ViewFilter("7", null)); vnfViewConfig.addViewFilter(new ViewFilter("8", null)); views.add(generateViewConfig(vnfViewConfig)); - + // View and Inspect (Schema) - 0 Filters ViewConfiguration viewInspectConfig = new ViewConfiguration("viewInspect"); views.add(generateViewConfig(viewInspectConfig)); @@ -123,11 +122,11 @@ public class FilterProcessorTest { dataIntegrityConfig.addViewFilter(new ViewFilter("5", defaultValue)); dataIntegrityConfig.addViewFilter(new ViewFilter("6", null)); views.add(generateViewConfig(dataIntegrityConfig)); - + uiViewsConfig.setViews(views); viewFilterConfig.setViewsConfig(uiViewsConfig); - + List<UiFilterOptionsValuesConfig> optionsValues = new ArrayList<UiFilterOptionsValuesConfig>(); optionsValues.add(new UiFilterOptionsValuesConfig("Today", "Last 0 hours")); optionsValues.add(new UiFilterOptionsValuesConfig("Since Yesterday", "Last 24 hours")); @@ -135,27 +134,19 @@ public class FilterProcessorTest { optionsValues.add(new UiFilterOptionsValuesConfig("Since Last Month", "Last 30 days")); optionsValues.add(new UiFilterOptionsValuesConfig("Custom Range", "Custom Range")); - - + + FiltersDetailsConfig uiFiltersConfig = new FiltersDetailsConfig(); List<UiFilterConfig> uiFilterConfig = new ArrayList<UiFilterConfig>(); - uiFilterConfig.add(new UiFilterConfig("1", "filterName1", "Display Name 1", "dropDown", "false", - "Any 1", null, "options", null, null)); - uiFilterConfig.add(new UiFilterConfig("2", "filterName2", "Display Name 2", "dropDown", "false", - "Any 2", null, "options", null, null)); - uiFilterConfig.add(new UiFilterConfig("3", "filterName3", "Display Name 3", "dropDown", "false", - "Any 3", null, "options", null, null)); - uiFilterConfig.add(new UiFilterConfig("4", "filterName4", "Display Name 4", "dropDown", "false", - "Any 4", null, "options", null, null)); - uiFilterConfig.add(new UiFilterConfig("5", "filterName5", "Display Name 5", "date", "false", - "Any 5", defaultValue, "dynamicOptions", optionsValues, null)); - uiFilterConfig.add(new UiFilterConfig("6", "filterName6", "Display Name 6", "dropDown", "false", - "Any 6", null, "options", null, null)); - uiFilterConfig.add(new UiFilterConfig("7", "filterName7", "Display Name 7", "dropDown", "false", - "Any 7", null, "options", null, null)); - uiFilterConfig.add(new UiFilterConfig("8", "filterName8", "Display Name 8", "dropDown", "false", - "Any 8", null, "options", null, null)); + uiFilterConfig.add(new UiFilterConfig("1", "filterName1", "Display Name 1", "dropDown", "false", "Any 1", null, "options", null, null)); + uiFilterConfig.add(new UiFilterConfig("2", "filterName2", "Display Name 2", "dropDown", "false", "Any 2", null, "options", null, null)); + uiFilterConfig.add(new UiFilterConfig("3", "filterName3", "Display Name 3", "dropDown", "false", "Any 3", null, "options", null, null)); + uiFilterConfig.add(new UiFilterConfig("4", "filterName4", "Display Name 4", "dropDown", "false", "Any 4", null, "options", null, null)); + uiFilterConfig.add(new UiFilterConfig("5", "filterName5", "Display Name 5", "date", "false", "Any 5", defaultValue, "dynamicOptions", optionsValues, null)); + uiFilterConfig.add(new UiFilterConfig("6", "filterName6", "Display Name 6", "dropDown", "false", "Any 6", null, "options", null, null)); + uiFilterConfig.add(new UiFilterConfig("7", "filterName7", "Display Name 7", "dropDown", "false", "Any 7", null, "options", null, null)); + uiFilterConfig.add(new UiFilterConfig("8", "filterName8", "Display Name 8", "dropDown", "false", "Any 8", null, "options", null, null)); uiFiltersConfig.setFilters(uiFilterConfig); @@ -172,6 +163,8 @@ public class FilterProcessorTest { mockRestletRequest = Mockito.mock(Request.class); mockRestletResponse = Mockito.mock(Response.class); +TODO-> edit the following:FilteredSearchHelper & FilterProcessor to pass in the correct parameters + filteredSearchHelper = new FilteredSearchHelper(generateDefaultViewsFilterConfig()); filterProcessor = new FilterProcessor(filteredSearchHelper); @@ -185,17 +178,16 @@ public class FilterProcessorTest { assertNotNull(filterProcessor.getFilteredSearchHelper()); } - private void verifyResponseAndNumFiltersForBadRequest(Status expectedStatus, - int numExpectedFilters) throws JsonParseException, JsonMappingException, IOException { - + private void verifyResponseAndNumFiltersForBadRequest(Status expectedStatus, int numExpectedFilters) + throws JsonParseException, JsonMappingException, IOException { + ArgumentCaptor<Status> responseCodeCaptor = ArgumentCaptor.forClass(Status.class); Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture()); assertEquals(expectedStatus, responseCodeCaptor.getValue()); ArgumentCaptor<String> entityPayload = ArgumentCaptor.forClass(String.class); ArgumentCaptor<MediaType> payloadMediaType = ArgumentCaptor.forClass(MediaType.class); - Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setEntity(entityPayload.capture(), - payloadMediaType.capture()); + Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setEntity(entityPayload.capture(), payloadMediaType.capture()); assertNotNull(entityPayload.getValue()); ArgumentCaptor<Response> responseObject = ArgumentCaptor.forClass(Response.class); @@ -204,28 +196,28 @@ public class FilterProcessorTest { JsonReader jsonReader = Json.createReader(new StringReader(entityPayload.getValue())); JsonObject responsePayload = jsonReader.readObject(); - + JsonObject filters = responsePayload.getJsonObject("filters"); assertEquals(0, filters.size()); } private void initializeMocks(String requestPayload) { - + Mockito.when(mockRequestMessage.getBody(String.class)).thenReturn(requestPayload); Mockito.when(mockExchange.getIn()).thenReturn(mockRequestMessage); Mockito.when(mockExchange.getOut()).thenReturn(mockResponseMessage); Mockito.when(mockRequestMessage.getHeader(RestletConstants.RESTLET_REQUEST, Request.class)) - .thenReturn(mockRestletRequest); + .thenReturn(mockRestletRequest); Mockito.when(mockRequestMessage.getHeader(RestletConstants.RESTLET_RESPONSE, Response.class)) - .thenReturn(mockRestletResponse); + .thenReturn(mockRestletResponse); } @Test public void testGetFiltersWithValues_success_path() throws IOException { - + // Initialize for call against 'vnfSearch' DiscoverFiltersRequest vnfSearchrequest = new DiscoverFiltersRequest(); vnfSearchrequest.setViewName("vnfSearch"); @@ -236,76 +228,71 @@ public class FilterProcessorTest { filterProcessor.getFiltersWithValues(mockExchange); ArgumentCaptor<Status> vnfResponseCodeCaptor = ArgumentCaptor.forClass(Status.class); - Mockito.verify(mockRestletResponse, Mockito.atLeast(1)) - .setStatus(vnfResponseCodeCaptor.capture()); + Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setStatus(vnfResponseCodeCaptor.capture()); assertEquals(Status.SUCCESS_OK, vnfResponseCodeCaptor.getValue()); ArgumentCaptor<String> vnfEntityPayload = ArgumentCaptor.forClass(String.class); ArgumentCaptor<MediaType> vnfPayloadMediaType = ArgumentCaptor.forClass(MediaType.class); - Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setEntity(vnfEntityPayload.capture(), - vnfPayloadMediaType.capture()); + Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setEntity(vnfEntityPayload.capture(), vnfPayloadMediaType.capture()); assertNotNull(vnfEntityPayload.getValue()); ArgumentCaptor<Response> vnfResponseObject = ArgumentCaptor.forClass(Response.class); Mockito.verify(mockResponseMessage, Mockito.atLeast(1)).setBody(vnfResponseObject.capture()); assertEquals(MediaType.APPLICATION_JSON, vnfPayloadMediaType.getValue()); - + JsonReader vnfJsonReader = Json.createReader(new StringReader(vnfEntityPayload.getValue())); JsonObject vnfResponsePayload = vnfJsonReader.readObject(); JsonObject vnfFilters = vnfResponsePayload.getJsonObject("filters"); assertNotNull(vnfFilters); assertEquals(4, vnfFilters.size()); - + JsonObject filterOne = vnfFilters.getJsonObject("1"); assertNotNull(filterOne); assertEquals("Display Name 1", filterOne.getString("label")); - + JsonObject filterEight = vnfFilters.getJsonObject("8"); assertNotNull(filterEight); - JsonObject eightInnerControl = - filterEight.getJsonObject("controls").getJsonObject("filterName8"); + JsonObject eightInnerControl = filterEight.getJsonObject("controls").getJsonObject("filterName8"); assertEquals(4, eightInnerControl.size()); assertEquals("dropDown", eightInnerControl.getString("type")); assertEquals("false", eightInnerControl.getString("multiSelect")); assertEquals("Any 8", eightInnerControl.getString("watermark")); assertEquals(0, eightInnerControl.getJsonArray("options").size()); - + // Initialize for call against 'dataIntegrity' DiscoverFiltersRequest dataIntegrityRequest = new DiscoverFiltersRequest(); dataIntegrityRequest.setViewName("dataIntegrity"); initializeMocks(NodeUtils.convertObjectToJson(dataIntegrityRequest, false)); - + // Test call against 'dataIntegrity' filterProcessor.getFiltersWithValues(mockExchange); - + ArgumentCaptor<Status> dIResponseCodeCaptor = ArgumentCaptor.forClass(Status.class); - Mockito.verify(mockRestletResponse, Mockito.atLeast(1)) - .setStatus(dIResponseCodeCaptor.capture()); + Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setStatus(dIResponseCodeCaptor.capture()); assertEquals(Status.SUCCESS_OK, dIResponseCodeCaptor.getValue()); ArgumentCaptor<String> dIEntityPayload = ArgumentCaptor.forClass(String.class); ArgumentCaptor<MediaType> dIPayloadMediaType = ArgumentCaptor.forClass(MediaType.class); - Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setEntity(dIEntityPayload.capture(), - dIPayloadMediaType.capture()); + Mockito.verify(mockRestletResponse, Mockito.atLeast(1)).setEntity(dIEntityPayload.capture(), dIPayloadMediaType.capture()); assertNotNull(dIEntityPayload.getValue()); ArgumentCaptor<Response> dIResponseObject = ArgumentCaptor.forClass(Response.class); Mockito.verify(mockResponseMessage, Mockito.atLeast(1)).setBody(dIResponseObject.capture()); assertEquals(MediaType.APPLICATION_JSON, dIPayloadMediaType.getValue()); - + JsonReader dIJsonReader = Json.createReader(new StringReader(dIEntityPayload.getValue())); JsonObject dIResponsePayload = dIJsonReader.readObject(); - + JsonObject dIFilters = dIResponsePayload.getJsonObject("filters"); assertNotNull(dIFilters); assertEquals(4, dIFilters.size()); - + JsonObject filterFour = dIFilters.getJsonObject("4"); assertNotNull(filterFour); assertEquals("Display Name 4", filterFour.getString("label")); - + JsonObject filterFive = dIFilters.getJsonObject("5"); assertNotNull(filterFive); JsonObject fiveInnerControl = filterFive.getJsonObject("controls").getJsonObject("filterName5"); @@ -321,7 +308,7 @@ public class FilterProcessorTest { @Test public void testGetFiltersWithValues_viewNameNull() throws IOException { - + DiscoverFiltersRequest discoverFiltersRequest = new DiscoverFiltersRequest(); initializeMocks(NodeUtils.convertObjectToJson(discoverFiltersRequest, false)); @@ -333,7 +320,7 @@ public class FilterProcessorTest { @Test public void testGetFiltersWithValues_viewNameEmptyString() throws IOException { - + DiscoverFiltersRequest discoverFiltersRequest = new DiscoverFiltersRequest(); discoverFiltersRequest.setViewName(""); @@ -347,7 +334,7 @@ public class FilterProcessorTest { @Test public void testGetFiltersWithValues_requestPayloadIsNull() throws IOException { - + initializeMocks(null); // Method under test @@ -358,7 +345,7 @@ public class FilterProcessorTest { @Test public void testGetFiltersWithValues_requestPayloadIsEmptyString() throws IOException { - + initializeMocks(""); // Method under test @@ -369,7 +356,7 @@ public class FilterProcessorTest { @Test public void testGetFiltersWithValues_requestPayloadCausesException() throws IOException { - + initializeMocks("{"); // Method under test @@ -377,4 +364,4 @@ public class FilterProcessorTest { verifyResponseAndNumFiltersForBadRequest(Status.SUCCESS_OK, 0); } -} +}*/ diff --git a/src/test/java/org/onap/aai/sparky/search/filters/FilteredSearchHelperTest.java b/src/test/java/org/onap/aai/sparky/search/filters/FilteredSearchHelperTest.java index 062aa04..56afcf9 100644 --- a/src/test/java/org/onap/aai/sparky/search/filters/FilteredSearchHelperTest.java +++ b/src/test/java/org/onap/aai/sparky/search/filters/FilteredSearchHelperTest.java @@ -33,7 +33,7 @@ import org.junit.BeforeClass; import org.junit.Test; import org.onap.aai.sparky.search.filters.FilteredSearchHelper; import org.onap.aai.sparky.search.filters.config.FiltersConfig; - +/* public class FilteredSearchHelperTest { private static FilteredSearchHelper filteredSearchHelper; @@ -47,7 +47,7 @@ public class FilteredSearchHelperTest { config.setViewsConfig(config.readUiViewsConfig()); System.out.println("SETTING UIFILTERSCONFIG"); config.setFiltersConfig(config.readUiFiltersConfig()); - + filteredSearchHelper = new FilteredSearchHelper(config); } @@ -66,4 +66,4 @@ public class FilteredSearchHelperTest { public void testDoFilterDiscovery_invalidViewName_emptyString() { assertEquals(0, filteredSearchHelper.doFilterDiscovery("").getFilters().size()); } -} +}*/ diff --git a/src/test/java/org/onap/aai/sparky/search/filters/entity/DiscoverFiltersRequest.java b/src/test/java/org/onap/aai/sparky/search/filters/entity/DiscoverFiltersRequest.java index f836821..336e3b1 100644 --- a/src/test/java/org/onap/aai/sparky/search/filters/entity/DiscoverFiltersRequest.java +++ b/src/test/java/org/onap/aai/sparky/search/filters/entity/DiscoverFiltersRequest.java @@ -36,5 +36,5 @@ public class DiscoverFiltersRequest { public void setViewName(String viewName) { this.viewName = viewName; } - + } diff --git a/src/test/java/org/onap/aai/sparky/security/portal/TestPortalRestAPIServiceImpl.java b/src/test/java/org/onap/aai/sparky/security/portal/TestPortalRestAPIServiceImpl.java index 7ce77c2..222c83c 100644 --- a/src/test/java/org/onap/aai/sparky/security/portal/TestPortalRestAPIServiceImpl.java +++ b/src/test/java/org/onap/aai/sparky/security/portal/TestPortalRestAPIServiceImpl.java @@ -63,9 +63,9 @@ import org.powermock.core.classloader.annotations.PrepareForTest; import org.powermock.modules.junit4.PowerMockRunner; import org.powermock.reflect.Whitebox; -@PowerMockIgnore({"javax.crypto.*"}) +@PowerMockIgnore({ "javax.crypto.*" }) @RunWith(PowerMockRunner.class) -@PrepareForTest({PortalAuthenticationConfig.class, RolesConfig.class}) +@PrepareForTest({ PortalAuthenticationConfig.class, RolesConfig.class }) public class TestPortalRestAPIServiceImpl { private static File testUsersFile; @@ -75,19 +75,13 @@ public class TestPortalRestAPIServiceImpl { enum TestData { // @formatter:off - TEST_USERS("src/test/resources/portal/test-users.config"), PORTAL_AUTHENTICATION_PROPERTIES( - "src/test/resources/portal/portal-authentication.properties"), ROLES_CONFIG_FILE( - "src/test/resources/portal/roles.config"); + TEST_USERS ("src/test/resources/portal/test-users.config"), + PORTAL_AUTHENTICATION_PROPERTIES ("src/test/resources/portal/portal-authentication.properties"), + ROLES_CONFIG_FILE ("src/test/resources/portal/roles.config"); private String filename; - - TestData(String filename) { - this.filename = filename; - } - - public String getFilename() { - return this.filename; - } + TestData(String filename) {this.filename = filename;} + public String getFilename() {return this.filename;} // @formatter:on } @@ -286,4 +280,4 @@ public class TestPortalRestAPIServiceImpl { assertThat(portalApi.isAppAuthenticated(request), is(true)); } -} +}
\ No newline at end of file diff --git a/src/test/java/org/onap/aai/sparky/security/portal/TestUserManager.java b/src/test/java/org/onap/aai/sparky/security/portal/TestUserManager.java index 521ca78..c34854a 100644 --- a/src/test/java/org/onap/aai/sparky/security/portal/TestUserManager.java +++ b/src/test/java/org/onap/aai/sparky/security/portal/TestUserManager.java @@ -72,20 +72,14 @@ public class TestUserManager { enum TestData { // @formatter:off - NO_FILE("src/test/resources/portal/no-users.config"), CONCURRENT_USERS( - "src/test/resources/portal/concurrent-users.config"), CONCURRENT_EDIT_USERS( - "src/test/resources/portal/concurrent-edit-users.config"); - // ROLES_CONFIG_FILE ("src/test/resources/portal/roles.config"); + NO_FILE ("src/test/resources/portal/no-users.config"), + CONCURRENT_USERS ("src/test/resources/portal/concurrent-users.config"), + CONCURRENT_EDIT_USERS ("src/test/resources/portal/concurrent-edit-users.config"); +// ROLES_CONFIG_FILE ("src/test/resources/portal/roles.config"); private String filename; - - TestData(String filename) { - this.filename = filename; - } - - public String getFilename() { - return this.filename; - } + TestData(String filename) {this.filename = filename;} + public String getFilename() {return this.filename;} // @formatter:on } @@ -137,8 +131,8 @@ public class TestUserManager { return pushTask(concurrentUsers, String.valueOf(NodeUtils.getRandomTxnId())); }; - List<Callable<EcompUser>> callables = - Arrays.asList(pushTask, pushTask, pushTask, pushTask, pushTask); + List<Callable<EcompUser>> callables = Arrays.asList(pushTask, pushTask, pushTask, pushTask, + pushTask); ExecutorService executor = Executors.newWorkStealingPool(); executor.invokeAll(callables).stream().map(future -> { @@ -180,9 +174,9 @@ public class TestUserManager { return editTask(LOGINID_3, "Amy"); }; - List<Callable<EcompUser>> callables = - Arrays.asList(pushTaskRandomId, pushTaskRandomId, pushTaskId3, editTaskId1, - pushTaskRandomId, pushTaskRandomId, editTaskId3, editTaskId2, pushTaskRandomId); + List<Callable<EcompUser>> callables = Arrays.asList(pushTaskRandomId, pushTaskRandomId, + pushTaskId3, editTaskId1, pushTaskRandomId, pushTaskRandomId, editTaskId3, editTaskId2, + pushTaskRandomId); ExecutorService executor = Executors.newWorkStealingPool(); List<EcompUser> userTasks = executor.invokeAll(callables).stream().map(future -> { @@ -268,4 +262,4 @@ public class TestUserManager { return user; } -} +}
\ No newline at end of file diff --git a/src/test/java/org/onap/aai/sparky/synchronizer/IndexDocumentTest.java b/src/test/java/org/onap/aai/sparky/synchronizer/IndexDocumentTest.java index 42db5c9..0451ec5 100644 --- a/src/test/java/org/onap/aai/sparky/synchronizer/IndexDocumentTest.java +++ b/src/test/java/org/onap/aai/sparky/synchronizer/IndexDocumentTest.java @@ -44,7 +44,7 @@ import ch.qos.logback.classic.Level; public class IndexDocumentTest { private LogValidator logValidator; - + /** * Inits the. diff --git a/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerBuilder.java b/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerBuilder.java index c5ca731..84d7fd2 100644 --- a/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerBuilder.java +++ b/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerBuilder.java @@ -30,426 +30,483 @@ package org.onap.aai.sparky.synchronizer; */ public class SyncControllerBuilder { - + /* * We'll have to revisit this class, as the sync controllers are wired up pretty differently now */ - + /** * Test elastic search update api. */ - /* - * public void testElasticSearchUpdateApi() { try { - * - * RestClientBuilder clientBuilder = new RestClientBuilder(); clientBuilder.setUseHttps(false); - * - * RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); - * - * ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); ElasticSearchDataProvider - * elasticSearchDataProvider = new ElasticSearchAdapter(nonCachingRestProvider, esConfig); - * - * String payload = - * "{ \"entityType\": \"complex\", \"pkey\": \"MORRISTOWN0075\", \"location\": { \"lat\": \"40.793414\", \"lon\": \"-74.480432\" }, \"selfLink\": \"https://aai-int1.test.att.com:8443/aai/v8/cloud-infrastructure/complexes/complex/MORRISTOWN0075?nodes-only\" }\n" - * ; - * - * String updateRequest = elasticSearchDataProvider.buildBulkImportOperationRequest( - * "topographysearchindex-localhost", "default", - * "1e2a6ba9e09d5e1bcb016b3a0b8d50273b42828e47957bd2a2f3ce1854744f5f", "6", payload); - * - * OperationResult or = elasticSearchDataProvider.doBulkOperation("http://localhost:9200/_bulk", - * updateRequest); - * - * System.out.println(or.toString()); - * - * /* String BULK_IMPORT_INDEX_TEMPLATE = - * "{\"index\":{\"_index\":\"%s\",\"_type\":\"%s\",\"_id\":\"%s\", \"_version\":\"%s\"}}\n"; - * - * StringBuilder updateRequestPayload = new StringBuilder(128); - * updateRequestPayload.append(String.format(BULK_IMPORT_INDEX_TEMPLATE, - * "topographysearchindex-localhost", "default", - * "1e2a6ba9e09d5e1bcb016b3a0b8d50273b42828e47957bd2a2f3ce1854744f5f", "5")); - * - * - * updateRequestPayload.append(payload); - * - * OperationResult or = nonCachingRestProvider.doRestfulOperation(HttpMethod.PUT, - * "http://localhost:9200/_bulk", updateRequestPayload.toString(), - * RestfulDataAccessor.APPLICATION_X_WWW_FORM_URL_ENCODED, RestfulDataAccessor.APPLICATION_JSON); - */ +/* public void testElasticSearchUpdateApi() { + try { + RestClientBuilder clientBuilder = new RestClientBuilder(); + clientBuilder.setUseHttps(false); - /* - * } catch (Exception exc) { exc.printStackTrace(); System.out.println( - * "Error: failed to sync with message = " + exc.getMessage()); } } - * - * /** Do historical entity sync. + RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); + + ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); + ElasticSearchDataProvider elasticSearchDataProvider = + new ElasticSearchAdapter(nonCachingRestProvider, esConfig); + + String payload = + "{ \"entityType\": \"complex\", \"pkey\": \"MORRISTOWN0075\", \"location\": { \"lat\": \"40.793414\", \"lon\": \"-74.480432\" }, \"selfLink\": \"https://aai-int1.test.att.com:8443/aai/v8/cloud-infrastructure/complexes/complex/MORRISTOWN0075?nodes-only\" }\n"; + + String updateRequest = elasticSearchDataProvider.buildBulkImportOperationRequest( + "topographysearchindex-localhost", "default", + "1e2a6ba9e09d5e1bcb016b3a0b8d50273b42828e47957bd2a2f3ce1854744f5f", "6", payload); + + OperationResult or = + elasticSearchDataProvider.doBulkOperation("http://localhost:9200/_bulk", updateRequest); + + System.out.println(or.toString()); + + /* + * String BULK_IMPORT_INDEX_TEMPLATE = + * "{\"index\":{\"_index\":\"%s\",\"_type\":\"%s\",\"_id\":\"%s\", \"_version\":\"%s\"}}\n"; + * + * StringBuilder updateRequestPayload = new StringBuilder(128); + * updateRequestPayload.append(String.format(BULK_IMPORT_INDEX_TEMPLATE, + * "topographysearchindex-localhost", "default", + * "1e2a6ba9e09d5e1bcb016b3a0b8d50273b42828e47957bd2a2f3ce1854744f5f", "5")); + * + * + * updateRequestPayload.append(payload); + * + * OperationResult or = nonCachingRestProvider.doRestfulOperation(HttpMethod.PUT, + * "http://localhost:9200/_bulk", updateRequestPayload.toString(), + * RestfulDataAccessor.APPLICATION_X_WWW_FORM_URL_ENCODED, + * RestfulDataAccessor.APPLICATION_JSON); + */ + + +/* + } catch (Exception exc) { + exc.printStackTrace(); + System.out.println("Error: failed to sync with message = " + exc.getMessage()); + } + } + + /** + * Do historical entity sync. *//* - * public void doHistoricalEntitySync() { try { SyncController syncController = new - * SyncControllerImpl("historicalEntityTestController"); - * - * ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new OxmModelLoader(), new - * RestClientBuilder()); - * - * RestClientBuilder clientBuilder = new RestClientBuilder(); clientBuilder.setUseHttps(false); - * - * RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); - * - * ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); - * - * ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider,esConfig); - * - * - * IndexIntegrityValidator entityCounterHistoryValidator = new - * IndexIntegrityValidator(nonCachingRestProvider, esConfig.getEntityCountHistoryIndex(), - * esConfig.getType(), esConfig.getIpAddress(), esConfig.getHttpPort(), - * esConfig.buildElasticSearchEntityCountHistoryTableConfig()); - * - * syncController.registerIndexValidator(entityCounterHistoryValidator); - * - * - * ////// - * - * - * - * HistoricalEntitySummarizer historicalSummarizer = new - * HistoricalEntitySummarizer(esConfig.getEntityCountHistoryIndex()); - * historicalSummarizer.setAaiDataProvider(aaiAdapter); - * historicalSummarizer.setEsDataProvider(esAdapter); - * syncController.registerEntitySynchronizer(historicalSummarizer); - * - * //// - * - * /* IndexIntegrityValidator entitySearchIndexValidator = new IndexIntegrityValidator(new - * RestClientBuilder()); - * - * entitySearchIndexValidator.setIndexName("topographysearchindex-localhost"); - * entitySearchIndexValidator.setIndexType("default"); - * entitySearchIndexValidator.setIndexSettings(""); - * entitySearchIndexValidator.setIndexSettings(""); - * - * syncController.registerIndexValidator(entitySearchIndexValidator); - */ + public void doHistoricalEntitySync() { + try { + SyncController syncController = new SyncControllerImpl("historicalEntityTestController"); - //// + ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new OxmModelLoader(), new RestClientBuilder()); - /* - * IndexCleaner index1Cleaner = new ElasticSearchIndexCleaner(nonCachingRestProvider, - * "topographysearchindex-localhost", "default", "127.0.0.1", "9200", 5, 5000); - */ + RestClientBuilder clientBuilder = new RestClientBuilder(); + clientBuilder.setUseHttps(false); - // syncController.registerIndexCleaner(index1Cleaner); + RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); - /// - /* - * for (int x = 0; x < 10; x++) { - * - * syncController.performAction(SyncActions.SYNCHRONIZE); - * - * while (syncController.getState() == SynchronizerState.PERFORMING_SYNCHRONIZATION) { - * - * System.out.println("sync controller state = " + syncController.getState()); - * - * Thread.sleep(1000); } } - * - * syncController.shutdown(); - * - * } catch (Exception exc) { exc.printStackTrace(); System.out.println( - * "Error: failed to sync with message = " + exc.getMessage()); } } - * - * /** Do geo entity sync. + ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); + + ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider,esConfig); + + + IndexIntegrityValidator entityCounterHistoryValidator = + new IndexIntegrityValidator(nonCachingRestProvider, esConfig.getEntityCountHistoryIndex(), + esConfig.getType(), esConfig.getIpAddress(), esConfig.getHttpPort(), + esConfig.buildElasticSearchEntityCountHistoryTableConfig()); + + syncController.registerIndexValidator(entityCounterHistoryValidator); + + + ////// + + + + HistoricalEntitySummarizer historicalSummarizer = + new HistoricalEntitySummarizer(esConfig.getEntityCountHistoryIndex()); + historicalSummarizer.setAaiDataProvider(aaiAdapter); + historicalSummarizer.setEsDataProvider(esAdapter); + syncController.registerEntitySynchronizer(historicalSummarizer); + + //// + + /* + * IndexIntegrityValidator entitySearchIndexValidator = new IndexIntegrityValidator(new + * RestClientBuilder()); + * + * entitySearchIndexValidator.setIndexName("topographysearchindex-localhost"); + * entitySearchIndexValidator.setIndexType("default"); + * entitySearchIndexValidator.setIndexSettings(""); + * entitySearchIndexValidator.setIndexSettings(""); + * + * syncController.registerIndexValidator(entitySearchIndexValidator); + */ + + //// + + /* + * IndexCleaner index1Cleaner = new ElasticSearchIndexCleaner(nonCachingRestProvider, + * "topographysearchindex-localhost", "default", "127.0.0.1", "9200", 5, 5000); + */ + + // syncController.registerIndexCleaner(index1Cleaner); + + /// +/* + for (int x = 0; x < 10; x++) { + + syncController.performAction(SyncActions.SYNCHRONIZE); + + while (syncController.getState() == SynchronizerState.PERFORMING_SYNCHRONIZATION) { + + System.out.println("sync controller state = " + syncController.getState()); + + Thread.sleep(1000); + } + } + + syncController.shutdown(); + + } catch (Exception exc) { + exc.printStackTrace(); + System.out.println("Error: failed to sync with message = " + exc.getMessage()); + } + } + + /** + * Do geo entity sync. *//* - * public void doGeoEntitySync() { try { - * - * ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new OxmModelLoader(), new - * RestClientBuilder()); - * - * RestClientBuilder clientBuilder = new RestClientBuilder(); clientBuilder.setUseHttps(false); - * - * RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); - * ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); - * - * ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider,esConfig); - * - * IndexIntegrityValidator entitySearchIndexValidator = new - * IndexIntegrityValidator(nonCachingRestProvider, esConfig.getIndexName(), esConfig.getType(), - * esConfig.getIpAddress(), esConfig.getHttpPort(), esConfig.buildElasticSearchTableConfig()); - * - * SyncController syncController = new SyncControllerImpl("geoEntitySyncTestController"); - * syncController.registerIndexValidator(entitySearchIndexValidator); - * - * - * ////// - * - * GeoSynchronizer geoSync = new GeoSynchronizer("topographysearchindex-localhost"); - * geoSync.setAaiDataProvider(aaiAdapter); geoSync.setEsDataProvider(esAdapter); - * syncController.registerEntitySynchronizer(geoSync); - * - * //// - * - * /* IndexIntegrityValidator entitySearchIndexValidator = new IndexIntegrityValidator(new - * RestClientBuilder()); - * - * entitySearchIndexValidator.setIndexName("topographysearchindex-localhost"); - * entitySearchIndexValidator.setIndexType("default"); - * entitySearchIndexValidator.setIndexSettings(""); - * entitySearchIndexValidator.setIndexSettings(""); - * - * syncController.registerIndexValidator(entitySearchIndexValidator); - */ + public void doGeoEntitySync() { + try { - //// + ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new OxmModelLoader(), new RestClientBuilder()); - /* - * IndexCleaner index1Cleaner = new ElasticSearchIndexCleaner(nonCachingRestProvider, - * "topographysearchindex-localhost", "default", "127.0.0.1", "9200", 5, 5000); - */ + RestClientBuilder clientBuilder = new RestClientBuilder(); + clientBuilder.setUseHttps(false); - // syncController.registerIndexCleaner(index1Cleaner); + RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); + ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); - /// - /* - * syncController.performAction(SyncActions.SYNCHRONIZE); - * - * while (syncController.getState() == SynchronizerState.PERFORMING_SYNCHRONIZATION) { - * Thread.sleep(1000); } - * - * syncController.shutdown(); - * - * } catch (Exception exc) { exc.printStackTrace(); System.out.println( - * "Error: failed to sync with message = " + exc.getMessage()); } } - * - * /** Do searchable entitysync. + ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider,esConfig); + + IndexIntegrityValidator entitySearchIndexValidator = + new IndexIntegrityValidator(nonCachingRestProvider, esConfig.getIndexName(), + esConfig.getType(), esConfig.getIpAddress(), esConfig.getHttpPort(), + esConfig.buildElasticSearchTableConfig()); + + SyncController syncController = new SyncControllerImpl("geoEntitySyncTestController"); + syncController.registerIndexValidator(entitySearchIndexValidator); + + + ////// + + GeoSynchronizer geoSync = new GeoSynchronizer("topographysearchindex-localhost"); + geoSync.setAaiDataProvider(aaiAdapter); + geoSync.setEsDataProvider(esAdapter); + syncController.registerEntitySynchronizer(geoSync); + + //// + + /* + * IndexIntegrityValidator entitySearchIndexValidator = new IndexIntegrityValidator(new + * RestClientBuilder()); + * + * entitySearchIndexValidator.setIndexName("topographysearchindex-localhost"); + * entitySearchIndexValidator.setIndexType("default"); + * entitySearchIndexValidator.setIndexSettings(""); + * entitySearchIndexValidator.setIndexSettings(""); + * + * syncController.registerIndexValidator(entitySearchIndexValidator); + */ + + //// + + /* + * IndexCleaner index1Cleaner = new ElasticSearchIndexCleaner(nonCachingRestProvider, + * "topographysearchindex-localhost", "default", "127.0.0.1", "9200", 5, 5000); + */ + + // syncController.registerIndexCleaner(index1Cleaner); + + /// +/* + syncController.performAction(SyncActions.SYNCHRONIZE); + + while (syncController.getState() == SynchronizerState.PERFORMING_SYNCHRONIZATION) { + Thread.sleep(1000); + } + + syncController.shutdown(); + + } catch (Exception exc) { + exc.printStackTrace(); + System.out.println("Error: failed to sync with message = " + exc.getMessage()); + } + } + + /** + * Do searchable entitysync. *//* - * public void doSearchableEntitysync() { try { - * - * - * ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new OxmModelLoader(), new - * RestClientBuilder()); - * - * RestClientBuilder clientBuilder = new RestClientBuilder(); clientBuilder.setUseHttps(false); - * - * RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); - * ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); - * - * ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider,esConfig); - * - * ////// - * - * SyncController syncController = new SyncControllerImpl("searchtableEntityTestController"); - * - * ViewInspectEntitySynchronizer ses = new - * ViewInspectEntitySynchronizer("entitysearchindex-localhost"); - * ses.setAaiDataProvider(aaiAdapter); ses.setEsDataProvider(esAdapter); - * syncController.registerEntitySynchronizer(ses); - * - * //// - * - * /* IndexIntegrityValidator entitySearchIndexValidator = new IndexIntegrityValidator(new - * RestClientBuilder()); - * - * entitySearchIndexValidator.setIndexName("esi-sync2-localhost"); - * entitySearchIndexValidator.setIndexType("default"); - * - * syncController.registerIndexValidator(entitySearchIndexValidator); - */ + public void doSearchableEntitysync() { + try { + - //// + ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new OxmModelLoader(), new RestClientBuilder()); - /* - * IndexCleaner index1Cleaner = new ElasticSearchIndexCleaner(nonCachingRestProvider, - * "entitysearchindex-localhost", "default", "127.0.0.1", "9200", 5, 5000); - * - * syncController.registerIndexCleaner(index1Cleaner); - */ + RestClientBuilder clientBuilder = new RestClientBuilder(); + clientBuilder.setUseHttps(false); + + RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); + ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); + + ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider,esConfig); + + ////// + + SyncController syncController = new SyncControllerImpl("searchtableEntityTestController"); + + ViewInspectEntitySynchronizer ses = + new ViewInspectEntitySynchronizer("entitysearchindex-localhost"); + ses.setAaiDataProvider(aaiAdapter); + ses.setEsDataProvider(esAdapter); + syncController.registerEntitySynchronizer(ses); + + //// + + /* + * IndexIntegrityValidator entitySearchIndexValidator = new IndexIntegrityValidator(new + * RestClientBuilder()); + * + * entitySearchIndexValidator.setIndexName("esi-sync2-localhost"); + * entitySearchIndexValidator.setIndexType("default"); + * + * syncController.registerIndexValidator(entitySearchIndexValidator); + */ + + //// + + /* + * IndexCleaner index1Cleaner = new ElasticSearchIndexCleaner(nonCachingRestProvider, + * "entitysearchindex-localhost", "default", "127.0.0.1", "9200", 5, 5000); + * + * syncController.registerIndexCleaner(index1Cleaner); + */ + + /// +/* + syncController.performAction(SyncActions.SYNCHRONIZE); + + while (syncController.getState() == SynchronizerState.PERFORMING_SYNCHRONIZATION) { + Thread.sleep(1000); + } + + syncController.shutdown(); + + } catch (Exception exc) { + exc.printStackTrace(); + System.out.println("Error: failed to sync with message = " + exc.getMessage()); + } + } + + /** + * Do cross entity reference sync. + *//* + public void doCrossEntityReferenceSync() { + try { + + ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new OxmModelLoader(), new RestClientBuilder()); + + RestClientBuilder clientBuilder = new RestClientBuilder(); + clientBuilder.setUseHttps(false); + + RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); + ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); + + ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider,esConfig); + + SyncController syncController = new SyncControllerImpl("crossEntityRefSyncController"); + + CrossEntityReferenceSynchronizer cers = + new CrossEntityReferenceSynchronizer("entitysearchindex-localhost", ActiveInventoryConfig.getConfig()); + cers.setAaiDataProvider(aaiAdapter); + cers.setEsDataProvider(esAdapter); + syncController.registerEntitySynchronizer(cers); + + ViewInspectEntitySynchronizer ses = + new ViewInspectEntitySynchronizer("entitysearchindex-localhost"); + ses.setAaiDataProvider(aaiAdapter); + ses.setEsDataProvider(esAdapter); + syncController.registerEntitySynchronizer(ses); + + ElasticSearchConfig config = ElasticSearchConfig.getConfig(); + + IndexIntegrityValidator entitySearchIndexValidator = new IndexIntegrityValidator( + nonCachingRestProvider, config.getIndexName(), config.getType(), config.getIpAddress(), + config.getHttpPort(), config.buildElasticSearchTableConfig()); + + syncController.registerIndexValidator(entitySearchIndexValidator); + + //// + + IndexCleaner index1Cleaner = + new ElasticSearchIndexCleaner(nonCachingRestProvider, config.getIndexName(), + config.getType(), config.getIpAddress(), config.getHttpPort(), 5, 5000); + + syncController.registerIndexCleaner(index1Cleaner); - /// + /// + + syncController.performAction(SyncActions.SYNCHRONIZE); + + while (syncController.getState() == SynchronizerState.PERFORMING_SYNCHRONIZATION) { + Thread.sleep(1000); + } + + syncController.shutdown(); + + } catch (Exception exc) { + exc.printStackTrace(); + System.out.println("Error: Failed to sync with message = " + exc.getMessage()); + } + } + + /** + * Do suggestion entitysync. + *//* + public void doSuggestionEntitySync() { + try { + ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new OxmModelLoader(), new RestClientBuilder()); + + RestClientBuilder clientBuilder = new RestClientBuilder(); + clientBuilder.setUseHttps(false); + + RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); + ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); + + ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider, esConfig); + + SyncController syncController = new SyncControllerImpl("suggestionEntityTestController"); + + AutosuggestionSynchronizer ses = + new AutosuggestionSynchronizer("entityautosuggestindex-localhost"); + ses.setAaiDataProvider(aaiAdapter); + ses.setEsDataProvider(esAdapter); + syncController.registerEntitySynchronizer(ses); + + syncController.performAction(SyncActions.SYNCHRONIZE); + + while (syncController.getState() == SynchronizerState.PERFORMING_SYNCHRONIZATION) { + Thread.sleep(1000); + } + + syncController.shutdown(); + + } catch (Exception exc) { + exc.printStackTrace(); + System.out.println("Error: failed to sync with message = " + exc.getMessage()); + } + } + /* - * syncController.performAction(SyncActions.SYNCHRONIZE); - * - * while (syncController.getState() == SynchronizerState.PERFORMING_SYNCHRONIZATION) { - * Thread.sleep(1000); } - * - * syncController.shutdown(); - * - * } catch (Exception exc) { exc.printStackTrace(); System.out.println( - * "Error: failed to sync with message = " + exc.getMessage()); } } - * - * /** Do cross entity reference sync. + * Do no op sync. *//* - * public void doCrossEntityReferenceSync() { try { - * - * ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new OxmModelLoader(), new - * RestClientBuilder()); - * - * RestClientBuilder clientBuilder = new RestClientBuilder(); clientBuilder.setUseHttps(false); - * - * RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); - * ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); - * - * ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider,esConfig); - * - * SyncController syncController = new SyncControllerImpl("crossEntityRefSyncController"); - * - * CrossEntityReferenceSynchronizer cers = new - * CrossEntityReferenceSynchronizer("entitysearchindex-localhost", - * ActiveInventoryConfig.getConfig()); cers.setAaiDataProvider(aaiAdapter); - * cers.setEsDataProvider(esAdapter); syncController.registerEntitySynchronizer(cers); - * - * ViewInspectEntitySynchronizer ses = new - * ViewInspectEntitySynchronizer("entitysearchindex-localhost"); - * ses.setAaiDataProvider(aaiAdapter); ses.setEsDataProvider(esAdapter); - * syncController.registerEntitySynchronizer(ses); - * - * ElasticSearchConfig config = ElasticSearchConfig.getConfig(); - * - * IndexIntegrityValidator entitySearchIndexValidator = new IndexIntegrityValidator( - * nonCachingRestProvider, config.getIndexName(), config.getType(), config.getIpAddress(), - * config.getHttpPort(), config.buildElasticSearchTableConfig()); - * - * syncController.registerIndexValidator(entitySearchIndexValidator); - * - * //// - * - * IndexCleaner index1Cleaner = new ElasticSearchIndexCleaner(nonCachingRestProvider, - * config.getIndexName(), config.getType(), config.getIpAddress(), config.getHttpPort(), 5, - * 5000); - * - * syncController.registerIndexCleaner(index1Cleaner); - * - * /// - * - * syncController.performAction(SyncActions.SYNCHRONIZE); - * - * while (syncController.getState() == SynchronizerState.PERFORMING_SYNCHRONIZATION) { - * Thread.sleep(1000); } - * - * syncController.shutdown(); - * - * } catch (Exception exc) { exc.printStackTrace(); System.out.println( - * "Error: Failed to sync with message = " + exc.getMessage()); } } - * - * /** Do suggestion entitysync. - *//* - * public void doSuggestionEntitySync() { try { ActiveInventoryAdapter aaiAdapter = new - * ActiveInventoryAdapter(new OxmModelLoader(), new RestClientBuilder()); + public void doNoOpSync() { + try { + SyncController syncController = new SyncControllerImpl("noopSyncTestController"); + + /* + * ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new RestClientBuilder()); * - * RestClientBuilder clientBuilder = new RestClientBuilder(); - * clientBuilder.setUseHttps(false); + * aaiAdapter.setCacheEnabled(true); * - * RestfulDataAccessor nonCachingRestProvider = new RestfulDataAccessor(clientBuilder); - * ElasticSearchConfig esConfig = ElasticSearchConfig.getConfig(); + * /*InMemoryEntityCache aaiInMemoryCache = new InMemoryEntityCache(); + * aaiAdapter.setEntityCache(aaiInMemoryCache); + */ + + /* + * PersistentEntityCache aaiDiskCache = new PersistentEntityCache(); + * aaiAdapter.setEntityCache(aaiDiskCache); * - * ElasticSearchAdapter esAdapter = new ElasticSearchAdapter(nonCachingRestProvider, - * esConfig); + * ElasticSearchConfig config = ElasticSearchConfig.getConfig(); OXMModelLoader loader = + * OXMModelLoader.getInstance(); SyncAdapter syncAdapter = new SyncAdapter(new + * RestClientBuilder(), config, loader); * - * SyncController syncController = new SyncControllerImpl("suggestionEntityTestController"); + * ////// * - * AutosuggestionSynchronizer ses = new - * AutosuggestionSynchronizer("entityautosuggestindex-localhost"); - * ses.setAaiDataProvider(aaiAdapter); ses.setEsDataProvider(esAdapter); + * SearchableEntitySynchronizer ses = new SearchableEntitySynchronizer(); + * ses.setAaiDataProvider(aaiAdapter); ses.setEsDataProvider(syncAdapter); * syncController.registerEntitySynchronizer(ses); * - * syncController.performAction(SyncActions.SYNCHRONIZE); + * //// * - * while (syncController.getState() == SynchronizerState.PERFORMING_SYNCHRONIZATION) { - * Thread.sleep(1000); } + * IndexIntegrityValidator entitySearchIndexValidator = new IndexIntegrityValidator(new + * RestClientBuilder()); * - * syncController.shutdown(); + * entitySearchIndexValidator.setIndexName("esi-sync2-localhost"); + * entitySearchIndexValidator.setIndexType("default"); + * entitySearchIndexValidator.setIndexSettings(""); + * entitySearchIndexValidator.setIndexSettings(""); * - * } catch (Exception exc) { exc.printStackTrace(); System.out.println( - * "Error: failed to sync with message = " + exc.getMessage()); } } + * syncController.registerIndexValidator(entitySearchIndexValidator); * - * /* Do no op sync. - *//* - * public void doNoOpSync() { try { SyncController syncController = new - * SyncControllerImpl("noopSyncTestController"); - * - * /* ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new - * RestClientBuilder()); - * - * aaiAdapter.setCacheEnabled(true); - * - * /*InMemoryEntityCache aaiInMemoryCache = new InMemoryEntityCache(); - * aaiAdapter.setEntityCache(aaiInMemoryCache); - */ + * //// + * + * ElasticSearchEntityPurger p1 = new ElasticSearchEntityPurger(new RestClientBuilder()); + * p1.setIndexName("esi-blal-blah"); + * + * ElasticSearchEntityPurger p2 = new ElasticSearchEntityPurger(new RestClientBuilder()); + * p2.setIndexName("esi-topo-blah"); + */ + /// +/* + syncController.performAction(SyncActions.SYNCHRONIZE); - /* - * PersistentEntityCache aaiDiskCache = new PersistentEntityCache(); - * aaiAdapter.setEntityCache(aaiDiskCache); - * - * ElasticSearchConfig config = ElasticSearchConfig.getConfig(); OXMModelLoader loader = - * OXMModelLoader.getInstance(); SyncAdapter syncAdapter = new SyncAdapter(new - * RestClientBuilder(), config, loader); - * - * ////// - * - * SearchableEntitySynchronizer ses = new SearchableEntitySynchronizer(); - * ses.setAaiDataProvider(aaiAdapter); ses.setEsDataProvider(syncAdapter); - * syncController.registerEntitySynchronizer(ses); - * - * //// - * - * IndexIntegrityValidator entitySearchIndexValidator = new IndexIntegrityValidator(new - * RestClientBuilder()); - * - * entitySearchIndexValidator.setIndexName("esi-sync2-localhost"); - * entitySearchIndexValidator.setIndexType("default"); - * entitySearchIndexValidator.setIndexSettings(""); - * entitySearchIndexValidator.setIndexSettings(""); - * - * syncController.registerIndexValidator(entitySearchIndexValidator); - * - * //// - * - * ElasticSearchEntityPurger p1 = new ElasticSearchEntityPurger(new RestClientBuilder()); - * p1.setIndexName("esi-blal-blah"); - * - * ElasticSearchEntityPurger p2 = new ElasticSearchEntityPurger(new RestClientBuilder()); - * p2.setIndexName("esi-topo-blah"); - */ - /// - /* - * syncController.performAction(SyncActions.SYNCHRONIZE); - * - * while (syncController.getState() == SynchronizerState.PERFORMING_SYNCHRONIZATION) { - * Thread.sleep(1000); } - * - * syncController.shutdown(); - * - * } catch (Exception exc) { System.out.println("Error: failed to sync with message = " + - * exc.getMessage()); } } - * - * - * /** The main method. + while (syncController.getState() == SynchronizerState.PERFORMING_SYNCHRONIZATION) { + Thread.sleep(1000); + } + + syncController.shutdown(); + + } catch (Exception exc) { + System.out.println("Error: failed to sync with message = " + exc.getMessage()); + } + } + + + /** + * The main method. * * @param args the arguments *//* - * public static void main(String[] args) { //boolean runSearchableEntitySync = false; //boolean - * runGeoEntitySync = true; - * - * //System.setProperty("AJSC_HOME", "e:\\dev"); // - * System.getProperties().setProperty("AJSC_HOME", // - * "c:\\rpo\\tier-support-ui\\target\\swm\\package\\nix\\" // + - * "dist_files\\opt\\app\\ajsc-tier-support-ui"); - * - * System.setProperty("CONFIG_HOME", "appconfig-local"); System.setProperty("AJSC_HOME", - * "x:\\1710_extensibility\\"); - * - * SyncControllerBuilder syncBuilder = new SyncControllerBuilder(); - * - * /* if (runSearchableEntitySync) syncBuilder.doSearchableEntitysync(); + public static void main(String[] args) { + //boolean runSearchableEntitySync = false; + //boolean runGeoEntitySync = true; + + //System.setProperty("AJSC_HOME", "e:\\dev"); + // System.getProperties().setProperty("AJSC_HOME", + // "c:\\rpo\\tier-support-ui\\target\\swm\\package\\nix\\" + // + "dist_files\\opt\\app\\ajsc-tier-support-ui"); + + System.setProperty("CONFIG_HOME", "appconfig-local"); + System.setProperty("AJSC_HOME", "x:\\1710_extensibility\\"); + + SyncControllerBuilder syncBuilder = new SyncControllerBuilder(); + + /* + * if (runSearchableEntitySync) syncBuilder.doSearchableEntitysync(); + */ +/* + syncBuilder.doSearchableEntitysync(); + // syncBuilder.doCrossEntityReferenceSync(); + // syncBuilder.doHistoricalEntitySync(); + // syncBuilder.doGeoEntitySync(); + //syncBuilder.doSuggestionEntitySync(); + //syncBuilder.doMasterEntitySync(); + + // syncBuilder.testElasticSearchUpdateAPI(); + + /* + * if (runGeoEntitySync) { syncBuilder.doGeoEntitySync(); } */ - /* - * syncBuilder.doSearchableEntitysync(); // syncBuilder.doCrossEntityReferenceSync(); // - * syncBuilder.doHistoricalEntitySync(); // syncBuilder.doGeoEntitySync(); - * //syncBuilder.doSuggestionEntitySync(); //syncBuilder.doMasterEntitySync(); - * - * // syncBuilder.testElasticSearchUpdateAPI(); - * - * /* if (runGeoEntitySync) { syncBuilder.doGeoEntitySync(); } - */ - // } + //} } diff --git a/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerServiceTest.java b/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerServiceTest.java index e491686..d4d62ba 100644 --- a/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerServiceTest.java +++ b/src/test/java/org/onap/aai/sparky/synchronizer/SyncControllerServiceTest.java @@ -10,25 +10,25 @@ public class SyncControllerServiceTest { private TestSyncController alpha; private SyncControllerService syncService; private SyncControllerRegistry syncControllerRegistry; - + @Before public void init() { alpha = new TestSyncController("alpha"); syncControllerRegistry = new SyncControllerRegistry(); - syncService = new SyncControllerService(syncControllerRegistry, 5, 5); + syncService = new SyncControllerService(syncControllerRegistry, 5,5); } @Test public void validateControllerRegistration() { - - syncControllerRegistry.registerSyncController(alpha); + + syncControllerRegistry.registerSyncController( alpha ); syncService.startSync(); - + syncService.shutdown(); } - - + + } diff --git a/src/test/java/org/onap/aai/sparky/synchronizer/TestSyncController.java b/src/test/java/org/onap/aai/sparky/synchronizer/TestSyncController.java index e8d3ec7..c61f78b 100644 --- a/src/test/java/org/onap/aai/sparky/synchronizer/TestSyncController.java +++ b/src/test/java/org/onap/aai/sparky/synchronizer/TestSyncController.java @@ -18,14 +18,14 @@ public class TestSyncController implements SyncController { private boolean periodic; private SynchronizerState internalState; private Semaphore gate; - + public TestSyncController(String name) { this.controllerName = name; this.internalState = SynchronizerState.IDLE; this.gate = new Semaphore(1); } - - + + @Override public String getControllerName() { return this.controllerName; @@ -33,12 +33,12 @@ public class TestSyncController implements SyncController { @Override public OperationState performAction(SyncActions requestedAction) { - + if (gate.tryAcquire()) { internalState = SynchronizerState.PERFORMING_SYNCHRONIZATION; - // System.out.println("performaAction = " + requestedAction); + // System.out.println("performaAction = " + requestedAction); System.out.println("Sync started with thread = " + Thread.currentThread().getName() + " at date = " + new Date(Calendar.getInstance().getTimeInMillis())); @@ -54,12 +54,12 @@ public class TestSyncController implements SyncController { + " at date = " + new Date(Calendar.getInstance().getTimeInMillis())); internalState = SynchronizerState.IDLE; - System.out.println("Next Sync at = " + Thread.currentThread().getName() + " at date = " - + new Date(Calendar.getInstance().getTimeInMillis() + 30000L)); - + System.out.println("Next Sync at = " + Thread.currentThread().getName() + + " at date = " + new Date(Calendar.getInstance().getTimeInMillis() + 30000L)); + gate.release(); - + return OperationState.OK; } else { return OperationState.IGNORED_SYNC_NOT_IDLE; @@ -69,30 +69,30 @@ public class TestSyncController implements SyncController { @Override public void registerEntitySynchronizer(IndexSynchronizer entitySynchronizer) { // TODO Auto-generated method stub - + } @Override public void registerIndexValidator(IndexValidator indexValidator) { // TODO Auto-generated method stub - + } @Override public void registerIndexCleaner(IndexCleaner indexCleaner) { // TODO Auto-generated method stub - + } @Override public void shutdown() { // TODO Auto-generated method stub - // System.out.println("shutdown"); + // System.out.println("shutdown"); } @Override public SynchronizerState getState() { - // System.out.println("getState()"); + // System.out.println("getState()"); return SynchronizerState.IDLE; } @@ -105,7 +105,7 @@ public class TestSyncController implements SyncController { @Override public void setDelayInMs(long delayInMs) { // TODO Auto-generated method stub - + } @Override @@ -117,12 +117,12 @@ public class TestSyncController implements SyncController { @Override public void setSyncFrequencyInMs(long syncFrequencyInMs) { // TODO Auto-generated method stub - + } @Override public Date getSyncStartTime() { - // System.out.println("getSyncStateTime()"); +// System.out.println("getSyncStateTime()"); // TODO Auto-generated method stub return null; } @@ -130,7 +130,7 @@ public class TestSyncController implements SyncController { @Override public void setSyncStartTime(Date syncStartTime) { // TODO Auto-generated method stub - + } @Override @@ -142,16 +142,16 @@ public class TestSyncController implements SyncController { @Override public void setLastExecutionDate(Date lastExecutionDate) { // TODO Auto-generated method stub - + } - + @Override public Calendar getCreationTime() { // TODO Auto-generated method stub return null; } - + @Override public String getNextSyncTime() { // TODO Auto-generated method stub @@ -171,7 +171,7 @@ public class TestSyncController implements SyncController { // TODO Auto-generated method stub return false; } - - + + } diff --git a/src/test/java/org/onap/aai/sparky/synchronizer/entity/AggregationSuggestionEntityTest.java b/src/test/java/org/onap/aai/sparky/synchronizer/entity/AggregationSuggestionEntityTest.java index 09a5299..ba3f38f 100644 --- a/src/test/java/org/onap/aai/sparky/synchronizer/entity/AggregationSuggestionEntityTest.java +++ b/src/test/java/org/onap/aai/sparky/synchronizer/entity/AggregationSuggestionEntityTest.java @@ -35,6 +35,7 @@ import java.util.List; import java.util.Scanner; import org.junit.Test; +import org.onap.aai.sparky.search.filters.config.FiltersConfig; import org.onap.aai.sparky.sync.entity.AggregationSuggestionEntity; public class AggregationSuggestionEntityTest { @@ -59,7 +60,8 @@ public class AggregationSuggestionEntityTest { @Test public void testGetIndexDocumentJson() { - AggregationSuggestionEntity aggregationSuggestionEntity = new AggregationSuggestionEntity(); + FiltersConfig filtersConfig = new FiltersConfig(); + AggregationSuggestionEntity aggregationSuggestionEntity = new AggregationSuggestionEntity(filtersConfig); List<String> filterIds = new ArrayList<>(Arrays.asList("1", "2", "7", "8")); aggregationSuggestionEntity.setFilterIds(filterIds); @@ -67,6 +69,7 @@ public class AggregationSuggestionEntityTest { String expectedFilterListPayload = getResourceFileContents( "filters/AggregationSuggestionEntity_getIndexDocumentJson_expected.json"); - assertTrue(aggregationSuggestionEntity.getAsJson().contains(expectedFilterListPayload.trim())); + assertTrue( + aggregationSuggestionEntity.getAsJson().contains(expectedFilterListPayload.trim())); } } diff --git a/src/test/java/org/onap/aai/sparky/synchronizer/entity/SuggestionSearchEntityTest.java b/src/test/java/org/onap/aai/sparky/synchronizer/entity/SuggestionSearchEntityTest.java index 8063e05..88f28b3 100644 --- a/src/test/java/org/onap/aai/sparky/synchronizer/entity/SuggestionSearchEntityTest.java +++ b/src/test/java/org/onap/aai/sparky/synchronizer/entity/SuggestionSearchEntityTest.java @@ -39,123 +39,149 @@ import com.fasterxml.jackson.databind.ObjectMapper; public class SuggestionSearchEntityTest { private SuggestionSearchEntity suggestionSearchEntity; ObjectMapper mapper = new ObjectMapper(); - private static FiltersConfig config = null; + private static FiltersConfig config = null; @BeforeClass public static void init() throws IOException { - config = FiltersConfig.getInstance(); + config = new FiltersConfig(); config.setFilterMappingsFileName("src/test/resources/filters/aaiui_views.json"); config.setFiltersFileName("src/test/resources/filters/aaiui_filters.json"); config.setViewsConfig(config.readUiViewsConfig()); config.setFiltersConfig(config.readUiFiltersConfig()); - + } - - public JsonNode getTestNodeForVnf_withProvAndOrchStatus() - throws JsonProcessingException, IOException { - String str = "{" + "\"vnf-id\": \"1\"," + "\"vnf-name\": \"2\"," + "\"vnf-type\": \"3\"," - + "\"orchestration-status\": \"o1\"," + "\"prov-status\": \"p1\"" + "}"; - + + public JsonNode getTestNodeForVnf_withProvAndOrchStatus() throws JsonProcessingException, IOException{ + String str = "{" + + "\"vnf-id\": \"1\"," + + "\"vnf-name\": \"2\"," + + "\"vnf-type\": \"3\"," + + "\"orchestration-status\": \"o1\"," + + "\"prov-status\": \"p1\"" + + "}"; + return mapper.readTree(str); } - - public JsonNode getTestNodeForVnf_withOrchStatus() throws JsonProcessingException, IOException { - String str = "{" + "\"vnf-id\": \"1\"," + "\"vnf-name\": \"2\"," + "\"vnf-type\": \"3\"," - + "\"orchestration-status\": \"o1\"" + "}"; - + + public JsonNode getTestNodeForVnf_withOrchStatus() throws JsonProcessingException, IOException{ + String str = "{" + + "\"vnf-id\": \"1\"," + + "\"vnf-name\": \"2\"," + + "\"vnf-type\": \"3\"," + + "\"orchestration-status\": \"o1\"" + + "}"; + return mapper.readTree(str); } - - public JsonNode getFilterListForOrchestrationStatusOnly(String orcStat) - throws JsonProcessingException, IOException { + + public JsonNode getFilterListForOrchestrationStatusOnly(String orcStat) throws JsonProcessingException, IOException{ String str = "{\"filterList\":[{\"filterId\":\"2\"},{\"filterId\":\"1\",\"filterValue\":" + orcStat + "}]}"; return mapper.readTree(str); } - - public String getStrFilterListForOrchestrationStatusOnly(String orcStat) - throws JsonProcessingException, IOException { + + public String getStrFilterListForOrchestrationStatusOnly(String orcStat) + throws JsonProcessingException, IOException{ String str = "{\"filterList\":[{\"filterId\":\"2\"},{\"filterId\":\"1\",\"filterValue\":" - + orcStat + "}," + "{\"filterId\":\"7\"}," + "{\"filterId\":\"8\"}" + "]}"; + + orcStat + "}," + + "{\"filterId\":\"7\"}," + + "{\"filterId\":\"8\"}" + + "]}"; return str; } - - public String getStrFilterListForOrcStatAndProvStat(String orcStat, String provStat) - throws JsonProcessingException, IOException { - String str = "{\"filterList\"" + ":[{\"filterId\":\"2\"," + "\"filterValue\":" + provStat - + "},{\"filterId\":\"1\",\"filterValue\":" + orcStat + "}," + "{\"filterId\":\"7\"}," - + "{\"filterId\":\"8\"}" + "]}"; + + public String getStrFilterListForOrcStatAndProvStat(String orcStat, String provStat) + throws JsonProcessingException, IOException{ + String str = "{\"filterList\"" + + ":[{\"filterId\":\"2\"," + + "\"filterValue\":" + provStat + + "},{\"filterId\":\"1\",\"filterValue\":" + + orcStat + "}," + + "{\"filterId\":\"7\"}," + + "{\"filterId\":\"8\"}" + + "]}"; return str; } - - public ArrayList<String> getSingleElementOrcStatUniqueList() { + + public ArrayList<String> getSingleElementOrcStatUniqueList(){ ArrayList<String> list = new ArrayList<String>(); list.add("orchestration-status"); - return list; + return list; } - - public ArrayList<String> getTwoElementUniqueList() { + + public ArrayList<String> getTwoElementUniqueList(){ ArrayList<String> list = new ArrayList<String>(); list.add("prov-status"); list.add("orchestration-status"); - return list; + return list; } - + // Testing the filters payload (for ES) when only one suggestible attribute is present // Use case: testing a single-element set from the power set of all attributes - /* - * @Test public void test_params_for_suggestions_with_orcStat_o1(){ suggestionSearchEntity = new - * SuggestionSearchEntity(SuggestionEntityLookup.getInstance(), config); - * suggestionSearchEntity.setEntityType("generic-vnf"); JsonNode node = null; try{ node = - * getTestNodeForVnf_withOrchStatus(); - * suggestionSearchEntity.setFilterBasedPayloadFromResponse(node, - * suggestionSearchEntity.getEntityType(), this.getSingleElementOrcStatUniqueList()); JSONObject - * json = suggestionSearchEntity.getPayload(); JSONObject exectedFilterPayload = new JSONObject( - * this.getStrFilterListForOrchestrationStatusOnly("o1")); - * - * final JsonNode tree1 = mapper.readTree(json.toString()); final JsonNode tree2 = - * mapper.readTree(exectedFilterPayload.toString()); - * - * assertTrue("Filter list not equal. Found: " + json + ". Expected: " + exectedFilterPayload, - * tree1.equals(tree2)); - * - * Map<String, String> inputOutput = suggestionSearchEntity.getInputOutputData(); Map<String, - * String> expectedInputOutput = new HashMap<String, String>(); - * expectedInputOutput.put("orchestration-status", "o1"); final JsonNode tree3 = - * mapper.readTree(mapper.writeValueAsString(inputOutput)); final JsonNode tree4 = - * mapper.readTree(mapper.writeValueAsString(expectedInputOutput)); - * - * assertTrue("inputs for suggestions are not equal", tree3.equals(tree4)); - * - * } catch (Exception e){ fail("Failed to get test node."); } } - */ - - // Testing the filters payload (for ES) when multiple suggestible attributes are present + /*@Test + public void test_params_for_suggestions_with_orcStat_o1(){ + suggestionSearchEntity = new SuggestionSearchEntity(SuggestionEntityLookup.getInstance(), config); + suggestionSearchEntity.setEntityType("generic-vnf"); + JsonNode node = null; + try{ + node = getTestNodeForVnf_withOrchStatus(); + suggestionSearchEntity.setFilterBasedPayloadFromResponse(node, + suggestionSearchEntity.getEntityType(), this.getSingleElementOrcStatUniqueList()); + JSONObject json = suggestionSearchEntity.getPayload(); + JSONObject exectedFilterPayload = new JSONObject( + this.getStrFilterListForOrchestrationStatusOnly("o1")); + + final JsonNode tree1 = mapper.readTree(json.toString()); + final JsonNode tree2 = mapper.readTree(exectedFilterPayload.toString()); + + assertTrue("Filter list not equal. Found: " + json + ". Expected: " + exectedFilterPayload, + tree1.equals(tree2)); + + Map<String, String> inputOutput = suggestionSearchEntity.getInputOutputData(); + Map<String, String> expectedInputOutput = new HashMap<String, String>(); + expectedInputOutput.put("orchestration-status", "o1"); + final JsonNode tree3 = mapper.readTree(mapper.writeValueAsString(inputOutput)); + final JsonNode tree4 = mapper.readTree(mapper.writeValueAsString(expectedInputOutput)); + + assertTrue("inputs for suggestions are not equal", tree3.equals(tree4)); + + } catch (Exception e){ + fail("Failed to get test node."); + } + }*/ + + //Testing the filters payload (for ES) when multiple suggestible attributes are present // Use case: testing a 2-element set from the power set of all attributes - /* - * @Test public void test_params_for_suggestions_with_orcStat_o1_provStat_p1(){ - * suggestionSearchEntity = new SuggestionSearchEntity(); - * suggestionSearchEntity.setEntityType("generic-vnf"); JsonNode node = null; try{ node = - * getTestNodeForVnf_withProvAndOrchStatus(); - * suggestionSearchEntity.setFilterBasedPayloadFromResponse(node, - * suggestionSearchEntity.getEntityType(), this.getTwoElementUniqueList()); JSONObject json = - * suggestionSearchEntity.getPayload(); JSONObject exectedFilterPayload = new JSONObject( - * this.getStrFilterListForOrcStatAndProvStat("o1", "p1")); - * - * final JsonNode tree1 = mapper.readTree(json.toString()); final JsonNode tree2 = - * mapper.readTree(exectedFilterPayload.toString()); - * - * assertTrue("Filter list not equal. Found: " + json + ". Expected: " + exectedFilterPayload, - * tree1.equals(tree2)); - * - * Map<String, String> inputOutput = suggestionSearchEntity.getInputOutputData(); Map<String, - * String> expectedInputOutput = new HashMap<String, String>(); - * expectedInputOutput.put("orchestration-status", "o1"); expectedInputOutput.put("prov-status", - * "p1"); final JsonNode tree3 = mapper.readTree(mapper.writeValueAsString(inputOutput)); final - * JsonNode tree4 = mapper.readTree(mapper.writeValueAsString(expectedInputOutput)); - * - * assertTrue("inputs for suggestions are not equal", tree3.equals(tree4)); - * - * } catch (Exception e){ fail("Failed to get node."); } } - */ + /*@Test + public void test_params_for_suggestions_with_orcStat_o1_provStat_p1(){ + suggestionSearchEntity = new SuggestionSearchEntity(); + suggestionSearchEntity.setEntityType("generic-vnf"); + JsonNode node = null; + try{ + node = getTestNodeForVnf_withProvAndOrchStatus(); + suggestionSearchEntity.setFilterBasedPayloadFromResponse(node, + suggestionSearchEntity.getEntityType(), this.getTwoElementUniqueList()); + JSONObject json = suggestionSearchEntity.getPayload(); + JSONObject exectedFilterPayload = new JSONObject( + this.getStrFilterListForOrcStatAndProvStat("o1", "p1")); + + final JsonNode tree1 = mapper.readTree(json.toString()); + final JsonNode tree2 = mapper.readTree(exectedFilterPayload.toString()); + + assertTrue("Filter list not equal. Found: " + json + ". Expected: " + exectedFilterPayload, + tree1.equals(tree2)); + + Map<String, String> inputOutput = suggestionSearchEntity.getInputOutputData(); + Map<String, String> expectedInputOutput = new HashMap<String, String>(); + expectedInputOutput.put("orchestration-status", "o1"); + expectedInputOutput.put("prov-status", "p1"); + final JsonNode tree3 = mapper.readTree(mapper.writeValueAsString(inputOutput)); + final JsonNode tree4 = mapper.readTree(mapper.writeValueAsString(expectedInputOutput)); + + assertTrue("inputs for suggestions are not equal", tree3.equals(tree4)); + + } catch (Exception e){ + fail("Failed to get node."); + } + }*/ } diff --git a/src/test/java/org/onap/aai/sparky/synchronizer/task/PerformActiveInventoryRetrievalTest.java b/src/test/java/org/onap/aai/sparky/synchronizer/task/PerformActiveInventoryRetrievalTest.java index cf658ba..60586bd 100644 --- a/src/test/java/org/onap/aai/sparky/synchronizer/task/PerformActiveInventoryRetrievalTest.java +++ b/src/test/java/org/onap/aai/sparky/synchronizer/task/PerformActiveInventoryRetrievalTest.java @@ -1,87 +1,93 @@ package org.onap.aai.sparky.synchronizer.task; import org.junit.BeforeClass; -import org.onap.aai.sparky.dal.aai.config.ActiveInventoryConfig; -import org.onap.aai.sparky.dal.aai.config.ActiveInventoryRestConfig; -import org.onap.aai.sparky.dal.aai.enums.RestAuthenticationMode; import org.onap.aai.sparky.sync.task.PerformActiveInventoryRetrieval; - +/* + * + * TODO-> RestClientBuilder is no longer being use neither is RestAuthenticationMode class + * need to be rewritten to use ONAP RestAuthenticationMode + */ +/* public class PerformActiveInventoryRetrievalTest { private PerformActiveInventoryRetrieval sut; @BeforeClass public static void initBeforeClass() throws Exception { - /* - * Mock aai.properties values which are used by repairSelfLink(), which is used both to build - * this test's expected URI and also used by PerformActiveInventoryRetrieval.get() which is the - * method under test - */ + /* Mock aai.properties values which are used by repairSelfLink(), which is used both to build this + * test's expected URI and also used by PerformActiveInventoryRetrieval.get() which is the method under test + * ActiveInventoryRestConfig aaiRestConfig = new ActiveInventoryRestConfig(null); ActiveInventoryConfig.getConfig().setAaiRestConfig(aaiRestConfig); ActiveInventoryConfig.getConfig().getAaiRestConfig().setHost("localhost"); ActiveInventoryConfig.getConfig().getAaiRestConfig().setPort("8443"); - ActiveInventoryConfig.getConfig().getAaiRestConfig() - .setAuthenticationMode(RestAuthenticationMode.SSL_CERT); + ActiveInventoryConfig.getConfig().getAaiRestConfig().setAuthenticationMode(RestAuthenticationMode.SSL_CERT); + } + + +/* @Test + public void testGet_relativeURI() throws Exception { + String uriToProcess = "/my/relative/uri"; // URI to perform test with + + Use uriToProcess + repairSelfLink() method to build the URI that we expect to see: + "https://localhost:8443/my/relative/uri" + String expectedURI = ActiveInventoryConfig.getConfig().repairSelfLink(uriToProcess); + + // Set up PerformActiveInventoryRetrieval dependencies + ActiveInventoryDataProvider aaiProvider = new ActiveInventoryAdapter(new OxmModelLoader(), new RestClientBuilder()); + NetworkTransaction txn = new NetworkTransaction(); + txn.setLink(uriToProcess); + + sut = new PerformActiveInventoryRetrieval(txn, aaiProvider); + sut.setContextMap(new HashMap<>()); + + // Call method under test which should add the missing scheme/host/port to the relative path given in this test + sut.get(); + + assertEquals(expectedURI, txn.getOperationResult().getRequestLink()); + } + + @Test + public void testGet_relativeURIWithSchemaAndAuthority() throws Exception { + String uriToProcess = "https://localhost:8443/my/relative/uri"; // URI to perform test with + + Use uriToProcess + repairSelfLink() method to build the URI that we expect to see: + "https://localhost:8443/my/relative/uri" + String expectedURI = ActiveInventoryConfig.getConfig().repairSelfLink(uriToProcess); + + // Set up PerformActiveInventoryRetrieval dependencies + ActiveInventoryDataProvider aaiProvider = new ActiveInventoryAdapter(new OxmModelLoader(), new RestClientBuilder()); + NetworkTransaction txn = new NetworkTransaction(); + txn.setLink(uriToProcess); + + sut = new PerformActiveInventoryRetrieval(txn, aaiProvider); + sut.setContextMap(new HashMap<>()); + + // Call method under test which shouldn't change the absolute path given in this test + sut.get(); + + assertEquals(expectedURI, txn.getOperationResult().getRequestLink()); } + @Test + public void testGet_emptyURI() throws Exception { + String uriToProcess = ""; // URI to perform test with - /* - * @Test public void testGet_relativeURI() throws Exception { String uriToProcess = - * "/my/relative/uri"; // URI to perform test with - * - * Use uriToProcess + repairSelfLink() method to build the URI that we expect to see: - * "https://localhost:8443/my/relative/uri" String expectedURI = - * ActiveInventoryConfig.getConfig().repairSelfLink(uriToProcess); - * - * // Set up PerformActiveInventoryRetrieval dependencies ActiveInventoryDataProvider aaiProvider - * = new ActiveInventoryAdapter(new OxmModelLoader(), new RestClientBuilder()); NetworkTransaction - * txn = new NetworkTransaction(); txn.setLink(uriToProcess); - * - * sut = new PerformActiveInventoryRetrieval(txn, aaiProvider); sut.setContextMap(new - * HashMap<>()); - * - * // Call method under test which should add the missing scheme/host/port to the relative path - * given in this test sut.get(); - * - * assertEquals(expectedURI, txn.getOperationResult().getRequestLink()); } - * - * @Test public void testGet_relativeURIWithSchemaAndAuthority() throws Exception { String - * uriToProcess = "https://localhost:8443/my/relative/uri"; // URI to perform test with - * - * Use uriToProcess + repairSelfLink() method to build the URI that we expect to see: - * "https://localhost:8443/my/relative/uri" String expectedURI = - * ActiveInventoryConfig.getConfig().repairSelfLink(uriToProcess); - * - * // Set up PerformActiveInventoryRetrieval dependencies ActiveInventoryDataProvider aaiProvider - * = new ActiveInventoryAdapter(new OxmModelLoader(), new RestClientBuilder()); NetworkTransaction - * txn = new NetworkTransaction(); txn.setLink(uriToProcess); - * - * sut = new PerformActiveInventoryRetrieval(txn, aaiProvider); sut.setContextMap(new - * HashMap<>()); - * - * // Call method under test which shouldn't change the absolute path given in this test - * sut.get(); - * - * assertEquals(expectedURI, txn.getOperationResult().getRequestLink()); } - * - * @Test public void testGet_emptyURI() throws Exception { String uriToProcess = ""; // URI to - * perform test with - * - * Use uriToProcess + repairSelfLink() method to build the URI that we expect to see: - * "https://localhost:8443" String expectedURI = - * ActiveInventoryConfig.getConfig().repairSelfLink(uriToProcess); - * - * // Set up PerformActiveInventoryRetrieval dependencies ActiveInventoryDataProvider aaiProvider - * = new ActiveInventoryAdapter(new OxmModelLoader(), new RestClientBuilder()); NetworkTransaction - * txn = new NetworkTransaction(); txn.setLink(uriToProcess); - * - * sut = new PerformActiveInventoryRetrieval(txn, aaiProvider); sut.setContextMap(new - * HashMap<>()); - * - * // Call method under test which should add the missing scheme/host/port to the empty URI given - * in this test sut.get(); - * - * assertEquals(expectedURI, txn.getOperationResult().getRequestLink()); } - */ -} + Use uriToProcess + repairSelfLink() method to build the URI that we expect to see: + "https://localhost:8443" + String expectedURI = ActiveInventoryConfig.getConfig().repairSelfLink(uriToProcess); + + // Set up PerformActiveInventoryRetrieval dependencies + ActiveInventoryDataProvider aaiProvider = new ActiveInventoryAdapter(new OxmModelLoader(), new RestClientBuilder()); + NetworkTransaction txn = new NetworkTransaction(); + txn.setLink(uriToProcess); + + sut = new PerformActiveInventoryRetrieval(txn, aaiProvider); + sut.setContextMap(new HashMap<>()); + + // Call method under test which should add the missing scheme/host/port to the empty URI given in this test + sut.get(); + + assertEquals(expectedURI, txn.getOperationResult().getRequestLink()); + } +}*/ diff --git a/src/test/java/org/onap/aai/sparky/util/CaptureLoggerAppender.java b/src/test/java/org/onap/aai/sparky/util/CaptureLoggerAppender.java index 3b86ad5..443328e 100644 --- a/src/test/java/org/onap/aai/sparky/util/CaptureLoggerAppender.java +++ b/src/test/java/org/onap/aai/sparky/util/CaptureLoggerAppender.java @@ -90,17 +90,13 @@ public class CaptureLoggerAppender implements Appender { - /* - * (non-Javadoc) - * + /* (non-Javadoc) * @see ch.qos.logback.core.spi.LifeCycle#start() */ @Override public void start() {} - /* - * (non-Javadoc) - * + /* (non-Javadoc) * @see ch.qos.logback.core.spi.LifeCycle#stop() */ @Override @@ -127,9 +123,7 @@ public class CaptureLoggerAppender implements Appender { return null; } - /* - * (non-Javadoc) - * + /* (non-Javadoc) * @see ch.qos.logback.core.spi.ContextAware#addStatus(ch.qos.logback.core.status.Status) */ @Override @@ -138,9 +132,7 @@ public class CaptureLoggerAppender implements Appender { System.out.println("addStatus"); } - /* - * (non-Javadoc) - * + /* (non-Javadoc) * @see ch.qos.logback.core.spi.ContextAware#addInfo(java.lang.String) */ @Override @@ -149,9 +141,7 @@ public class CaptureLoggerAppender implements Appender { } - /* - * (non-Javadoc) - * + /* (non-Javadoc) * @see ch.qos.logback.core.spi.ContextAware#addInfo(java.lang.String, java.lang.Throwable) */ @Override @@ -160,9 +150,7 @@ public class CaptureLoggerAppender implements Appender { } - /* - * (non-Javadoc) - * + /* (non-Javadoc) * @see ch.qos.logback.core.spi.ContextAware#addWarn(java.lang.String) */ @Override @@ -171,9 +159,7 @@ public class CaptureLoggerAppender implements Appender { } - /* - * (non-Javadoc) - * + /* (non-Javadoc) * @see ch.qos.logback.core.spi.ContextAware#addWarn(java.lang.String, java.lang.Throwable) */ @Override @@ -182,9 +168,7 @@ public class CaptureLoggerAppender implements Appender { } - /* - * (non-Javadoc) - * + /* (non-Javadoc) * @see ch.qos.logback.core.spi.ContextAware#addError(java.lang.String) */ @Override @@ -193,9 +177,7 @@ public class CaptureLoggerAppender implements Appender { } - /* - * (non-Javadoc) - * + /* (non-Javadoc) * @see ch.qos.logback.core.spi.ContextAware#addError(java.lang.String, java.lang.Throwable) */ @Override @@ -204,9 +186,7 @@ public class CaptureLoggerAppender implements Appender { } - /* - * (non-Javadoc) - * + /* (non-Javadoc) * @see ch.qos.logback.core.spi.FilterAttachable#addFilter(ch.qos.logback.core.filter.Filter) */ @Override @@ -215,9 +195,7 @@ public class CaptureLoggerAppender implements Appender { } - /* - * (non-Javadoc) - * + /* (non-Javadoc) * @see ch.qos.logback.core.spi.FilterAttachable#clearAllFilters() */ @Override @@ -232,9 +210,7 @@ public class CaptureLoggerAppender implements Appender { return null; } - /* - * (non-Javadoc) - * + /* (non-Javadoc) * @see ch.qos.logback.core.spi.FilterAttachable#getFilterChainDecision(java.lang.Object) */ @Override @@ -250,9 +226,7 @@ public class CaptureLoggerAppender implements Appender { return "MOCK"; } - /* - * (non-Javadoc) - * + /* (non-Javadoc) * @see ch.qos.logback.core.Appender#doAppend(java.lang.Object) */ @Override diff --git a/src/test/java/org/onap/aai/sparky/util/ElasticEntitySummarizer.java b/src/test/java/org/onap/aai/sparky/util/ElasticEntitySummarizer.java deleted file mode 100644 index d09f5d0..0000000 --- a/src/test/java/org/onap/aai/sparky/util/ElasticEntitySummarizer.java +++ /dev/null @@ -1,167 +0,0 @@ -/** - * ============LICENSE_START=================================================== - * SPARKY (AAI UI service) - * ============================================================================ - * Copyright © 2017 AT&T Intellectual Property. - * Copyright © 2017 Amdocs - * All rights reserved. - * ============================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END===================================================== - * - * ECOMP and OpenECOMP are trademarks - * and service marks of AT&T Intellectual Property. - */ - -package org.onap.aai.sparky.util; - -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; -import java.util.Map; -import java.util.TreeMap; -import java.util.concurrent.atomic.AtomicInteger; - -import org.onap.aai.sparky.dal.elasticsearch.config.ElasticSearchConfig; -import org.onap.aai.sparky.dal.exception.ElasticSearchOperationException; -import org.onap.aai.sparky.dal.rest.RestDataProvider; - -/** - * The Class ElasticEntitySummarizer. - */ -public class ElasticEntitySummarizer { - - private RestDataProvider syncAdapter; - private ElasticSearchConfig elasticConfig; - private Map<String, AtomicInteger> entityCounters; - - /** - * Instantiates a new elastic entity summarizer. - * - * @param loader the loader - * @throws Exception the exception - */ - public ElasticEntitySummarizer() throws Exception { - - - elasticConfig = new ElasticSearchConfig(); - - elasticConfig.setIndexName("entitysearchindex-localhost"); - elasticConfig.setIpAddress("127.0.0.1"); - elasticConfig.setHttpPort("9200"); - elasticConfig.setType("default"); - - // syncAdapter = new SyncAdapter(new RestClientBuilder(), elasticConfig, loader); - - entityCounters = new HashMap<String, AtomicInteger>(); - - } - - /** - * Peg counter. - * - * @param entityName the entity name - */ - private synchronized void pegCounter(String entityName) { - - if (entityName == null || entityName.length() == 0) { - return; - } - - AtomicInteger counter = entityCounters.get(entityName); - - if (counter == null) { - counter = new AtomicInteger(0); - entityCounters.put(entityName, counter); - } - - counter.incrementAndGet(); - - } - - - /** - * Enumerate entities. - */ - public void enumerateEntities() { - - try { - - Map<String, String> preSyncObjectIdsAndTypes = new HashMap<String, String>(); - - /* - * Map<String, String> preSyncObjectIdsAndTypes = - * syncAdapter.retrieveAllDocumentIdentifiers(elasticConfig.getIndexName(), - * elasticConfig.getType(), 5, 5000); - */ - - if (preSyncObjectIdsAndTypes != null) { - - Collection<String> entityTypes = preSyncObjectIdsAndTypes.values(); - for (String t : entityTypes) { - pegCounter(t); - } - } - - TreeMap<String, AtomicInteger> elasticEntitySortedTreeMap = - new TreeMap<String, AtomicInteger>(new Comparator<String>() { - - @Override - public int compare(String o1, String o2) { - return o1.toLowerCase().compareTo(o2.toLowerCase()); - } - }); - - elasticEntitySortedTreeMap.putAll(entityCounters); - - int totalEntities = 0; - - System.out.println("\n"); - - for (String counterEntityKey : elasticEntitySortedTreeMap.keySet()) { - - AtomicInteger counter = elasticEntitySortedTreeMap.get(counterEntityKey); - totalEntities += counter.get(); - System.out.println(String.format("%-30s %-12d", counterEntityKey, counter.get())); - } - - System.out.println(String.format("\n%-30s %-12d", "Total", totalEntities)); - - } catch (Exception exc) { - System.out.println("An error occurred while attempting to collect pre-sync elastic" - + " search document ids with an error cause = " + exc.getLocalizedMessage()); - } - - - } - - - /** - * The main method. - * - * @param args the arguments - * @throws ElasticSearchOperationException the elastic search operation exception - */ - public static void main(String[] args) throws ElasticSearchOperationException { - - - // ElasticEntitySummarizer summarizer = new ElasticEntitySummarizer(); - // summarizer.enumerateEntities(); - - - - } - - - -} diff --git a/src/test/java/org/onap/aai/sparky/util/ExceptionHelper.java b/src/test/java/org/onap/aai/sparky/util/ExceptionHelper.java index e3008ef..f05aed8 100644 --- a/src/test/java/org/onap/aai/sparky/util/ExceptionHelper.java +++ b/src/test/java/org/onap/aai/sparky/util/ExceptionHelper.java @@ -29,7 +29,7 @@ package org.onap.aai.sparky.util; * The Class ExceptionHelper. */ public class ExceptionHelper { - + /** * Extract stack trace elements. * diff --git a/src/test/java/org/onap/aai/sparky/util/HttpServletHelper.java b/src/test/java/org/onap/aai/sparky/util/HttpServletHelper.java index e026530..132f330 100644 --- a/src/test/java/org/onap/aai/sparky/util/HttpServletHelper.java +++ b/src/test/java/org/onap/aai/sparky/util/HttpServletHelper.java @@ -64,8 +64,8 @@ public class HttpServletHelper { try { Mockito.when(request.getContentType()).thenReturn(mimeType); - - + + final ByteArrayInputStream bais = new ByteArrayInputStream(payloadContent.getBytes(StandardCharsets.UTF_8)); @@ -94,9 +94,8 @@ public class HttpServletHelper { }; Mockito.when(request.getInputStream()).thenReturn(servletInputStream); - Mockito.when(request.getReader()) - .thenReturn(new BufferedReader(new StringReader(payloadContent))); - + Mockito.when(request.getReader()).thenReturn(new BufferedReader(new StringReader(payloadContent))); + } catch (IOException ioe) { fail(ExceptionHelper.extractStackTraceElements(5, ioe)); } @@ -151,12 +150,11 @@ public class HttpServletHelper { for (String key : paramNameValueMap.keySet()) { Mockito.when(req.getParameter(key)).thenReturn(paramNameValueMap.get(key)); } - + } } - - public static void assignRequestHeader(HttpServletRequest req, String headerName, - String headerValue) { + + public static void assignRequestHeader(HttpServletRequest req, String headerName, String headerValue) { Mockito.when(req.getHeader(headerName)).thenReturn(headerValue); } diff --git a/src/test/java/org/onap/aai/sparky/util/SuggestionsPermutationTest.java b/src/test/java/org/onap/aai/sparky/util/SuggestionsPermutationTest.java index 6de5f69..6aa23b7 100644 --- a/src/test/java/org/onap/aai/sparky/util/SuggestionsPermutationTest.java +++ b/src/test/java/org/onap/aai/sparky/util/SuggestionsPermutationTest.java @@ -42,144 +42,73 @@ public class SuggestionsPermutationTest { inputList.add("str1"); inputList.add("str2"); inputList.add("str3"); - + List<List<String>> expectedListOfLists = new ArrayList<List<String>>(); - expectedListOfLists.add((new ArrayList<String>() { - { - add("str1"); - } - })); - expectedListOfLists.add((new ArrayList<String>() { - { - add("str2"); - } - })); - expectedListOfLists.add((new ArrayList<String>() { - { - add("str3"); - } - })); - expectedListOfLists.add((new ArrayList<String>() { - { - add("str1"); - add("str2"); - } - })); - expectedListOfLists.add((new ArrayList<String>() { - { - add("str1"); - add("str3"); - } - })); - expectedListOfLists.add((new ArrayList<String>() { - { - add("str2"); - add("str3"); - } - })); - expectedListOfLists.add((new ArrayList<String>() { - { - add("str1"); - add("str2"); - add("str3"); - } - })); - + expectedListOfLists.add((new ArrayList<String>(){{add("str1");}})); + expectedListOfLists.add((new ArrayList<String>(){{add("str2");}})); + expectedListOfLists.add((new ArrayList<String>(){{add("str3");}})); + expectedListOfLists.add((new ArrayList<String>(){{add("str1");add("str2");}})); + expectedListOfLists.add((new ArrayList<String>(){{add("str1");add("str3");}})); + expectedListOfLists.add((new ArrayList<String>(){{add("str2");add("str3");}})); + expectedListOfLists.add((new ArrayList<String>(){{add("str1");add("str2");add("str3");}})); + int expectedCount = expectedListOfLists.size(); int actualCount = 0; - ArrayList<ArrayList<String>> actualListOfLists = - SuggestionsPermutation.getNonEmptyUniqueLists(inputList); - - for (List<String> list : expectedListOfLists) { - for (ArrayList<String> actualList : actualListOfLists) { - if (new HashSet(list).equals(new HashSet(actualList))) { + ArrayList<ArrayList<String>> actualListOfLists = SuggestionsPermutation.getNonEmptyUniqueLists(inputList); + + for (List<String> list: expectedListOfLists){ + for (ArrayList<String> actualList: actualListOfLists) { + if (new HashSet(list).equals (new HashSet(actualList)) ){ actualCount++; } } } - - assertTrue("Missing entries in the unique list of lists for input: " + inputList.toString() - + ". Found: " + actualListOfLists.toString() + " expected: " - + expectedListOfLists.toString(), actualCount == expectedCount); + + assertTrue("Missing entries in the unique list of lists for input: " + inputList.toString() + + ". Found: "+ actualListOfLists.toString() + + " expected: " + expectedListOfLists.toString(), actualCount == expectedCount); } - + @Test public void testGetListPermutations() { List<String> inputList = new ArrayList<String>(); inputList.add("str1"); inputList.add("str2"); inputList.add("str3"); - + List<List<String>> expectedPermutations = new ArrayList<List<String>>(); - expectedPermutations.add((new ArrayList<String>() { - { - add("str1"); - add("str2"); - add("str3"); - } - })); - expectedPermutations.add((new ArrayList<String>() { - { - add("str2"); - add("str1"); - add("str3"); - } - })); - expectedPermutations.add((new ArrayList<String>() { - { - add("str2"); - add("str3"); - add("str1"); - } - })); - expectedPermutations.add((new ArrayList<String>() { - { - add("str1"); - add("str3"); - add("str2"); - } - })); - expectedPermutations.add((new ArrayList<String>() { - { - add("str3"); - add("str1"); - add("str2"); - } - })); - expectedPermutations.add((new ArrayList<String>() { - { - add("str3"); - add("str2"); - add("str1"); - } - })); - + expectedPermutations.add((new ArrayList<String>(){{add("str1");add("str2");add("str3");}})); + expectedPermutations.add((new ArrayList<String>(){{add("str2");add("str1");add("str3");}})); + expectedPermutations.add((new ArrayList<String>(){{add("str2");add("str3");add("str1");}})); + expectedPermutations.add((new ArrayList<String>(){{add("str1");add("str3");add("str2");}})); + expectedPermutations.add((new ArrayList<String>(){{add("str3");add("str1");add("str2");}})); + expectedPermutations.add((new ArrayList<String>(){{add("str3");add("str2");add("str1");}})); + int expectedCount = expectedPermutations.size(); int actualCount = 0; List<List<String>> actualPermutations = SuggestionsPermutation.getListPermutations(inputList); - - for (List<String> list : expectedPermutations) { - for (List<String> actualList : actualPermutations) { - if (list.toString().equals(actualList.toString())) { + + for (List<String> list: expectedPermutations){ + for (List<String> actualList: actualPermutations) { + if (list.toString().equals(actualList.toString()) ){ actualCount++; } } } - - assertTrue( - "Missing entries in the permutation of list: " + inputList.toString() + ". Found: " - + actualPermutations.toString() + " expected: " + expectedPermutations.toString(), - actualCount == expectedCount); + + assertTrue("Missing entries in the permutation of list: " + + inputList.toString() + ". Found: "+ actualPermutations.toString() + + " expected: " + expectedPermutations.toString(), actualCount == expectedCount); } @Test public void isValidSuggestionInputPermutation_verbose_successPath() { - + List<String> x = new ArrayList<>(Arrays.asList("A", "B", "C", "D")); ArrayList<ArrayList<String>> uniqueLists = SuggestionsPermutation.getNonEmptyUniqueLists(x); - - assertTrue(uniqueLists.get(0).toString().equals("[A, B, C, D]")); + + assertTrue(uniqueLists.get(0).toString().equals("[A, B, C, D]")); assertTrue(uniqueLists.get(1).toString().equals("[B, C, D]")); assertTrue(uniqueLists.get(2).toString().equals("[A, C, D]")); assertTrue(uniqueLists.get(3).toString().equals("[C, D]")); @@ -195,7 +124,7 @@ public class SuggestionsPermutationTest { assertTrue(uniqueLists.get(13).toString().equals("[B]")); assertTrue(uniqueLists.get(14).toString().equals("[A]")); assertTrue(uniqueLists.size() == 15); - + } - + } diff --git a/src/test/java/org/onap/aai/sparky/util/TreeWalkerTest.java b/src/test/java/org/onap/aai/sparky/util/TreeWalkerTest.java index ba1435f..f6947cf 100644 --- a/src/test/java/org/onap/aai/sparky/util/TreeWalkerTest.java +++ b/src/test/java/org/onap/aai/sparky/util/TreeWalkerTest.java @@ -55,7 +55,8 @@ public class TreeWalkerTest { * @throws Exception the exception */ @Before - public void init() throws Exception {} + public void init() throws Exception { + } /** * Validate json node conversion null input. @@ -181,7 +182,8 @@ public class TreeWalkerTest { public void validateWalkTreeOneParentNodeWithObjectArray() { try { - String jsonStr = "{\"Employee\":[{\"id\":\"101\",\"name\":\"Pushkar\",\"salary\":\"5000\"}," + String jsonStr = + "{\"Employee\":[{\"id\":\"101\",\"name\":\"Pushkar\",\"salary\":\"5000\"}," + "{\"id\":\"102\",\"name\":\"Rahul\",\"salary\":\"4000\"}," + "{\"id\":\"103\",\"name\":\"tanveer\",\"salary\":\"56678\"}]}"; TreeWalker walker = new TreeWalker(); @@ -226,68 +228,68 @@ public class TreeWalkerTest { try { String jsonStr = "{ \"generalNodeClass\": { \"class\": \"aai-entity-node general-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }, {" - + " \"type\": \"circle\", \"class\": \"inner\", " - + " \"svgAttributes\": { \"r\": \"10\" " - + "} }, { \"type\": \"text\", " - + "\"class\": \"id-type-label\", \"displayKey\": \"itemType\", " - + " \"shapeAttributes\": { \"offset\": { " - + " \"x\": \"0\", \"y\": \"30\" } " - + " } }, { \"type\": \"text\", " - + " \"class\": \"id-value-label\", \"displayKey\":" - + " \"itemNameValue\", \"shapeAttributes\": { " - + " \"offset\": { \"x\": \"0\", " - + " \"y\": \"40\" } } } ] " - + " }, \"searchedNodeClass\": { \"class\": \"aai-entity-node search-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": { " - + " \"r\": \"20\" } }, { " - + " \"type\": \"circle\", \"class\": \"inner\", " - + " \"svgAttributes\": { \"r\": \"10\" }" - + " }, { \"type\": \"text\", " - + "\"class\": \"id-type-label\", \"displayKey\": \"itemType\", " - + " \"shapeAttributes\": { \"offset\": { " - + " \"x\": \"0\", \"y\": \"30\" }" - + " } }, { \"type\": \"text\", " - + " \"class\": \"id-value-label\", " - + "\"displayKey\": \"itemNameValue\", \"shapeAttributes\": {" - + " \"offset\": { \"x\": \"0\"," - + " \"y\": \"40\" } }" - + " } ] }, \"selectedSearchedNodeClass\": { " - + "\"class\": \"aai-entity-node selected-search-node\", \"visualElements\": [" - + " { \"type\": \"circle\", " - + "\"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }, {" - + " \"type\": \"circle\", \"class\": \"inner\"," - + " \"svgAttributes\": { \"r\": \"10\" " - + " } }, { \"type\": \"text\", " - + " \"class\": \"id-type-label\", \"displayKey\": \"itemType\"," - + " \"shapeAttributes\": { \"offset\": {" - + " \"x\": \"0\", \"y\": \"30\"" - + " } } }, { " - + " \"type\": \"text\", \"class\": \"id-value-label\", " - + " \"displayKey\": \"itemNameValue\", \"shapeAttributes\": {" - + " \"offset\": { \"x\": \"0\", " - + " \"y\": \"40\" } } } ]" - + " }, \"selectedNodeClass\": { \"class\":" - + " \"aai-entity-node selected-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }, {" - + " \"type\": \"circle\", \"class\": \"inner\"," - + " \"svgAttributes\": { \"r\": \"10\" " - + " } }, { \"type\": \"text\", " - + " \"class\": \"id-type-label\", \"displayKey\": \"itemType\"," - + " \"shapeAttributes\": { \"offset\": " - + "{ " - + " \"x\": \"0\", \"y\": \"30\" } " - + " } }, { \"type\": \"text\"," - + " \"class\": \"id-value-label\", \"displayKey\":" - + " \"itemNameValue\", \"shapeAttributes\": { " - + "\"offset\": { \"x\": \"0\", " - + "\"y\": \"40\" } } } ] }}"; + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }, {" + + " \"type\": \"circle\", \"class\": \"inner\", " + + " \"svgAttributes\": { \"r\": \"10\" " + + "} }, { \"type\": \"text\", " + + "\"class\": \"id-type-label\", \"displayKey\": \"itemType\", " + + " \"shapeAttributes\": { \"offset\": { " + + " \"x\": \"0\", \"y\": \"30\" } " + + " } }, { \"type\": \"text\", " + + " \"class\": \"id-value-label\", \"displayKey\":" + + " \"itemNameValue\", \"shapeAttributes\": { " + + " \"offset\": { \"x\": \"0\", " + + " \"y\": \"40\" } } } ] " + + " }, \"searchedNodeClass\": { \"class\": \"aai-entity-node search-node\"," + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": { " + + " \"r\": \"20\" } }, { " + + " \"type\": \"circle\", \"class\": \"inner\", " + + " \"svgAttributes\": { \"r\": \"10\" }" + + " }, { \"type\": \"text\", " + + "\"class\": \"id-type-label\", \"displayKey\": \"itemType\", " + + " \"shapeAttributes\": { \"offset\": { " + + " \"x\": \"0\", \"y\": \"30\" }" + + " } }, { \"type\": \"text\", " + + " \"class\": \"id-value-label\", " + + "\"displayKey\": \"itemNameValue\", \"shapeAttributes\": {" + + " \"offset\": { \"x\": \"0\"," + + " \"y\": \"40\" } }" + + " } ] }, \"selectedSearchedNodeClass\": { " + + "\"class\": \"aai-entity-node selected-search-node\", \"visualElements\": [" + + " { \"type\": \"circle\", " + + "\"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }, {" + + " \"type\": \"circle\", \"class\": \"inner\"," + + " \"svgAttributes\": { \"r\": \"10\" " + + " } }, { \"type\": \"text\", " + + " \"class\": \"id-type-label\", \"displayKey\": \"itemType\"," + + " \"shapeAttributes\": { \"offset\": {" + + " \"x\": \"0\", \"y\": \"30\"" + + " } } }, { " + + " \"type\": \"text\", \"class\": \"id-value-label\", " + + " \"displayKey\": \"itemNameValue\", \"shapeAttributes\": {" + + " \"offset\": { \"x\": \"0\", " + + " \"y\": \"40\" } } } ]" + + " }, \"selectedNodeClass\": { \"class\":" + + " \"aai-entity-node selected-node\"," + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }, {" + + " \"type\": \"circle\", \"class\": \"inner\"," + + " \"svgAttributes\": { \"r\": \"10\" " + + " } }, { \"type\": \"text\", " + + " \"class\": \"id-type-label\", \"displayKey\": \"itemType\"," + + " \"shapeAttributes\": { \"offset\": " + + "{ " + + " \"x\": \"0\", \"y\": \"30\" } " + + " } }, { \"type\": \"text\"," + + " \"class\": \"id-value-label\", \"displayKey\":" + + " \"itemNameValue\", \"shapeAttributes\": { " + + "\"offset\": { \"x\": \"0\", " + + "\"y\": \"40\" } } } ] }}"; TreeWalker walker = new TreeWalker(); List<String> paths = new ArrayList<String>(); walker.walkTree(paths, walker.convertJsonToNode(jsonStr)); @@ -396,143 +398,143 @@ public class TreeWalkerTest { try { String n1Str = "{ \"generalNodeClass\": { \"class\": \"aai-entity-node general-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }, {" - + " \"type\": \"circle\", \"class\": \"inner\"," - + " \"svgAttributes\": { \"r\": \"10\"" - + " } }, { \"type\": \"text\"," - + " \"class\": \"id-type-label\", \"displayKey\":" - + " \"itemType\", \"shapeAttributes\": { \"offset\":" - + " { \"x\": \"0\", \"y\": \"30\"" - + " } } }, {" - + " \"type\": \"text\", \"class\": \"id-value-label\"," - + " \"displayKey\": \"itemNameValue\"," - + " \"shapeAttributes\": { \"offset\":" - + " { \"x\": \"0\", \"y\": \"40\"" - + " } } } ] }," - + " \"searchedNodeClass\": { \"class\": \"aai-entity-node search-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }, {" - + " \"type\": \"circle\", \"class\": \"inner\"," - + " \"svgAttributes\": { \"r\": \"10\"" - + " } }, { \"type\": \"text\"," - + " \"class\": \"id-type-label\", \"displayKey\":" - + " \"itemType\", \"shapeAttributes\": { \"offset\": {" - + " \"x\": \"0\", \"y\": \"30\"" - + " } } }, {" - + " \"type\": \"text\", \"class\": \"id-value-label\"," - + " \"displayKey\": \"itemNameValue\"," - + " \"shapeAttributes\": { \"offset\": {" - + " \"x\": \"0\", \"y\": \"40\"" - + " } } } ] }," - + " \"selectedSearchedNodeClass\": { \"class\":" - + " \"aai-entity-node selected-search-node\", \"visualElements\": [" - + " { \"type\": \"circle\", \"class\":" - + " \"outer\", \"svgAttributes\": { \"r\": \"20\"" - + " } }, { \"type\": \"circle\"," - + " \"class\": \"inner\", \"svgAttributes\": {" - + " \"r\": \"10\" } }, {" - + " \"type\": \"text\", \"class\": \"id-type-label\"," - + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" - + " \"offset\": { \"x\": \"0\"," - + " \"y\": \"30\" } }" - + " }, { \"type\": \"text\"," - + " \"class\": \"id-value-label\"," - + " \"displayKey\": \"itemNameValue\"," - + " \"shapeAttributes\": { \"offset\": {" - + " \"x\": \"0\", \"y\": \"40\"" - + " } } } ] }," - + " \"selectedNodeClass\": { \"class\": \"aai-entity-node selected-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }, {" - + " \"type\": \"circle\", \"class\": \"inner\"," - + " \"svgAttributes\": { \"r\": \"10\"" - + " } }, { \"type\": \"text\"," - + " \"class\": \"id-type-label\", \"displayKey\":" - + " \"itemType\", \"shapeAttributes\": {" - + " \"offset\": { \"x\": \"0\"," - + " \"y\": \"30\" }" - + " } }, { \"type\": \"text\"," - + " \"class\": \"id-value-label\", \"displayKey\":" - + " \"itemNameValue\", \"shapeAttributes\": {" - + " \"offset\": { \"x\": \"0\"," - + " \"y\": \"40\" } }" - + " } ] }}"; + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }, {" + + " \"type\": \"circle\", \"class\": \"inner\"," + + " \"svgAttributes\": { \"r\": \"10\"" + + " } }, { \"type\": \"text\"," + + " \"class\": \"id-type-label\", \"displayKey\":" + + " \"itemType\", \"shapeAttributes\": { \"offset\":" + + " { \"x\": \"0\", \"y\": \"30\"" + + " } } }, {" + + " \"type\": \"text\", \"class\": \"id-value-label\"," + + " \"displayKey\": \"itemNameValue\"," + + " \"shapeAttributes\": { \"offset\":" + + " { \"x\": \"0\", \"y\": \"40\"" + + " } } } ] }," + + " \"searchedNodeClass\": { \"class\": \"aai-entity-node search-node\"," + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }, {" + + " \"type\": \"circle\", \"class\": \"inner\"," + + " \"svgAttributes\": { \"r\": \"10\"" + + " } }, { \"type\": \"text\"," + + " \"class\": \"id-type-label\", \"displayKey\":" + + " \"itemType\", \"shapeAttributes\": { \"offset\": {" + + " \"x\": \"0\", \"y\": \"30\"" + + " } } }, {" + + " \"type\": \"text\", \"class\": \"id-value-label\"," + + " \"displayKey\": \"itemNameValue\"," + + " \"shapeAttributes\": { \"offset\": {" + + " \"x\": \"0\", \"y\": \"40\"" + + " } } } ] }," + + " \"selectedSearchedNodeClass\": { \"class\":" + + " \"aai-entity-node selected-search-node\", \"visualElements\": [" + + " { \"type\": \"circle\", \"class\":" + + " \"outer\", \"svgAttributes\": { \"r\": \"20\"" + + " } }, { \"type\": \"circle\"," + + " \"class\": \"inner\", \"svgAttributes\": {" + + " \"r\": \"10\" } }, {" + + " \"type\": \"text\", \"class\": \"id-type-label\"," + + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" + + " \"offset\": { \"x\": \"0\"," + + " \"y\": \"30\" } }" + + " }, { \"type\": \"text\"," + + " \"class\": \"id-value-label\"," + + " \"displayKey\": \"itemNameValue\"," + + " \"shapeAttributes\": { \"offset\": {" + + " \"x\": \"0\", \"y\": \"40\"" + + " } } } ] }," + + " \"selectedNodeClass\": { \"class\": \"aai-entity-node selected-node\"," + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }, {" + + " \"type\": \"circle\", \"class\": \"inner\"," + + " \"svgAttributes\": { \"r\": \"10\"" + + " } }, { \"type\": \"text\"," + + " \"class\": \"id-type-label\", \"displayKey\":" + + " \"itemType\", \"shapeAttributes\": {" + + " \"offset\": { \"x\": \"0\"," + + " \"y\": \"30\" }" + + " } }, { \"type\": \"text\"," + + " \"class\": \"id-value-label\", \"displayKey\":" + + " \"itemNameValue\", \"shapeAttributes\": {" + + " \"offset\": { \"x\": \"0\"," + + " \"y\": \"40\" } }" + + " } ] }}"; String n2Str = "{ \"searchedNodeClass\": { \"class\": \"aai-entity-node search-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }," - + " { \"type\": \"circle\"," - + " \"class\": \"inner\", \"svgAttributes\": {" - + " \"r\": \"10\" } }, {" - + " \"type\": \"text\", \"class\": \"id-type-label\"," - + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" - + " \"offset\": { \"y\": \"30\"," - + " \"x\": \"0\" } }" - + " }, { \"type\": \"text\"," - + " \"class\": \"id-value-label\"," - + " \"displayKey\": \"itemNameValue\"," - + " \"shapeAttributes\": { \"offset\": {" - + " \"y\": \"40\", \"x\": \"0\"" - + " } } } ] }," - + " \"selectedSearchedNodeClass\": { \"class\":" - + " \"aai-entity-node selected-search-node\", \"visualElements\": [" - + " { \"type\": \"circle\", \"class\":" - + " \"outer\", \"svgAttributes\": { \"r\": \"20\"" - + " } }, { \"type\": \"circle\"," - + " \"class\": \"inner\", \"svgAttributes\": {" - + " \"r\": \"10\" } }, {" - + " \"type\": \"text\", \"class\": \"id-type-label\"," - + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" - + " \"offset\": { \"y\": \"30\"," - + " \"x\": \"0\" } }" - + " }, { \"type\": \"text\"," - + " \"class\": \"id-value-label\"," - + " \"displayKey\": \"itemNameValue\"," - + " \"shapeAttributes\": { \"offset\": {" - + " \"y\": \"40\", \"x\": \"0\"" - + " } } } ] }," - + " \"selectedNodeClass\": { \"class\": \"aai-entity-node selected-node\"," - + " \"visualElements\": [ { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }, {" - + " \"type\": \"circle\", \"class\": \"inner\"," - + " \"svgAttributes\": { \"r\": \"10\"" - + " } }, { \"type\": \"text\"," - + " \"class\": \"id-type-label\"," - + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" - + " \"offset\": { \"y\": \"30\"," - + " \"x\": \"0\" } }" - + " }, { \"type\": \"text\"," - + " \"class\": \"id-value-label\"," - + " \"displayKey\": \"itemNameValue\"," - + " \"shapeAttributes\": { \"offset\": {" - + " \"y\": \"40\", \"x\": \"0\"" - + " } } } ] }," - + " \"generalNodeClass\": { \"class\":" - + " \"aai-entity-node general-node\", \"visualElements\": [" - + " { \"type\": \"circle\"," - + " \"class\": \"outer\", \"svgAttributes\": {" - + " \"r\": \"20\" } }," - + " { \"type\": \"circle\"," - + " \"class\": \"inner\", \"svgAttributes\": {" - + " \"r\": \"10\" } }," - + " { \"type\": \"text\"," - + " \"class\": \"id-type-label\", \"displayKey\":" - + " \"itemType\", \"shapeAttributes\": {" - + " \"offset\": { \"y\": \"30\"," - + " \"x\": \"0\" }" - + " } }, {" - + " \"type\": \"text\"," - + " \"class\": \"id-value-label\", \"displayKey\":" - + " \"itemNameValue\", \"shapeAttributes\": {" - + " \"offset\": { \"y\": \"40\"," - + " \"x\": \"0\" }" - + " } } ] }}"; + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }," + + " { \"type\": \"circle\"," + + " \"class\": \"inner\", \"svgAttributes\": {" + + " \"r\": \"10\" } }, {" + + " \"type\": \"text\", \"class\": \"id-type-label\"," + + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" + + " \"offset\": { \"y\": \"30\"," + + " \"x\": \"0\" } }" + + " }, { \"type\": \"text\"," + + " \"class\": \"id-value-label\"," + + " \"displayKey\": \"itemNameValue\"," + + " \"shapeAttributes\": { \"offset\": {" + + " \"y\": \"40\", \"x\": \"0\"" + + " } } } ] }," + + " \"selectedSearchedNodeClass\": { \"class\":" + + " \"aai-entity-node selected-search-node\", \"visualElements\": [" + + " { \"type\": \"circle\", \"class\":" + + " \"outer\", \"svgAttributes\": { \"r\": \"20\"" + + " } }, { \"type\": \"circle\"," + + " \"class\": \"inner\", \"svgAttributes\": {" + + " \"r\": \"10\" } }, {" + + " \"type\": \"text\", \"class\": \"id-type-label\"," + + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" + + " \"offset\": { \"y\": \"30\"," + + " \"x\": \"0\" } }" + + " }, { \"type\": \"text\"," + + " \"class\": \"id-value-label\"," + + " \"displayKey\": \"itemNameValue\"," + + " \"shapeAttributes\": { \"offset\": {" + + " \"y\": \"40\", \"x\": \"0\"" + + " } } } ] }," + + " \"selectedNodeClass\": { \"class\": \"aai-entity-node selected-node\"," + + " \"visualElements\": [ { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }, {" + + " \"type\": \"circle\", \"class\": \"inner\"," + + " \"svgAttributes\": { \"r\": \"10\"" + + " } }, { \"type\": \"text\"," + + " \"class\": \"id-type-label\"," + + " \"displayKey\": \"itemType\", \"shapeAttributes\": {" + + " \"offset\": { \"y\": \"30\"," + + " \"x\": \"0\" } }" + + " }, { \"type\": \"text\"," + + " \"class\": \"id-value-label\"," + + " \"displayKey\": \"itemNameValue\"," + + " \"shapeAttributes\": { \"offset\": {" + + " \"y\": \"40\", \"x\": \"0\"" + + " } } } ] }," + + " \"generalNodeClass\": { \"class\":" + + " \"aai-entity-node general-node\", \"visualElements\": [" + + " { \"type\": \"circle\"," + + " \"class\": \"outer\", \"svgAttributes\": {" + + " \"r\": \"20\" } }," + + " { \"type\": \"circle\"," + + " \"class\": \"inner\", \"svgAttributes\": {" + + " \"r\": \"10\" } }," + + " { \"type\": \"text\"," + + " \"class\": \"id-type-label\", \"displayKey\":" + + " \"itemType\", \"shapeAttributes\": {" + + " \"offset\": { \"y\": \"30\"," + + " \"x\": \"0\" }" + + " } }, {" + + " \"type\": \"text\"," + + " \"class\": \"id-value-label\", \"displayKey\":" + + " \"itemNameValue\", \"shapeAttributes\": {" + + " \"offset\": { \"y\": \"40\"," + + " \"x\": \"0\" }" + + " } } ] }}"; TreeWalker walker = new TreeWalker(); List<String> n1Paths = new ArrayList<String>(); diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchAdapterTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchAdapterTest.java index 4d46945..5ddf07e 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchAdapterTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchAdapterTest.java @@ -24,7 +24,7 @@ */ package org.onap.aai.sparky.viewandinspect; - +/* import static org.mockito.Matchers.anyObject; import static org.mockito.Matchers.anyString; import static org.mockito.Matchers.same; @@ -42,7 +42,9 @@ import com.sun.jersey.api.client.WebResource.Builder; /** * The Class SearchAdapterTest. - */ + * + * + *TODO -> rewrite the test as it no longer uses RestClientBuilder public class SearchAdapterTest { private RestClientBuilder clientBuilderMock; @@ -51,19 +53,19 @@ public class SearchAdapterTest { private WebResource mockWebResource; private Builder mockBuilder; - + /** * Inits the. * * @throws Exception the exception - */ + * @Before public void init() throws Exception { /* * common collaborator mocking setup - */ + * clientBuilderMock = mock(RestClientBuilder.class); mockClient = mock(Client.class); @@ -82,4 +84,4 @@ public class SearchAdapterTest { doReturn(mockClientResponse).when(mockBuilder).delete(same(ClientResponse.class)); } -} +}*/
\ No newline at end of file diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchResponseTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchResponseTest.java index 5081fa1..7975c13 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchResponseTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchResponseTest.java @@ -57,19 +57,19 @@ public class SearchResponseTest { SearchResponse response = new SearchResponse(); - // response.setNumReturned(1); + //response.setNumReturned(1); response.setProcessingTimeInMs(512); - // response.setTotalFound(50); + //response.setTotalFound(50); List<EntityEntry> entities = new ArrayList<EntityEntry>(); - // response.setEntities(entities); + //response.setEntities(entities); EntityEntry e1 = new EntityEntry(); e1.setEntityPrimaryKeyValue("e1"); e1.setEntityType("e1"); e1.setSearchTags("e1"); - // response.addEntityEntry(e1); + //response.addEntityEntry(e1); EntityEntry e2 = new EntityEntry(); @@ -77,15 +77,15 @@ public class SearchResponseTest { e2.setEntityType("e2"); e2.setSearchTags("e2"); - // response.addEntityEntry(e2); + //response.addEntityEntry(e2); - // assertEquals(1, response.getNumReturned()); - // assertEquals(512, response.getProcessingTimeInMs()); - // assertEquals(50, response.getTotalFound()); + //assertEquals(1, response.getNumReturned()); + //assertEquals(512, response.getProcessingTimeInMs()); + //assertEquals(50, response.getTotalFound()); - // List<EntityEntry> responseEntities = response.getEntities(); + //List<EntityEntry> responseEntities = response.getEntities(); - // assertEquals(2, responseEntities.size()); + //assertEquals(2, responseEntities.size()); } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchServletTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchServletTest.java index f99088d..69c408c 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchServletTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchServletTest.java @@ -1,858 +1,992 @@ /** - * ============LICENSE_START=================================================== SPARKY (AAI UI - * service) ============================================================================ Copyright © - * 2017 AT&T Intellectual Property. Copyright © 2017 Amdocs All rights reserved. - * ============================================================================ Licensed under the - * Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with - * the License. You may obtain a copy of the License at + * ============LICENSE_START=================================================== + * SPARKY (AAI UI service) + * ============================================================================ + * Copyright © 2017 AT&T Intellectual Property. + * Copyright © 2017 Amdocs + * All rights reserved. + * ============================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at * - * http://www.apache.org/licenses/LICENSE-2.0 + * http://www.apache.org/licenses/LICENSE-2.0 * - * Unless required by applicable law or agreed to in writing, software distributed under the License - * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express - * or implied. See the License for the specific language governing permissions and limitations under - * the License. ============LICENSE_END===================================================== + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END===================================================== * - * ECOMP and OpenECOMP are trademarks and service marks of AT&T Intellectual Property. + * ECOMP and OpenECOMP are trademarks + * and service marks of AT&T Intellectual Property. */ package org.onap.aai.sparky.viewandinspect; /* - * import org.openecomp.sparky.config.oxm.OxmEntityDescriptor; import - * org.openecomp.sparky.config.oxm.OxmModelLoader; import - * org.openecomp.sparky.dal.elasticsearch.SearchAdapter; import - * org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestDocumentEntity; import - * org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestDocumentEntityFields; import - * org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestElasticHitEntity; import - * org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestElasticHitsEntity; import - * org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestElasticSearchResponse; import - * org.openecomp.sparky.dal.elasticsearch.entity.BucketEntity; import - * org.openecomp.sparky.dal.elasticsearch.entity.ElasticHitsEntity; import - * org.openecomp.sparky.dal.elasticsearch.entity.ElasticSearchAggegrationResponse; import - * org.openecomp.sparky.dal.elasticsearch.entity.ElasticSearchAggregation; import - * org.openecomp.sparky.dal.elasticsearch.entity.ElasticSearchCountResponse; import - * org.openecomp.sparky.dal.elasticsearch.entity.PayloadEntity; import - * org.openecomp.sparky.dal.rest.OperationResult; import - * org.openecomp.sparky.dal.sas.config.SearchServiceConfig; import - * org.openecomp.sparky.dal.sas.entity.EntityCountResponse; import - * org.openecomp.sparky.dal.sas.entity.GroupByAggregationResponseEntity; import - * org.openecomp.sparky.dal.sas.entity.SearchAbstractionEntityBuilder; import - * org.openecomp.sparky.search.VnfSearchService; import - * org.openecomp.sparky.search.config.SuggestionConfig; import - * org.openecomp.sparky.search.filters.FilteredSearchHelper; import - * org.openecomp.sparky.search.filters.entity.UiFilterEntity; import - * org.openecomp.sparky.search.filters.entity.UiFilterValueEntity; import - * org.openecomp.sparky.search.filters.entity.UiFiltersEntity; import - * org.openecomp.sparky.suggestivesearch.SuggestionEntity; import - * org.openecomp.sparky.util.ExceptionHelper; import org.openecomp.sparky.util.HttpServletHelper; - * import org.openecomp.sparky.util.NodeUtils; import - * org.openecomp.sparky.viewandinspect.entity.QuerySearchEntity; import - * org.openecomp.sparky.viewandinspect.entity.SearchResponse; import org.slf4j.MDC; - * - * import org.onap.aai.cl.mdc.MdcContext; import com.fasterxml.jackson.core.JsonProcessingException; - * import com.fasterxml.jackson.databind.ObjectMapper; import - * com.fasterxml.jackson.databind.SerializationFeature; import - * com.fasterxml.jackson.databind.node.ObjectNode; import com.google.common.net.MediaType; - * - * - * /** The Class SearchServletTest. - */ +import org.openecomp.sparky.config.oxm.OxmEntityDescriptor; +import org.openecomp.sparky.config.oxm.OxmModelLoader; +import org.openecomp.sparky.dal.elasticsearch.SearchAdapter; +import org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestDocumentEntity; +import org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestDocumentEntityFields; +import org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestElasticHitEntity; +import org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestElasticHitsEntity; +import org.openecomp.sparky.dal.elasticsearch.entity.AutoSuggestElasticSearchResponse; +import org.openecomp.sparky.dal.elasticsearch.entity.BucketEntity; +import org.openecomp.sparky.dal.elasticsearch.entity.ElasticHitsEntity; +import org.openecomp.sparky.dal.elasticsearch.entity.ElasticSearchAggegrationResponse; +import org.openecomp.sparky.dal.elasticsearch.entity.ElasticSearchAggregation; +import org.openecomp.sparky.dal.elasticsearch.entity.ElasticSearchCountResponse; +import org.openecomp.sparky.dal.elasticsearch.entity.PayloadEntity; +import org.openecomp.sparky.dal.rest.OperationResult; +import org.openecomp.sparky.dal.sas.config.SearchServiceConfig; +import org.openecomp.sparky.dal.sas.entity.EntityCountResponse; +import org.openecomp.sparky.dal.sas.entity.GroupByAggregationResponseEntity; +import org.openecomp.sparky.dal.sas.entity.SearchAbstractionEntityBuilder; +import org.openecomp.sparky.search.VnfSearchService; +import org.openecomp.sparky.search.config.SuggestionConfig; +import org.openecomp.sparky.search.filters.FilteredSearchHelper; +import org.openecomp.sparky.search.filters.entity.UiFilterEntity; +import org.openecomp.sparky.search.filters.entity.UiFilterValueEntity; +import org.openecomp.sparky.search.filters.entity.UiFiltersEntity; +import org.openecomp.sparky.suggestivesearch.SuggestionEntity; +import org.openecomp.sparky.util.ExceptionHelper; +import org.openecomp.sparky.util.HttpServletHelper; +import org.openecomp.sparky.util.NodeUtils; +import org.openecomp.sparky.viewandinspect.entity.QuerySearchEntity; +import org.openecomp.sparky.viewandinspect.entity.SearchResponse; +import org.slf4j.MDC; -/* - * public class SearchServletTest { - * - * private static final String VNF_ROUTE = "vnf"; private static final String VIEW_INSPECT_ROUTE = - * "viewInspect"; - * - * private HttpServletRequest commonRequest = null; private HttpServletResponse commonResponse = - * null; private PrintWriter printWriter = null; private StringWriter responseStringWriter = null; - * private SearchServiceWrapper searchWrapper = null; private SearchAdapter searchAdapter = null; - * private VnfSearchService vnfSearchService = null; private ObjectMapper mapper = null; private - * SecureRandom rand = null; private OxmModelLoader loader; private Map<String, OxmEntityDescriptor> - * descriptors = null; private SuggestionConfig suggestionConfig = null; private SearchServiceConfig - * esConfig = null; - * - * @BeforeClass public static void initBeforeClass() throws IOException { if (null == - * System.getProperty("CONFIG_HOME")) { /* Set "CONFIG_HOME" environment variable so path of filter - * & view schema files are correct when they're loaded during SearchServiceWrapper instantiation - */ -/* - * String configHomePath = (new File(".").getCanonicalPath() + "/appconfig-local").replace('\\', - * '/'); System.setProperty("CONFIG_HOME", configHomePath); } } - * - * /** Inits the. - * - * @throws Exception the exception - */ -/* - * @Before public void init() throws Exception { commonRequest = - * HttpServletHelper.getMockHttpServletRequest(); responseStringWriter = new StringWriter(); - * printWriter = new PrintWriter(responseStringWriter); commonResponse = - * HttpServletHelper.getMockHttpServletResponse(printWriter); mapper = new ObjectMapper(); - * - * // permit serialization of objects with no members - * mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); - * - * rand = new SecureRandom(); - * - * loader = Mockito.mock(OxmModelLoader.class); descriptors = new HashMap<String, - * OxmEntityDescriptor>(); - * - * esConfig = new SearchServiceConfig(); suggestionConfig = SuggestionConfig.getConfig(); - * - * // Use SearchServiceWrapper and VnfSearchService for suggestionConfig Map<String, String> svcs = - * new HashMap<String, String>(); svcs.put("autosuggestIndexname", "SearchServiceWrapper"); - * svcs.put("indexName", "VnfSearchService"); suggestionConfig.setSearchIndexToSearchService(svcs); - * - * esConfig.setIndexName("esi-localhost"); esConfig.setType("default"); - * - * searchAdapter = Mockito.mock(SearchAdapter.class); vnfSearchService = - * Mockito.mock(VnfSearchService.class); - * - * initializeEntityDescriptors(); - * - * searchWrapper = new SearchServiceWrapper(); searchWrapper.setSasConfig(esConfig); - * searchWrapper.setSearch(searchAdapter); searchWrapper.setVnfSearch(vnfSearchService); - * searchWrapper.setSuggestionConfig(suggestionConfig); searchWrapper.setOxmModelLoader(loader); } - * - * @Test public void validateAccessors() { assertNotNull("Vnf Search Service should not be null", - * searchWrapper.getVnfSearch()); } - * - * @Test public void validateInitializer() { - * - * try { assertNotNull("Oxm Model loader should not be null", searchWrapper.getOxmModelLoader()); - * assertNotNull("SearchAbstractionConfig should not be null", searchWrapper.getSasConfig()); - * assertNotNull("SearchAdapter should not be null", searchWrapper.getSearch()); assertNotNull( - * "Suggestion Config should not be null", searchWrapper.getSuggestionConfig()); assertNotNull( - * "VnfSearchService should not be null", searchWrapper.getVnfSearch()); - * - * searchWrapper.setOxmModelLoader(null); searchWrapper.setSasConfig(null); - * searchWrapper.setSearch(null); searchWrapper.setSuggestionConfig(null); - * searchWrapper.setVnfSearch(null); - * - * assertNull("Oxm Model loader should be null", searchWrapper.getOxmModelLoader()); assertNull( - * "SearchAbstractionConfig should be null", searchWrapper.getSasConfig()); assertNull( - * "SearchAdapter should be null", searchWrapper.getSearch()); assertNull( - * "Suggestion Config should be null", searchWrapper.getSuggestionConfig()); assertNull( - * "VnfSearchService should be null", searchWrapper.getVnfSearch()); - * - * } catch (Exception exc) { fail("Servlet Initialization Failed with error = " + exc.getMessage()); - * } - * - * } - * - * /** Test doGet() and doPost() for a non-existent end-point. A test objective would be to either - * return a 404 Not Found. - */ -/* - * @Test public void validateMdcContextLoggingVariablesWhenExplicitlySet() { - * - * final String transactionId = "1234"; final String serviceName = "AAI-UI"; final String - * partnerName = "SparkyApp"; - * - * HttpServletHelper.assignRequestHeader(commonRequest, "X-TransactionId", transactionId); - * HttpServletHelper.assignRequestHeader(commonRequest, "X-FromAppId", partnerName); - * - * HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/"); - * - * try { - * - * /* Testing the doGet() operation will hit the doPost() operation in the servlet as well - */ +import org.onap.aai.cl.mdc.MdcContext; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; +import com.fasterxml.jackson.databind.node.ObjectNode; +import com.google.common.net.MediaType; -/* - * OperationResult result = doEvaluationTestMDC(true, commonRequest, commonResponse); - * - * assertEquals(transactionId,MDC.get(MdcContext.MDC_REQUEST_ID)); - * assertEquals(serviceName,MDC.get(MdcContext.MDC_SERVICE_NAME)); - * assertEquals(partnerName,MDC.get(MdcContext.MDC_PARTNER_NAME)); - * - * } catch (Exception exc) { exc.printStackTrace(); fail("Unexpected exception = " + - * exc.getLocalizedMessage()); } - * - * } - * - * /** Test doGet() and doPost() for a non-existent end-point. A test objective would be to either - * return a 404 Not Found. - */ -/* - * @Test public void validateMdcContextLoggingVariablesWhenNotExplicitlySet() { - * - * /*final String transactionId = "1234"; final String serviceName = "AAI-UI"; final String - * partnerName = "SparkyApp"; - * - * HttpServletHelper.assignRequestHeader(commonRequest, "X-TransactionId", transactionId); - * HttpServletHelper.assignRequestHeader(commonRequest, "X-FromAppId", serviceName); - */ -/* - * HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/"); - * - * try { - * - * /* Testing the doGet() operation will hit the doPost() operation in the servlet as well +/** + * The Class SearchServletTest. */ -/* - * OperationResult result = doEvaluationTestMDC(true, commonRequest, commonResponse); - * - * assertNotNull(MDC.get(MdcContext.MDC_REQUEST_ID)); - * assertNotNull(MDC.get(MdcContext.MDC_SERVICE_NAME)); - * assertNotNull(MDC.get(MdcContext.MDC_PARTNER_NAME)); - * - * } catch (Exception exc) { exc.printStackTrace(); fail("Unexpected exception = " + - * exc.getLocalizedMessage()); } - * - * } - * - * - * - * /** Test doGet() and doPost() for a non-existent end-point. - */ -/* - * @Test public void validateViewAndInspectSearchError_invalidRequestUri() { - * - * HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/"); - * - * try { - * - * /* Testing the doGet() operation will hit the doPost() operation in the servlet as well - */ -/* - * OperationResult result = doEvaluation(true, commonRequest, commonResponse); assertEquals(404, - * result.getResultCode()); assertTrue(result.getResult().contains("Ignored request-uri")); - * - * } catch (Exception exc) { exc.printStackTrace(); fail("Unexpected exception = " + - * exc.getLocalizedMessage()); } - * - * } - * - * /** Test doGet() and doPost() for Unified Query Search success path - */ -/* - * @Test public void validateQuerySearch_successPath() { - * - * try { - * - * QuerySearchEntity searchEntity = new QuerySearchEntity(); searchEntity.setMaxResults("10"); - * searchEntity.setQueryStr("the quick brown fox"); - * - * HttpServletHelper.assignRequestUri(commonRequest, "search/querysearch"); - * HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), - * NodeUtils.convertObjectToJson(searchEntity, false)); - * - * - * // set search-abstraction-response that we expect to get back from real system, but stubbed - * through a mock // to fulfill collaborator behavior - * - * OperationResult mockedEntitySearchResponse = new OperationResult(); - * mockedEntitySearchResponse.setResultCode(200); - * mockedEntitySearchResponse.setResult(NodeUtils.convertObjectToJson( - * SearchAbstractionEntityBuilder.getSuccessfulEntitySearchResponse(), false)); - * - * // TODO: make parameters expect certain values to lock in invocation attempt against a specific - * input sequence Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString())) - * .thenReturn(mockedEntitySearchResponse); - * - * List<SuggestionEntity> autoSuggestions = new ArrayList<SuggestionEntity>(); - * - * autoSuggestions.add(new SuggestionEntity("1234", "vnf", "VNFs", null)); autoSuggestions.add(new - * SuggestionEntity("1111", "vnf", "Created VNFs", null)); autoSuggestions.add(new - * SuggestionEntity("1122", "vnf", "ACTIVE VNFs", null)); autoSuggestions.add(new - * SuggestionEntity("2233", "vnf", "ACTIVE and Error VNFs", null)); autoSuggestions.add(new - * SuggestionEntity("3344", "vnf", "ACTIVE and NOT ORCHESTRATED VNFs", null)); - * autoSuggestions.add(new SuggestionEntity("4455", "vnf", "ACTIVE and Running VNFs", null)); - * autoSuggestions.add(new SuggestionEntity("5566", "vnf", "Activated VNFs", null)); - * autoSuggestions.add(new SuggestionEntity("6677", "vnf", "CAPPED VNFs", null)); - * autoSuggestions.add(new SuggestionEntity("7788", "vnf", "CAPPED and Created VNFs", null)); - * - * Mockito.when(vnfSearchService.getSuggestionsResults(Mockito.anyObject(), Mockito.anyInt())) - * .thenReturn(autoSuggestions); - * - * /* Testing the doGet() operation will hit the doPost() operation in the servlet as well - */ -/* - * OperationResult result = doEvaluation(true, commonRequest, commonResponse); - * - * - * assertEquals(200, result.getResultCode()); - * - * SearchResponse searchResponse = mapper.readValue(result.getResult(), SearchResponse.class); - * - * assertEquals(10, searchResponse.getTotalFound()); - * - * int numVnf = 0; int numViewInspect = 0; - * - * for ( SuggestionEntity suggestion : searchResponse.getSuggestions()) { - * - * if ( VNF_ROUTE.equals(suggestion.getRoute())) { numVnf++; } else if ( - * VIEW_INSPECT_ROUTE.equals(suggestion.getRoute())) { numViewInspect++; } } - * - * assertEquals(5, numVnf); assertEquals(5, numViewInspect); - * - * //assertTrue(result.getResult().contains("Ignored request-uri")); - * - * } catch (Exception exc) { fail("Unexpected exception = " + exc.getLocalizedMessage()); } - * - * } - * - * /** Test doGet() and doPost() for Unified Query Search success path - */ -/* - * @Test - * - * @Ignore public void validateSummaryByEntityTypeCount_successPath() { - * - * try { - * - * HttpServletHelper.assignRequestUri(commonRequest, "search/summarybyentitytype/count"); - * - * Map<String,String> payloadFields = new HashMap<String,String>(); payloadFields.put("hashId", - * "662d1b57c31df70d7ef57ec53c0ace81578ec77b6bc5de055a57c7547ec122dd"); payloadFields.put("groupby", - * "orchestration-status"); - * - * HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), - * NodeUtils.convertObjectToJson(payloadFields, false)); - * - * /* In this test we don't want to mock the vnf search service, only it's collaborator interactions - * with a REST endpoint. - */ -/* - * vnfSearchService = new VnfSearchService(); vnfSearchService.setSearch(searchAdapter); - * searchWrapper.setVnfSearch(vnfSearchService); - * - * /* The first network response to mock is the one to elastic search to get the suggestion entity - * by hash id - * - * http://localhost:9200/entityautosuggestindex-localhost/_search - * {"query":{"term":{"_id":"2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"}}} - */ -/* - * AutoSuggestElasticSearchResponse elasticResponse = new AutoSuggestElasticSearchResponse(); - * - * elasticResponse.setTook(1); - * - * elasticResponse.setTimedOut(false); elasticResponse.addShard("total", "5"); - * elasticResponse.addShard("successful", "5"); elasticResponse.addShard("failed", "0"); - * - * AutoSuggestElasticHitEntity elasticHit = new AutoSuggestElasticHitEntity(); - * elasticHit.setIndex("entityautosuggestindex-localhost"); elasticHit.setType("default"); - * elasticHit.setId("2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"); - * elasticHit.setScore("1"); - * - * AutoSuggestDocumentEntityFields suggestDocFields = new AutoSuggestDocumentEntityFields(); - * suggestDocFields.addInput("VNFs"); suggestDocFields.addInput("generic-vnfs"); - * suggestDocFields.setOutput("VNFs"); suggestDocFields.setPayload(new PayloadEntity()); - * suggestDocFields.setWeight(100); - * - * AutoSuggestDocumentEntity autoSuggestDoc = new AutoSuggestDocumentEntity(); - * autoSuggestDoc.setFields(suggestDocFields); - * - * elasticHit.setSource(autoSuggestDoc); - * - * AutoSuggestElasticHitsEntity hits = new AutoSuggestElasticHitsEntity(); hits.addHit(elasticHit); - * - * elasticResponse.setHits(hits); - * - * - * OperationResult mockedSearchResponse = new OperationResult(); - * mockedSearchResponse.setResultCode(200); - * - * mockedSearchResponse.setResult(NodeUtils.convertObjectToJson(elasticResponse, false)); - * - * - * /* The second response is the count API dip to elastic search - */ -/* - * ElasticSearchCountResponse countResponse = new ElasticSearchCountResponse(); - * countResponse.setCount(3170); countResponse.addShard("total", "5"); - * countResponse.addShard("successful", "5"); countResponse.addShard("failed", "0"); - * - * OperationResult searchResponseForCount = new OperationResult(); - * searchResponseForCount.setResultCode(200); - * - * searchResponseForCount.setResult(NodeUtils.convertObjectToJson(countResponse, false)); - * - * // TODO: make parameters expect certain values to lock in invocation attempt against a specific - * input sequence Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString())) - * .thenReturn(mockedSearchResponse).thenReturn(searchResponseForCount); - * - * - * /* Testing the doGet() operation will hit the doPost() operation in the servlet as well - */ -/* - * OperationResult result = doEvaluation(true, commonRequest, commonResponse); - * - * - * assertEquals(200, result.getResultCode()); - * - * // //{"shards":{"total":"5","failed":"0","successful":"5"},"count":3170} - * - * EntityCountResponse entityCountResponse = mapper.readValue(result.getResult(), - * EntityCountResponse.class); - * - * assertEquals(3170, entityCountResponse.getCount()); - * - * } catch (Exception exc) { fail("Unexpected exception = " + exc.getLocalizedMessage()); } - * - * } - * - * - * /** Test doGet() and doPost() for Unified Query Search success path - */ -/* - * @Test - * - * @Ignore public void validateSummaryByEntityType_successPath() { - * - * try { - * - * HttpServletHelper.assignRequestUri(commonRequest, "search/summarybyentitytype"); - * - * Map<String,String> payloadFields = new HashMap<String,String>(); payloadFields.put("hashId", - * "662d1b57c31df70d7ef57ec53c0ace81578ec77b6bc5de055a57c7547ec122dd"); payloadFields.put("groupby", - * "orchestration-status"); - * - * HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), - * NodeUtils.convertObjectToJson(payloadFields, false)); - * - * /* In this test we don't want to mock the vnf search service, only it's collaborator interactions - * with a REST endpoint. - */ -/* - * vnfSearchService = new VnfSearchService(); vnfSearchService.setSearch(searchAdapter); - * searchWrapper.setVnfSearch(vnfSearchService); - * - * /* The first network response to mock is the one to elastic search to get the suggestion entity - * by hash id - * - * http://localhost:9200/entityautosuggestindex-localhost/_search - * {"query":{"term":{"_id":"2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"}}} - */ +/*public class SearchServletTest { + private static final String VNF_ROUTE = "vnf"; + private static final String VIEW_INSPECT_ROUTE = "viewInspect"; + + private HttpServletRequest commonRequest = null; + private HttpServletResponse commonResponse = null; + private PrintWriter printWriter = null; + private StringWriter responseStringWriter = null; + private SearchServiceWrapper searchWrapper = null; + private SearchAdapter searchAdapter = null; + private VnfSearchService vnfSearchService = null; + private ObjectMapper mapper = null; + private SecureRandom rand = null; + private OxmModelLoader loader; + private Map<String, OxmEntityDescriptor> descriptors = null; + private SuggestionConfig suggestionConfig = null; + private SearchServiceConfig esConfig = null; + + @BeforeClass + public static void initBeforeClass() throws IOException { + if (null == System.getProperty("CONFIG_HOME")) { + /* Set "CONFIG_HOME" environment variable so path of filter & view schema files are correct when + they're loaded during SearchServiceWrapper instantiation */ +/* String configHomePath = (new File(".").getCanonicalPath() + "/appconfig-local").replace('\\', '/'); + System.setProperty("CONFIG_HOME", configHomePath); + } + } + + /** + * Inits the. + * + * @throws Exception the exception + */ +/* @Before + public void init() throws Exception { + commonRequest = HttpServletHelper.getMockHttpServletRequest(); + responseStringWriter = new StringWriter(); + printWriter = new PrintWriter(responseStringWriter); + commonResponse = HttpServletHelper.getMockHttpServletResponse(printWriter); + mapper = new ObjectMapper(); + + // permit serialization of objects with no members + mapper.configure(SerializationFeature.FAIL_ON_EMPTY_BEANS, false); + + rand = new SecureRandom(); + + loader = Mockito.mock(OxmModelLoader.class); + descriptors = new HashMap<String, OxmEntityDescriptor>(); + + esConfig = new SearchServiceConfig(); + suggestionConfig = SuggestionConfig.getConfig(); + + // Use SearchServiceWrapper and VnfSearchService for suggestionConfig + Map<String, String> svcs = new HashMap<String, String>(); + svcs.put("autosuggestIndexname", "SearchServiceWrapper"); + svcs.put("indexName", "VnfSearchService"); + suggestionConfig.setSearchIndexToSearchService(svcs); + + esConfig.setIndexName("esi-localhost"); + esConfig.setType("default"); + + searchAdapter = Mockito.mock(SearchAdapter.class); + vnfSearchService = Mockito.mock(VnfSearchService.class); + + initializeEntityDescriptors(); + + searchWrapper = new SearchServiceWrapper(); + searchWrapper.setSasConfig(esConfig); + searchWrapper.setSearch(searchAdapter); + searchWrapper.setVnfSearch(vnfSearchService); + searchWrapper.setSuggestionConfig(suggestionConfig); + searchWrapper.setOxmModelLoader(loader); + } + + @Test + public void validateAccessors() { + assertNotNull("Vnf Search Service should not be null", searchWrapper.getVnfSearch()); + } + + @Test + public void validateInitializer() { + + try { + assertNotNull("Oxm Model loader should not be null", searchWrapper.getOxmModelLoader()); + assertNotNull("SearchAbstractionConfig should not be null", searchWrapper.getSasConfig()); + assertNotNull("SearchAdapter should not be null", searchWrapper.getSearch()); + assertNotNull("Suggestion Config should not be null", searchWrapper.getSuggestionConfig()); + assertNotNull("VnfSearchService should not be null", searchWrapper.getVnfSearch()); + + searchWrapper.setOxmModelLoader(null); + searchWrapper.setSasConfig(null); + searchWrapper.setSearch(null); + searchWrapper.setSuggestionConfig(null); + searchWrapper.setVnfSearch(null); + + assertNull("Oxm Model loader should be null", searchWrapper.getOxmModelLoader()); + assertNull("SearchAbstractionConfig should be null", searchWrapper.getSasConfig()); + assertNull("SearchAdapter should be null", searchWrapper.getSearch()); + assertNull("Suggestion Config should be null", searchWrapper.getSuggestionConfig()); + assertNull("VnfSearchService should be null", searchWrapper.getVnfSearch()); + + } catch (Exception exc) { + fail("Servlet Initialization Failed with error = " + exc.getMessage()); + } + + } + + /** + * Test doGet() and doPost() for a non-existent end-point. A test objective would be + * to either return a 404 Not Found. + */ + /* @Test + public void validateMdcContextLoggingVariablesWhenExplicitlySet() { + + final String transactionId = "1234"; + final String serviceName = "AAI-UI"; + final String partnerName = "SparkyApp"; + + HttpServletHelper.assignRequestHeader(commonRequest, "X-TransactionId", transactionId); + HttpServletHelper.assignRequestHeader(commonRequest, "X-FromAppId", partnerName); + + HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/"); + + try { + + /* + * Testing the doGet() operation will hit the doPost() operation in the servlet as well + */ + + /* OperationResult result = doEvaluationTestMDC(true, commonRequest, commonResponse); + + assertEquals(transactionId,MDC.get(MdcContext.MDC_REQUEST_ID)); + assertEquals(serviceName,MDC.get(MdcContext.MDC_SERVICE_NAME)); + assertEquals(partnerName,MDC.get(MdcContext.MDC_PARTNER_NAME)); + + } catch (Exception exc) { + exc.printStackTrace(); + fail("Unexpected exception = " + exc.getLocalizedMessage()); + } + + } + + /** + * Test doGet() and doPost() for a non-existent end-point. A test objective would be + * to either return a 404 Not Found. + */ + /* @Test + public void validateMdcContextLoggingVariablesWhenNotExplicitlySet() { + + /*final String transactionId = "1234"; + final String serviceName = "AAI-UI"; + final String partnerName = "SparkyApp"; + + HttpServletHelper.assignRequestHeader(commonRequest, "X-TransactionId", transactionId); + HttpServletHelper.assignRequestHeader(commonRequest, "X-FromAppId", serviceName);*/ + +/* HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/"); + + try { + + /* + * Testing the doGet() operation will hit the doPost() operation in the servlet as well + */ + + /* OperationResult result = doEvaluationTestMDC(true, commonRequest, commonResponse); + + assertNotNull(MDC.get(MdcContext.MDC_REQUEST_ID)); + assertNotNull(MDC.get(MdcContext.MDC_SERVICE_NAME)); + assertNotNull(MDC.get(MdcContext.MDC_PARTNER_NAME)); + + } catch (Exception exc) { + exc.printStackTrace(); + fail("Unexpected exception = " + exc.getLocalizedMessage()); + } + + } + + + + /** + * Test doGet() and doPost() for a non-existent end-point. + */ + /* @Test + public void validateViewAndInspectSearchError_invalidRequestUri() { + + HttpServletHelper.assignRequestUri(commonRequest, "search/this/path/does/not/exist/"); + + try { + + /* + * Testing the doGet() operation will hit the doPost() operation in the servlet as well + */ /* - * AutoSuggestElasticSearchResponse elasticResponse = new AutoSuggestElasticSearchResponse(); - * - * elasticResponse.setTook(1); - * - * elasticResponse.setTimedOut(false); elasticResponse.addShard("total", "5"); - * elasticResponse.addShard("successful", "5"); elasticResponse.addShard("failed", "0"); - * - * AutoSuggestElasticHitEntity elasticHit = new AutoSuggestElasticHitEntity(); - * elasticHit.setIndex("entityautosuggestindex-localhost"); elasticHit.setType("default"); - * elasticHit.setId("2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"); - * elasticHit.setScore("1"); - * - * AutoSuggestDocumentEntityFields suggestDocFields = new AutoSuggestDocumentEntityFields(); - * suggestDocFields.addInput("VNFs"); suggestDocFields.addInput("generic-vnfs"); - * suggestDocFields.setOutput("VNFs"); suggestDocFields.setPayload(new PayloadEntity()); - * suggestDocFields.setWeight(100); - * - * AutoSuggestDocumentEntity autoSuggestDoc = new AutoSuggestDocumentEntity(); - * autoSuggestDoc.setFields(suggestDocFields); - * - * elasticHit.setSource(autoSuggestDoc); - * - * AutoSuggestElasticHitsEntity hits = new AutoSuggestElasticHitsEntity(); hits.addHit(elasticHit); - * - * elasticResponse.setHits(hits); - * - * - * OperationResult mockedSearchResponse = new OperationResult(); - * mockedSearchResponse.setResultCode(200); - * - * mockedSearchResponse.setResult(NodeUtils.convertObjectToJson(elasticResponse, false)); - * - * - * /* The second response is the aggregation API dip to elastic search - */ -/* - * ElasticSearchAggegrationResponse aggResponse = new ElasticSearchAggegrationResponse(); - * - * aggResponse.setTook(20); aggResponse.setTimedOut(false); - * - * aggResponse.addShard("total","5"); aggResponse.addShard("successful","5"); - * aggResponse.addShard("failed","0"); - * - * ElasticHitsEntity hitsEntity = new ElasticHitsEntity(); - * - * hitsEntity.setTotal(3170); hitsEntity.setMaxScore(0); - * - * aggResponse.setHits(hitsEntity); - * - * ElasticSearchAggregation defaultAggregation = new ElasticSearchAggregation(); - * - * defaultAggregation.setDocCountErrorUpperBound(0); defaultAggregation.setSumOtherDocCount(0); - * defaultAggregation.addBucket(new BucketEntity("created",1876)); defaultAggregation.addBucket(new - * BucketEntity("Created",649)); defaultAggregation.addBucket(new BucketEntity("Activated",158)); - * defaultAggregation.addBucket(new BucketEntity("active",59)); defaultAggregation.addBucket(new - * BucketEntity("NOT ORCHESTRATED",42)); defaultAggregation.addBucket(new - * BucketEntity("Pending-Create",10)); defaultAggregation.addBucket(new BucketEntity("Running",9)); - * defaultAggregation.addBucket(new BucketEntity("Configured",7)); defaultAggregation.addBucket(new - * BucketEntity("pending-create",7)); defaultAggregation.addBucket(new BucketEntity("Error",3)); - * defaultAggregation.addBucket(new BucketEntity("planned",3)); defaultAggregation.addBucket(new - * BucketEntity("PLANNED",2)); defaultAggregation.addBucket(new BucketEntity("ERROR",1)); - * defaultAggregation.addBucket(new BucketEntity("RUNNING",1)); defaultAggregation.addBucket(new - * BucketEntity("example-orchestration-status-val-6176",1)); - * - * aggResponse.addAggregation("default", defaultAggregation); - * - * OperationResult searchResponseForAggregation = new OperationResult(); - * searchResponseForAggregation.setResultCode(200); - * - * searchResponseForAggregation.setResult(NodeUtils.convertObjectToJson(aggResponse, false)); - * - * // TODO: make parameters expect certain values to lock in invocation attempt against a specific - * input sequence Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString())) - * .thenReturn(mockedSearchResponse).thenReturn(searchResponseForAggregation); - * - * - * /* Testing the doGet() operation will hit the doPost() operation in the servlet as well - */ -/* - * OperationResult result = doEvaluation(true, commonRequest, commonResponse); - * - * - * assertEquals(200, result.getResultCode()); - * - * // //{"shards":{"total":"5","failed":"0","successful":"5"},"count":3170} - * - * GroupByAggregationResponseEntity groupByResponse = mapper.readValue(result.getResult(), - * GroupByAggregationResponseEntity.class); - * - * assertEquals(2828, groupByResponse.getAggEntity().getTotalChartHits()); assertEquals(15, - * groupByResponse.getAggEntity().getBuckets().size()); - * - * } catch (Exception exc) { fail("Unexpected exception = " + exc.getLocalizedMessage()); } } - * - * @Test public void validateHandleDiscoverSearchFilters_vnfSearchViewName() throws IOException { - * String requestBody = "{ \"viewName\" : \"VnfSearch\" }"; String expectedResponse = - * "{\"filters\":[{\"filterId\":\"1\",\"filterName\":\"Orchestration-Status\",\"displayName\":\"Orchestration Status\",\"dataType\":\"list\"},{\"filterId\":\"2\",\"filterName\":\"Prov-Status\",\"displayName\":\"Provisioning Status\",\"dataType\":\"list\"}]}" - * ; - * - * HttpServletHelper.assignRequestUri(commonRequest, "search/discoverFilters"); - * HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); - * - * OperationResult result = doEvaluation(true, commonRequest, commonResponse); - * - * assertEquals(expectedResponse, result.getResult().trim()); } - * - * @Test public void validateFilterAggregation_successPath() { String requestBodyFilePath = - * "filters/filterAggregationEndpoint_successPath_requestBody.json"; String expectedResponseFilePath - * = "filters/filterAggregationEndpoint_successPath_expectedResponse.json"; String - * operationResultFilePath = "filters/filterAggregationEndpoint_successPath_operationResult.json"; - * - * String requestBody = getResourceFileContents(requestBodyFilePath); String expectedResponse = - * getResourceFileContents(expectedResponseFilePath); - * - * HttpServletHelper.assignRequestUri(commonRequest, "search/filterAggregation"); - * HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); - * - * OperationResult operationResult = new OperationResult(); - * operationResult.setResult(getResourceFileContents(operationResultFilePath)); - * - * vnfSearchService = new VnfSearchService(); vnfSearchService.setSearch(searchAdapter); - * searchWrapper.setVnfSearch(vnfSearchService); - * - * Mockito.when(searchAdapter.doPost(anyString(), anyString(), - * anyString())).thenReturn(operationResult); - * - * OperationResult result = doEvaluation(true, commonRequest, commonResponse); - * - * assertEquals(expectedResponse.trim(), result.getResult().trim()); } - * - * @Test public void validateFilterAggregation_emptyRequestFilterArray() throws IOException { String - * requestBodyFilePath = - * "filters/filterAggregationEndpoint_emptyRequestFilterArray_requestBody.json"; String - * expectedResponseFilePath = - * "filters/filterAggregationEndpoint_emptyRequestFilterArray_expectedResponse.json"; - * - * String requestBody = getResourceFileContents(requestBodyFilePath); String expectedResponse = - * getResourceFileContents(expectedResponseFilePath); - * - * HttpServletHelper.assignRequestUri(commonRequest, "search/filterAggregation"); - * HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); - * - * vnfSearchService = new VnfSearchService(); vnfSearchService.setSearch(searchAdapter); - * searchWrapper.setVnfSearch(vnfSearchService); - * - * OperationResult result = doEvaluation(true, commonRequest, commonResponse); - * - * assertEquals(expectedResponse.trim(), result.getResult().trim()); } - * - * @Test public void validateFilterAggregation_emptyRequestBody() throws IOException { String - * expectedResponseFilePath = - * "filters/filterAggregationEndpoint_emptyRequestBody_expectedResponse.json"; - * - * String expectedResponse = getResourceFileContents(expectedResponseFilePath); - * - * HttpServletHelper.assignRequestUri(commonRequest, "search/filterAggregation"); - * HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), "{}"); - * - * vnfSearchService = new VnfSearchService(); vnfSearchService.setSearch(searchAdapter); - * searchWrapper.setVnfSearch(vnfSearchService); - * - * OperationResult result = doEvaluation(true, commonRequest, commonResponse); - * - * assertEquals(expectedResponse.trim(), result.getResult().trim()); } - * - * @Test public void validateHandleDiscoverSearchFilters_diuiViewName() throws IOException { String - * requestBody = "{ \"viewName\" : \"dataIntegrity\" }"; String expectedResponse = - * "{\"filters\":[{\"filterId\":\"3\",\"filterName\":\"Severity\",\"displayName\":\"Severity\",\"dataType\":\"list\"},{\"filterId\":\"4\",\"filterName\":\"Category\",\"displayName\":\"Category\",\"dataType\":\"list\"},{\"filterId\":\"5\",\"filterName\":\"Date\",\"displayName\":\"Date\",\"dataType\":\"date\"},{\"filterId\":\"6\",\"filterName\":\"EntityType\",\"displayName\":\"Entity Type\",\"dataType\":\"list\"}]}" - * ; - * - * HttpServletHelper.assignRequestUri(commonRequest, "search/discoverFilters"); - * HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); - * - * OperationResult result = doEvaluation(true, commonRequest, commonResponse); - * - * assertEquals(expectedResponse, result.getResult().trim()); } - * - * @Test public void validateHandleDiscoverSearchFilterValues_validId() throws IOException { String - * requestBody = "{ \"filterIdList\" : [ { \"filterId\" : \"1\" } ] }"; String expectedResponse = - * "{\"filters\":[{\"filterId\":\"1\",\"filterName\":\"Orchestration-Status\",\"displayName\":\"Orchestration Status\",\"dataType\":\"list\",\"filterValueList\":[{\"filterValue\":\"created\",\"displayName\":\"created\"}]}]}" - * ; - * - * HttpServletHelper.assignRequestUri(commonRequest, "search/discoverFilterValues"); - * HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); - * - * FilteredSearchHelper filteredSearchHelper = Mockito.mock(FilteredSearchHelper.class); - * searchWrapper.setFilteredSearchHelper(filteredSearchHelper); - * - * UiFilterValueEntity uiFilterValueEntity = new UiFilterValueEntity(null, "created", "created"); - * - * UiFilterEntity uiFilterEntity = new UiFilterEntity(); uiFilterEntity.setDataType("list"); - * uiFilterEntity.setDisplayName("Orchestration Status"); uiFilterEntity.setFilterId("1"); - * uiFilterEntity.setFilterName("Orchestration-Status"); - * uiFilterEntity.addFilterValue(uiFilterValueEntity); - * - * UiFiltersEntity uiFiltersEntity = new UiFiltersEntity(); - * uiFiltersEntity.addFilter(uiFilterEntity); - * - * Mockito.when(filteredSearchHelper.doFilterEnumeration(Mockito.anyList())) - * .thenReturn(uiFiltersEntity); - * - * OperationResult result = doEvaluation(true, commonRequest, commonResponse); - * - * assertEquals(expectedResponse, result.getResult().trim()); } - * - * @Test public void validateHandleDiscoverSearchFilterValues_multipleValidIds() throws IOException - * { String requestBody = - * "{ \"filterIdList\" : [ { \"filterId\" : \"1\" }, { \"filterId\" : \"2\" } ] }"; String - * expectedResponse = - * "{\"filters\":[{\"filterId\":\"1\",\"filterName\":\"Orchestration-Status\",\"displayName\":\"Orchestration Status\",\"dataType\":\"list\",\"filterValueList\":[{\"filterValue\":\"created\",\"displayName\":\"created\"}]},{\"filterId\":\"2\",\"filterName\":\"Prov-Status\",\"displayName\":\"Provisioning Status\",\"dataType\":\"list\",\"filterValueList\":[{\"filterValue\":\"active\",\"displayName\":\"active\"}]}]}" - * ; - * - * HttpServletHelper.assignRequestUri(commonRequest, "search/discoverFilterValues"); - * HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); - * - * FilteredSearchHelper filteredSearchHelper = Mockito.mock(FilteredSearchHelper.class); - * searchWrapper.setFilteredSearchHelper(filteredSearchHelper); - * - * UiFiltersEntity uiFiltersEntity = new UiFiltersEntity(); - * - * UiFilterValueEntity uiFilter1ValueEntity = new UiFilterValueEntity(null, "created", "created"); - * UiFilterEntity uiFilterEntity1 = new UiFilterEntity(); uiFilterEntity1.setDataType("list"); - * uiFilterEntity1.setDisplayName("Orchestration Status"); uiFilterEntity1.setFilterId("1"); - * uiFilterEntity1.setFilterName("Orchestration-Status"); - * uiFilterEntity1.addFilterValue(uiFilter1ValueEntity); uiFiltersEntity.addFilter(uiFilterEntity1); - * - * UiFilterValueEntity uiFilter2ValueEntity = new UiFilterValueEntity(null, "active", "active"); - * UiFilterEntity uiFilterEntity2 = new UiFilterEntity(); uiFilterEntity2.setDataType("list"); - * uiFilterEntity2.setDisplayName("Provisioning Status"); uiFilterEntity2.setFilterId("2"); - * uiFilterEntity2.setFilterName("Prov-Status"); - * uiFilterEntity2.addFilterValue(uiFilter2ValueEntity); uiFiltersEntity.addFilter(uiFilterEntity2); - * - * Mockito.when(filteredSearchHelper.doFilterEnumeration(Mockito.anyList())) - * .thenReturn(uiFiltersEntity); - * - * OperationResult result = doEvaluation(true, commonRequest, commonResponse); - * - * assertEquals(expectedResponse, result.getResult().trim()); } - * - * @Test public void validateHandleDiscoverSearchFilterValues_invalidId() throws IOException { - * String requestBody = "{ \"filterIdList\" : [ { \"filterId\" : \"999\" } ] }"; String - * expectedResponse = "{\"filters\":[]}"; - * - * HttpServletHelper.assignRequestUri(commonRequest, "search/discoverFilterValues"); - * HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); - * - * OperationResult result = doEvaluation(true, commonRequest, commonResponse); - * - * assertEquals(expectedResponse, result.getResult().trim()); } - * - * @Test public void validateHandleDiscoverSearchFilterValues_validIdAndInvalidId() throws - * IOException { String requestBody = - * "{ \"filterIdList\" : [ { \"filterId\" : \"1\" }, { \"filterId\" : \"999\" } ] }"; String - * expectedResponse = - * "{\"filters\":[{\"filterId\":\"1\",\"filterName\":\"Orchestration-Status\",\"displayName\":\"Orchestration Status\",\"dataType\":\"list\",\"filterValueList\":[{\"filterValue\":\"created\",\"displayName\":\"created\"}]}]}" - * ; - * - * HttpServletHelper.assignRequestUri(commonRequest, "search/discoverFilterValues"); - * HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); - * - * FilteredSearchHelper filteredSearchHelper = Mockito.mock(FilteredSearchHelper.class); - * searchWrapper.setFilteredSearchHelper(filteredSearchHelper); - * - * UiFilterValueEntity uiFilterValueEntity = new UiFilterValueEntity(null, "created", "created"); - * - * UiFilterEntity uiFilterEntity = new UiFilterEntity(); uiFilterEntity.setDataType("list"); - * uiFilterEntity.setDisplayName("Orchestration Status"); uiFilterEntity.setFilterId("1"); - * uiFilterEntity.setFilterName("Orchestration-Status"); - * uiFilterEntity.addFilterValue(uiFilterValueEntity); - * - * UiFiltersEntity uiFiltersEntity = new UiFiltersEntity(); - * uiFiltersEntity.addFilter(uiFilterEntity); - * - * Mockito.when(filteredSearchHelper.doFilterEnumeration(Mockito.anyList())) - * .thenReturn(uiFiltersEntity); - * - * OperationResult result = doEvaluation(true, commonRequest, commonResponse); - * - * assertEquals(expectedResponse, result.getResult().trim()); } - * - * /** Builds the resource entity descriptor. - * - * @param entityType the entity type - * - * @param attributeNames the attribute names - * - * @param searchableAttributes the searchable attributes - * - * @return the oxm entity descriptor - */ -/* - * @SuppressWarnings("unchecked") private OxmEntityDescriptor buildResourceEntityDescriptor(String - * entityType, String attributeNames, String searchableAttributes) { OxmEntityDescriptor descriptor - * = new OxmEntityDescriptor(); descriptor.setEntityName(entityType); - * - * if (attributeNames != null) { - * descriptor.setPrimaryKeyAttributeName(Arrays.asList(attributeNames.split(","))); } - * - * if (searchableAttributes != null) { - * descriptor.setSearchableAttributes(Arrays.asList(searchableAttributes.split(","))); } - * - * return descriptor; } - * - * /** Initialize entity descriptors. - */ -/* - * private void initializeEntityDescriptors() { descriptors.put("customer", - * buildResourceEntityDescriptor("customer", "service-instance-id", "f1,f2,f3")); } - * - * /** Builds the view and inspect search request. - * - * @param maxResults the max results - * - * @param queryStr the query str - * - * @return the string - * - * @throws JsonProcessingException the json processing exception - */ + OperationResult result = doEvaluation(true, commonRequest, commonResponse); + assertEquals(404, result.getResultCode()); + assertTrue(result.getResult().contains("Ignored request-uri")); + + } catch (Exception exc) { + exc.printStackTrace(); + fail("Unexpected exception = " + exc.getLocalizedMessage()); + } + + } + + /** + * Test doGet() and doPost() for Unified Query Search success path + */ +/* @Test + public void validateQuerySearch_successPath() { + + try { + + QuerySearchEntity searchEntity = new QuerySearchEntity(); + searchEntity.setMaxResults("10"); + searchEntity.setQueryStr("the quick brown fox"); + + HttpServletHelper.assignRequestUri(commonRequest, "search/querysearch"); + HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), + NodeUtils.convertObjectToJson(searchEntity, false)); + + + // set search-abstraction-response that we expect to get back from real system, but stubbed through a mock + // to fulfill collaborator behavior + + OperationResult mockedEntitySearchResponse = new OperationResult(); + mockedEntitySearchResponse.setResultCode(200); + mockedEntitySearchResponse.setResult(NodeUtils.convertObjectToJson( + SearchAbstractionEntityBuilder.getSuccessfulEntitySearchResponse(), false)); + + // TODO: make parameters expect certain values to lock in invocation attempt against a specific input sequence + Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString())) + .thenReturn(mockedEntitySearchResponse); + + List<SuggestionEntity> autoSuggestions = new ArrayList<SuggestionEntity>(); + + autoSuggestions.add(new SuggestionEntity("1234", "vnf", "VNFs", null)); + autoSuggestions.add(new SuggestionEntity("1111", "vnf", "Created VNFs", null)); + autoSuggestions.add(new SuggestionEntity("1122", "vnf", "ACTIVE VNFs", null)); + autoSuggestions.add(new SuggestionEntity("2233", "vnf", "ACTIVE and Error VNFs", null)); + autoSuggestions.add(new SuggestionEntity("3344", "vnf", "ACTIVE and NOT ORCHESTRATED VNFs", null)); + autoSuggestions.add(new SuggestionEntity("4455", "vnf", "ACTIVE and Running VNFs", null)); + autoSuggestions.add(new SuggestionEntity("5566", "vnf", "Activated VNFs", null)); + autoSuggestions.add(new SuggestionEntity("6677", "vnf", "CAPPED VNFs", null)); + autoSuggestions.add(new SuggestionEntity("7788", "vnf", "CAPPED and Created VNFs", null)); + + Mockito.when(vnfSearchService.getSuggestionsResults(Mockito.anyObject(), Mockito.anyInt())) + .thenReturn(autoSuggestions); + + /* + * Testing the doGet() operation will hit the doPost() operation in the servlet as well + */ /* - * public String buildViewAndInspectSearchRequest(Integer maxResults, String queryStr) throws - * JsonProcessingException { - * - * /* { "maxResults" : "10", "searchStr" : "<search bar text>" } - */ + OperationResult result = doEvaluation(true, commonRequest, commonResponse); + + + assertEquals(200, result.getResultCode()); + + SearchResponse searchResponse = mapper.readValue(result.getResult(), SearchResponse.class); + + assertEquals(10, searchResponse.getTotalFound()); + + int numVnf = 0; + int numViewInspect = 0; + + for ( SuggestionEntity suggestion : searchResponse.getSuggestions()) { + + if ( VNF_ROUTE.equals(suggestion.getRoute())) { + numVnf++; + } else if ( VIEW_INSPECT_ROUTE.equals(suggestion.getRoute())) { + numViewInspect++; + } + } + + assertEquals(5, numVnf); + assertEquals(5, numViewInspect); + + //assertTrue(result.getResult().contains("Ignored request-uri")); + + } catch (Exception exc) { + fail("Unexpected exception = " + exc.getLocalizedMessage()); + } + + } + + /** + * Test doGet() and doPost() for Unified Query Search success path + */ + /*@Test + @Ignore + public void validateSummaryByEntityTypeCount_successPath() { + + try { + + HttpServletHelper.assignRequestUri(commonRequest, "search/summarybyentitytype/count"); + + Map<String,String> payloadFields = new HashMap<String,String>(); + payloadFields.put("hashId", "662d1b57c31df70d7ef57ec53c0ace81578ec77b6bc5de055a57c7547ec122dd"); + payloadFields.put("groupby", "orchestration-status"); + + HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), NodeUtils.convertObjectToJson(payloadFields, false)); + + /* + * In this test we don't want to mock the vnf search service, only it's collaborator + * interactions with a REST endpoint. + */ + /* vnfSearchService = new VnfSearchService(); + vnfSearchService.setSearch(searchAdapter); + searchWrapper.setVnfSearch(vnfSearchService); + + /* + * The first network response to mock is the one to elastic search to get the suggestion entity by hash id + * + * http://localhost:9200/entityautosuggestindex-localhost/_search + * {"query":{"term":{"_id":"2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"}}} + */ + /* + AutoSuggestElasticSearchResponse elasticResponse = new AutoSuggestElasticSearchResponse(); + + elasticResponse.setTook(1); + + elasticResponse.setTimedOut(false); + elasticResponse.addShard("total", "5"); + elasticResponse.addShard("successful", "5"); + elasticResponse.addShard("failed", "0"); + + AutoSuggestElasticHitEntity elasticHit = new AutoSuggestElasticHitEntity(); + elasticHit.setIndex("entityautosuggestindex-localhost"); + elasticHit.setType("default"); + elasticHit.setId("2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"); + elasticHit.setScore("1"); + + AutoSuggestDocumentEntityFields suggestDocFields = new AutoSuggestDocumentEntityFields(); + suggestDocFields.addInput("VNFs"); + suggestDocFields.addInput("generic-vnfs"); + suggestDocFields.setOutput("VNFs"); + suggestDocFields.setPayload(new PayloadEntity()); + suggestDocFields.setWeight(100); + + AutoSuggestDocumentEntity autoSuggestDoc = new AutoSuggestDocumentEntity(); + autoSuggestDoc.setFields(suggestDocFields); + + elasticHit.setSource(autoSuggestDoc); + + AutoSuggestElasticHitsEntity hits = new AutoSuggestElasticHitsEntity(); + hits.addHit(elasticHit); + + elasticResponse.setHits(hits); + + + OperationResult mockedSearchResponse = new OperationResult(); + mockedSearchResponse.setResultCode(200); + + mockedSearchResponse.setResult(NodeUtils.convertObjectToJson(elasticResponse, false)); + + + /* + * The second response is the count API dip to elastic search + */ + /* + ElasticSearchCountResponse countResponse = new ElasticSearchCountResponse(); + countResponse.setCount(3170); + countResponse.addShard("total", "5"); + countResponse.addShard("successful", "5"); + countResponse.addShard("failed", "0"); + + OperationResult searchResponseForCount = new OperationResult(); + searchResponseForCount.setResultCode(200); + + searchResponseForCount.setResult(NodeUtils.convertObjectToJson(countResponse, false)); + + // TODO: make parameters expect certain values to lock in invocation attempt against a specific input sequence + Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString())) + .thenReturn(mockedSearchResponse).thenReturn(searchResponseForCount); + + + /* + * Testing the doGet() operation will hit the doPost() operation in the servlet as well + */ /* - * ObjectNode rootNode = mapper.createObjectNode(); - * - * if (maxResults != null) { rootNode.put("maxResults", maxResults); } - * - * if (queryStr != null) { rootNode.put("queryStr", queryStr); } - * - * return NodeUtils.convertObjectToJson(rootNode, true); - * - * } - * - * public String getResourceFileContents(String filePath) { StringBuilder result = new - * StringBuilder(""); - * - * ClassLoader classLoader = getClass().getClassLoader(); File file = new - * File(classLoader.getResource(filePath).getFile()); - * - * try (Scanner scanner = new Scanner(file)) { while (scanner.hasNextLine()) { String line = - * scanner.nextLine(); result.append(line).append("\n"); } - * - * scanner.close(); - * - * } catch (IOException e) { e.printStackTrace(); } - * - * return result.toString(); } - * - * - * /** Do evaluation. - * - * @param doGet the do get - * - * @param req the req - * - * @param res the res - * - * @return the string - *//* - * private OperationResult doEvaluationTestMDC(boolean doGet, HttpServletRequest req, - * HttpServletResponse res) { - * - * /* Test method invocation + OperationResult result = doEvaluation(true, commonRequest, commonResponse); + + + assertEquals(200, result.getResultCode()); + + // + //{"shards":{"total":"5","failed":"0","successful":"5"},"count":3170} + + EntityCountResponse entityCountResponse = mapper.readValue(result.getResult(), EntityCountResponse.class); + + assertEquals(3170, entityCountResponse.getCount()); + + } catch (Exception exc) { + fail("Unexpected exception = " + exc.getLocalizedMessage()); + } + + } + + + /** + * Test doGet() and doPost() for Unified Query Search success path */ + /*@Test + @Ignore + public void validateSummaryByEntityType_successPath() { + + try { + + HttpServletHelper.assignRequestUri(commonRequest, "search/summarybyentitytype"); + + Map<String,String> payloadFields = new HashMap<String,String>(); + payloadFields.put("hashId", "662d1b57c31df70d7ef57ec53c0ace81578ec77b6bc5de055a57c7547ec122dd"); + payloadFields.put("groupby", "orchestration-status"); + + HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), NodeUtils.convertObjectToJson(payloadFields, false)); + + /* + * In this test we don't want to mock the vnf search service, only it's collaborator + * interactions with a REST endpoint. + */ + /* vnfSearchService = new VnfSearchService(); + vnfSearchService.setSearch(searchAdapter); + searchWrapper.setVnfSearch(vnfSearchService); + + /* + * The first network response to mock is the one to elastic search to get the suggestion entity by hash id + * + * http://localhost:9200/entityautosuggestindex-localhost/_search + * {"query":{"term":{"_id":"2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"}}} + */ + + /* AutoSuggestElasticSearchResponse elasticResponse = new AutoSuggestElasticSearchResponse(); + + elasticResponse.setTook(1); + + elasticResponse.setTimedOut(false); + elasticResponse.addShard("total", "5"); + elasticResponse.addShard("successful", "5"); + elasticResponse.addShard("failed", "0"); + + AutoSuggestElasticHitEntity elasticHit = new AutoSuggestElasticHitEntity(); + elasticHit.setIndex("entityautosuggestindex-localhost"); + elasticHit.setType("default"); + elasticHit.setId("2172a3c25ae56e4995038ffbc1f055692bfc76c0b8ceda1205bc745a9f7a805d"); + elasticHit.setScore("1"); + + AutoSuggestDocumentEntityFields suggestDocFields = new AutoSuggestDocumentEntityFields(); + suggestDocFields.addInput("VNFs"); + suggestDocFields.addInput("generic-vnfs"); + suggestDocFields.setOutput("VNFs"); + suggestDocFields.setPayload(new PayloadEntity()); + suggestDocFields.setWeight(100); + + AutoSuggestDocumentEntity autoSuggestDoc = new AutoSuggestDocumentEntity(); + autoSuggestDoc.setFields(suggestDocFields); + + elasticHit.setSource(autoSuggestDoc); + + AutoSuggestElasticHitsEntity hits = new AutoSuggestElasticHitsEntity(); + hits.addHit(elasticHit); + + elasticResponse.setHits(hits); + + + OperationResult mockedSearchResponse = new OperationResult(); + mockedSearchResponse.setResultCode(200); + + mockedSearchResponse.setResult(NodeUtils.convertObjectToJson(elasticResponse, false)); + + + /* + * The second response is the aggregation API dip to elastic search + */ + /* + ElasticSearchAggegrationResponse aggResponse = new ElasticSearchAggegrationResponse(); + + aggResponse.setTook(20); + aggResponse.setTimedOut(false); + + aggResponse.addShard("total","5"); + aggResponse.addShard("successful","5"); + aggResponse.addShard("failed","0"); + + ElasticHitsEntity hitsEntity = new ElasticHitsEntity(); + + hitsEntity.setTotal(3170); + hitsEntity.setMaxScore(0); + + aggResponse.setHits(hitsEntity); + + ElasticSearchAggregation defaultAggregation = new ElasticSearchAggregation(); + + defaultAggregation.setDocCountErrorUpperBound(0); + defaultAggregation.setSumOtherDocCount(0); + defaultAggregation.addBucket(new BucketEntity("created",1876)); + defaultAggregation.addBucket(new BucketEntity("Created",649)); + defaultAggregation.addBucket(new BucketEntity("Activated",158)); + defaultAggregation.addBucket(new BucketEntity("active",59)); + defaultAggregation.addBucket(new BucketEntity("NOT ORCHESTRATED",42)); + defaultAggregation.addBucket(new BucketEntity("Pending-Create",10)); + defaultAggregation.addBucket(new BucketEntity("Running",9)); + defaultAggregation.addBucket(new BucketEntity("Configured",7)); + defaultAggregation.addBucket(new BucketEntity("pending-create",7)); + defaultAggregation.addBucket(new BucketEntity("Error",3)); + defaultAggregation.addBucket(new BucketEntity("planned",3)); + defaultAggregation.addBucket(new BucketEntity("PLANNED",2)); + defaultAggregation.addBucket(new BucketEntity("ERROR",1)); + defaultAggregation.addBucket(new BucketEntity("RUNNING",1)); + defaultAggregation.addBucket(new BucketEntity("example-orchestration-status-val-6176",1)); + + aggResponse.addAggregation("default", defaultAggregation); + + OperationResult searchResponseForAggregation = new OperationResult(); + searchResponseForAggregation.setResultCode(200); + + searchResponseForAggregation.setResult(NodeUtils.convertObjectToJson(aggResponse, false)); + + // TODO: make parameters expect certain values to lock in invocation attempt against a specific input sequence + Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString())) + .thenReturn(mockedSearchResponse).thenReturn(searchResponseForAggregation); + + + /* + * Testing the doGet() operation will hit the doPost() operation in the servlet as well + */ /* - * SearchServlet searchServlet = new SearchServlet(); try { searchServlet.init(); } catch - * (ServletException e) { // TODO Auto-generated catch block e.printStackTrace(); } - * ArgumentCaptor<Integer> responseCodeCaptor = ArgumentCaptor.forClass(Integer.class); - * - * try { if (doGet) { searchServlet.doGet(req, res); } else { searchServlet.doPost(req, res); } } - * catch (ServletException exc) { fail(ExceptionHelper.extractStackTraceElements(5, exc)); } catch - * (IOException exc) { fail(ExceptionHelper.extractStackTraceElements(5, exc)); } - * - * responseStringWriter.flush(); Mockito.verify(commonResponse, - * Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture()); - * - * OperationResult result = new OperationResult(); - * - * result.setResultCode(responseCodeCaptor.getValue()); - * result.setResult(responseStringWriter.toString()); - * - * return result; - * - * } - * - * /** Do evaluation. - * - * @param doGet the do get - * - * @param req the req - * - * @param res the res - * - * @return the string - *//* - * private OperationResult doEvaluation(boolean doGet, HttpServletRequest req, HttpServletResponse - * res) { - * - * /* Test method invocation + OperationResult result = doEvaluation(true, commonRequest, commonResponse); + + + assertEquals(200, result.getResultCode()); + + // + //{"shards":{"total":"5","failed":"0","successful":"5"},"count":3170} + + GroupByAggregationResponseEntity groupByResponse = mapper.readValue(result.getResult(), GroupByAggregationResponseEntity.class); + + assertEquals(2828, groupByResponse.getAggEntity().getTotalChartHits()); + assertEquals(15, groupByResponse.getAggEntity().getBuckets().size()); + + } catch (Exception exc) { + fail("Unexpected exception = " + exc.getLocalizedMessage()); + } + } + + @Test + public void validateHandleDiscoverSearchFilters_vnfSearchViewName() throws IOException { + String requestBody = "{ \"viewName\" : \"VnfSearch\" }"; + String expectedResponse = "{\"filters\":[{\"filterId\":\"1\",\"filterName\":\"Orchestration-Status\",\"displayName\":\"Orchestration Status\",\"dataType\":\"list\"},{\"filterId\":\"2\",\"filterName\":\"Prov-Status\",\"displayName\":\"Provisioning Status\",\"dataType\":\"list\"}]}"; + + HttpServletHelper.assignRequestUri(commonRequest, "search/discoverFilters"); + HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); + + OperationResult result = doEvaluation(true, commonRequest, commonResponse); + + assertEquals(expectedResponse, result.getResult().trim()); + } + + @Test + public void validateFilterAggregation_successPath() { + String requestBodyFilePath = "filters/filterAggregationEndpoint_successPath_requestBody.json"; + String expectedResponseFilePath = "filters/filterAggregationEndpoint_successPath_expectedResponse.json"; + String operationResultFilePath = "filters/filterAggregationEndpoint_successPath_operationResult.json"; + + String requestBody = getResourceFileContents(requestBodyFilePath); + String expectedResponse = getResourceFileContents(expectedResponseFilePath); + + HttpServletHelper.assignRequestUri(commonRequest, "search/filterAggregation"); + HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); + + OperationResult operationResult = new OperationResult(); + operationResult.setResult(getResourceFileContents(operationResultFilePath)); + + vnfSearchService = new VnfSearchService(); + vnfSearchService.setSearch(searchAdapter); + searchWrapper.setVnfSearch(vnfSearchService); + + Mockito.when(searchAdapter.doPost(anyString(), anyString(), anyString())).thenReturn(operationResult); + + OperationResult result = doEvaluation(true, commonRequest, commonResponse); + + assertEquals(expectedResponse.trim(), result.getResult().trim()); + } + + @Test + public void validateFilterAggregation_emptyRequestFilterArray() throws IOException { + String requestBodyFilePath = "filters/filterAggregationEndpoint_emptyRequestFilterArray_requestBody.json"; + String expectedResponseFilePath = "filters/filterAggregationEndpoint_emptyRequestFilterArray_expectedResponse.json"; + + String requestBody = getResourceFileContents(requestBodyFilePath); + String expectedResponse = getResourceFileContents(expectedResponseFilePath); + + HttpServletHelper.assignRequestUri(commonRequest, "search/filterAggregation"); + HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); + + vnfSearchService = new VnfSearchService(); + vnfSearchService.setSearch(searchAdapter); + searchWrapper.setVnfSearch(vnfSearchService); + + OperationResult result = doEvaluation(true, commonRequest, commonResponse); + + assertEquals(expectedResponse.trim(), result.getResult().trim()); + } + + @Test + public void validateFilterAggregation_emptyRequestBody() throws IOException { + String expectedResponseFilePath = "filters/filterAggregationEndpoint_emptyRequestBody_expectedResponse.json"; + + String expectedResponse = getResourceFileContents(expectedResponseFilePath); + + HttpServletHelper.assignRequestUri(commonRequest, "search/filterAggregation"); + HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), "{}"); + + vnfSearchService = new VnfSearchService(); + vnfSearchService.setSearch(searchAdapter); + searchWrapper.setVnfSearch(vnfSearchService); + + OperationResult result = doEvaluation(true, commonRequest, commonResponse); + + assertEquals(expectedResponse.trim(), result.getResult().trim()); + } + + @Test + public void validateHandleDiscoverSearchFilters_diuiViewName() throws IOException { + String requestBody = "{ \"viewName\" : \"dataIntegrity\" }"; + String expectedResponse = "{\"filters\":[{\"filterId\":\"3\",\"filterName\":\"Severity\",\"displayName\":\"Severity\",\"dataType\":\"list\"},{\"filterId\":\"4\",\"filterName\":\"Category\",\"displayName\":\"Category\",\"dataType\":\"list\"},{\"filterId\":\"5\",\"filterName\":\"Date\",\"displayName\":\"Date\",\"dataType\":\"date\"},{\"filterId\":\"6\",\"filterName\":\"EntityType\",\"displayName\":\"Entity Type\",\"dataType\":\"list\"}]}"; + + HttpServletHelper.assignRequestUri(commonRequest, "search/discoverFilters"); + HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); + + OperationResult result = doEvaluation(true, commonRequest, commonResponse); + + assertEquals(expectedResponse, result.getResult().trim()); + } + + @Test + public void validateHandleDiscoverSearchFilterValues_validId() throws IOException { + String requestBody = "{ \"filterIdList\" : [ { \"filterId\" : \"1\" } ] }"; + String expectedResponse = "{\"filters\":[{\"filterId\":\"1\",\"filterName\":\"Orchestration-Status\",\"displayName\":\"Orchestration Status\",\"dataType\":\"list\",\"filterValueList\":[{\"filterValue\":\"created\",\"displayName\":\"created\"}]}]}"; + + HttpServletHelper.assignRequestUri(commonRequest, "search/discoverFilterValues"); + HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); + + FilteredSearchHelper filteredSearchHelper = Mockito.mock(FilteredSearchHelper.class); + searchWrapper.setFilteredSearchHelper(filteredSearchHelper); + + UiFilterValueEntity uiFilterValueEntity = new UiFilterValueEntity(null, "created", "created"); + + UiFilterEntity uiFilterEntity = new UiFilterEntity(); + uiFilterEntity.setDataType("list"); + uiFilterEntity.setDisplayName("Orchestration Status"); + uiFilterEntity.setFilterId("1"); + uiFilterEntity.setFilterName("Orchestration-Status"); + uiFilterEntity.addFilterValue(uiFilterValueEntity); + + UiFiltersEntity uiFiltersEntity = new UiFiltersEntity(); + uiFiltersEntity.addFilter(uiFilterEntity); + + Mockito.when(filteredSearchHelper.doFilterEnumeration(Mockito.anyList())) + .thenReturn(uiFiltersEntity); + + OperationResult result = doEvaluation(true, commonRequest, commonResponse); + + assertEquals(expectedResponse, result.getResult().trim()); + } + + @Test + public void validateHandleDiscoverSearchFilterValues_multipleValidIds() throws IOException { + String requestBody = "{ \"filterIdList\" : [ { \"filterId\" : \"1\" }, { \"filterId\" : \"2\" } ] }"; + String expectedResponse = "{\"filters\":[{\"filterId\":\"1\",\"filterName\":\"Orchestration-Status\",\"displayName\":\"Orchestration Status\",\"dataType\":\"list\",\"filterValueList\":[{\"filterValue\":\"created\",\"displayName\":\"created\"}]},{\"filterId\":\"2\",\"filterName\":\"Prov-Status\",\"displayName\":\"Provisioning Status\",\"dataType\":\"list\",\"filterValueList\":[{\"filterValue\":\"active\",\"displayName\":\"active\"}]}]}"; + + HttpServletHelper.assignRequestUri(commonRequest, "search/discoverFilterValues"); + HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); + + FilteredSearchHelper filteredSearchHelper = Mockito.mock(FilteredSearchHelper.class); + searchWrapper.setFilteredSearchHelper(filteredSearchHelper); + + UiFiltersEntity uiFiltersEntity = new UiFiltersEntity(); + + UiFilterValueEntity uiFilter1ValueEntity = new UiFilterValueEntity(null, "created", "created"); + UiFilterEntity uiFilterEntity1 = new UiFilterEntity(); + uiFilterEntity1.setDataType("list"); + uiFilterEntity1.setDisplayName("Orchestration Status"); + uiFilterEntity1.setFilterId("1"); + uiFilterEntity1.setFilterName("Orchestration-Status"); + uiFilterEntity1.addFilterValue(uiFilter1ValueEntity); + uiFiltersEntity.addFilter(uiFilterEntity1); + + UiFilterValueEntity uiFilter2ValueEntity = new UiFilterValueEntity(null, "active", "active"); + UiFilterEntity uiFilterEntity2 = new UiFilterEntity(); + uiFilterEntity2.setDataType("list"); + uiFilterEntity2.setDisplayName("Provisioning Status"); + uiFilterEntity2.setFilterId("2"); + uiFilterEntity2.setFilterName("Prov-Status"); + uiFilterEntity2.addFilterValue(uiFilter2ValueEntity); + uiFiltersEntity.addFilter(uiFilterEntity2); + + Mockito.when(filteredSearchHelper.doFilterEnumeration(Mockito.anyList())) + .thenReturn(uiFiltersEntity); + + OperationResult result = doEvaluation(true, commonRequest, commonResponse); + + assertEquals(expectedResponse, result.getResult().trim()); + } + + @Test + public void validateHandleDiscoverSearchFilterValues_invalidId() throws IOException { + String requestBody = "{ \"filterIdList\" : [ { \"filterId\" : \"999\" } ] }"; + String expectedResponse = "{\"filters\":[]}"; + + HttpServletHelper.assignRequestUri(commonRequest, "search/discoverFilterValues"); + HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); + + OperationResult result = doEvaluation(true, commonRequest, commonResponse); + + assertEquals(expectedResponse, result.getResult().trim()); + } + + @Test + public void validateHandleDiscoverSearchFilterValues_validIdAndInvalidId() throws IOException { + String requestBody = "{ \"filterIdList\" : [ { \"filterId\" : \"1\" }, { \"filterId\" : \"999\" } ] }"; + String expectedResponse = "{\"filters\":[{\"filterId\":\"1\",\"filterName\":\"Orchestration-Status\",\"displayName\":\"Orchestration Status\",\"dataType\":\"list\",\"filterValueList\":[{\"filterValue\":\"created\",\"displayName\":\"created\"}]}]}"; + + HttpServletHelper.assignRequestUri(commonRequest, "search/discoverFilterValues"); + HttpServletHelper.setRequestPayload(commonRequest, MediaType.JSON_UTF_8.toString(), requestBody); + + FilteredSearchHelper filteredSearchHelper = Mockito.mock(FilteredSearchHelper.class); + searchWrapper.setFilteredSearchHelper(filteredSearchHelper); + + UiFilterValueEntity uiFilterValueEntity = new UiFilterValueEntity(null, "created", "created"); + + UiFilterEntity uiFilterEntity = new UiFilterEntity(); + uiFilterEntity.setDataType("list"); + uiFilterEntity.setDisplayName("Orchestration Status"); + uiFilterEntity.setFilterId("1"); + uiFilterEntity.setFilterName("Orchestration-Status"); + uiFilterEntity.addFilterValue(uiFilterValueEntity); + + UiFiltersEntity uiFiltersEntity = new UiFiltersEntity(); + uiFiltersEntity.addFilter(uiFilterEntity); + + Mockito.when(filteredSearchHelper.doFilterEnumeration(Mockito.anyList())) + .thenReturn(uiFiltersEntity); + + OperationResult result = doEvaluation(true, commonRequest, commonResponse); + + assertEquals(expectedResponse, result.getResult().trim()); + } + + /** + * Builds the resource entity descriptor. + * + * @param entityType the entity type + * @param attributeNames the attribute names + * @param searchableAttributes the searchable attributes + * @return the oxm entity descriptor + */ +/* @SuppressWarnings("unchecked") + private OxmEntityDescriptor buildResourceEntityDescriptor(String entityType, + String attributeNames, String searchableAttributes) { + OxmEntityDescriptor descriptor = new OxmEntityDescriptor(); + descriptor.setEntityName(entityType); + + if (attributeNames != null) { + descriptor.setPrimaryKeyAttributeName(Arrays.asList(attributeNames.split(","))); + } + + if (searchableAttributes != null) { + descriptor.setSearchableAttributes(Arrays.asList(searchableAttributes.split(","))); + } + + return descriptor; + } + + /** + * Initialize entity descriptors. + */ + /*private void initializeEntityDescriptors() { + descriptors.put("customer", + buildResourceEntityDescriptor("customer", "service-instance-id", "f1,f2,f3")); + } + + /** + * Builds the view and inspect search request. + * + * @param maxResults the max results + * @param queryStr the query str + * @return the string + * @throws JsonProcessingException the json processing exception */ + /* public String buildViewAndInspectSearchRequest(Integer maxResults, String queryStr) + throws JsonProcessingException { + + /* + * { "maxResults" : "10", "searchStr" : "<search bar text>" } + */ /* - * ArgumentCaptor<Integer> responseCodeCaptor = ArgumentCaptor.forClass(Integer.class); - * - * try { if (doGet) { searchWrapper.doGet(req, res); } else { searchWrapper.doPost(req, res); } } - * catch (ServletException exc) { fail(ExceptionHelper.extractStackTraceElements(5, exc)); } catch - * (IOException exc) { fail(ExceptionHelper.extractStackTraceElements(5, exc)); } - * - * responseStringWriter.flush(); Mockito.verify(commonResponse, - * Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture()); - * - * OperationResult result = new OperationResult(); - * - * result.setResultCode(responseCodeCaptor.getValue()); - * result.setResult(responseStringWriter.toString()); - * - * return result; - * - * } - * - * } - */ + ObjectNode rootNode = mapper.createObjectNode(); + + if (maxResults != null) { + rootNode.put("maxResults", maxResults); + } + + if (queryStr != null) { + rootNode.put("queryStr", queryStr); + } + + return NodeUtils.convertObjectToJson(rootNode, true); + + } + + public String getResourceFileContents(String filePath) { + StringBuilder result = new StringBuilder(""); + + ClassLoader classLoader = getClass().getClassLoader(); + File file = new File(classLoader.getResource(filePath).getFile()); + + try (Scanner scanner = new Scanner(file)) { + while (scanner.hasNextLine()) { + String line = scanner.nextLine(); + result.append(line).append("\n"); + } + + scanner.close(); + + } catch (IOException e) { + e.printStackTrace(); + } + + return result.toString(); + } + + + /** + * Do evaluation. + * + * @param doGet the do get + * @param req the req + * @param res the res + * @return the string + *//* + private OperationResult doEvaluationTestMDC(boolean doGet, HttpServletRequest req, HttpServletResponse res) { + + /* + * Test method invocation + */ +/* + SearchServlet searchServlet = new SearchServlet(); + try { + searchServlet.init(); + } catch (ServletException e) { + // TODO Auto-generated catch block + e.printStackTrace(); + } + ArgumentCaptor<Integer> responseCodeCaptor = ArgumentCaptor.forClass(Integer.class); + + try { + if (doGet) { + searchServlet.doGet(req, res); + } else { + searchServlet.doPost(req, res); + } + } catch (ServletException exc) { + fail(ExceptionHelper.extractStackTraceElements(5, exc)); + } catch (IOException exc) { + fail(ExceptionHelper.extractStackTraceElements(5, exc)); + } + + responseStringWriter.flush(); + Mockito.verify(commonResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture()); + + OperationResult result = new OperationResult(); + + result.setResultCode(responseCodeCaptor.getValue()); + result.setResult(responseStringWriter.toString()); + + return result; + + } + + /** + * Do evaluation. + * + * @param doGet the do get + * @param req the req + * @param res the res + * @return the string + *//* + private OperationResult doEvaluation(boolean doGet, HttpServletRequest req, HttpServletResponse res) { + + /* + * Test method invocation + */ + /* ArgumentCaptor<Integer> responseCodeCaptor = ArgumentCaptor.forClass(Integer.class); + + try { + if (doGet) { + searchWrapper.doGet(req, res); + } else { + searchWrapper.doPost(req, res); + } + } catch (ServletException exc) { + fail(ExceptionHelper.extractStackTraceElements(5, exc)); + } catch (IOException exc) { + fail(ExceptionHelper.extractStackTraceElements(5, exc)); + } + + responseStringWriter.flush(); + Mockito.verify(commonResponse, Mockito.atLeast(1)).setStatus(responseCodeCaptor.capture()); + + OperationResult result = new OperationResult(); + + result.setResultCode(responseCodeCaptor.getValue()); + result.setResult(responseStringWriter.toString()); + + return result; + + } + +}*/ diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchableGroupsTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchableGroupsTest.java index 98442be..3aaf17a 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/SearchableGroupsTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/SearchableGroupsTest.java @@ -36,36 +36,38 @@ public class SearchableGroupsTest { + "\"search-paths\" : [\"cloud-infrastructure\", \"business\", \"network\"]" + "}," + "{" + "\"group-name\" : \"cloud-infrastructure\"," + "\"search-paths\" : [\"complexes\", \"cloud-regions\", \"pservers\"]" + "}" + "]" + "}"; - /* - * @Before public void init() throws NoSuchFieldException, SecurityException, - * IllegalArgumentException, IllegalAccessException { Field instance = - * SearchableGroups.class.getDeclaredField("instance"); instance.setAccessible(true); - * instance.set(null, null); } - * - * @Test public void test_FileNotFound() throws ElasticSearchOperationException { - * System.setProperty("AJSC_HOME", ""); SearchableGroups testGroups = - * SearchableGroups.getTestInstance(); assertTrue(testGroups.getGroups().isEmpty()); } - * - * @Test public void test_FileFoundWithProperlyFormatedConfig() throws - * ElasticSearchOperationException { ResolverUtils testUtils = Mockito.mock(ResolverUtils.class); - * Mockito.when(testUtils.getConfigSettings(anyString())).thenReturn(GOOD_TEST_CONFIG); - * SearchableGroups testGroups = SearchableGroups.getTestInstance(); - * - * testGroups.setUtils(testUtils); testGroups.initSearchableGroups(); - * - * assertFalse(testGroups.getGroups().isEmpty()); - * - * assertFalse(testGroups.getSearchableGroups("inventory").isEmpty()); } - * - * @Test public void test_FileFoundGroupDoesNotExist() throws ElasticSearchOperationException { - * ResolverUtils testUtils = Mockito.mock(ResolverUtils.class); - * Mockito.when(testUtils.getConfigSettings(anyString())).thenReturn(GOOD_TEST_CONFIG); - * SearchableGroups testGroups = SearchableGroups.getTestInstance(); - * - * testGroups.setUtils(testUtils); testGroups.initSearchableGroups(); - * - * assertFalse(testGroups.getGroups().isEmpty()); - * - * assertEquals(null, testGroups.getSearchableGroups("Test")); } - */ + /* + * @Before public void init() throws NoSuchFieldException, SecurityException, + * IllegalArgumentException, IllegalAccessException { Field instance = + * SearchableGroups.class.getDeclaredField("instance"); instance.setAccessible(true); + * instance.set(null, null); } + * + * @Test public void test_FileNotFound() throws ElasticSearchOperationException { + * System.setProperty("AJSC_HOME", ""); SearchableGroups testGroups = + * SearchableGroups.getTestInstance(); assertTrue(testGroups.getGroups().isEmpty()); } + * + * @Test public void test_FileFoundWithProperlyFormatedConfig() throws + * ElasticSearchOperationException { ResolverUtils testUtils = + * Mockito.mock(ResolverUtils.class); + * Mockito.when(testUtils.getConfigSettings(anyString())).thenReturn(GOOD_TEST_CONFIG); + * SearchableGroups testGroups = SearchableGroups.getTestInstance(); + * + * testGroups.setUtils(testUtils); testGroups.initSearchableGroups(); + * + * assertFalse(testGroups.getGroups().isEmpty()); + * + * assertFalse(testGroups.getSearchableGroups("inventory").isEmpty()); } + * + * @Test public void test_FileFoundGroupDoesNotExist() throws + * ElasticSearchOperationException { + * ResolverUtils testUtils = Mockito.mock(ResolverUtils.class); + * Mockito.when(testUtils.getConfigSettings(anyString())).thenReturn(GOOD_TEST_CONFIG); + * SearchableGroups testGroups = SearchableGroups.getTestInstance(); + * + * testGroups.setUtils(testUtils); testGroups.initSearchableGroups(); + * + * assertFalse(testGroups.getGroups().isEmpty()); + * + * assertEquals(null, testGroups.getSearchableGroups("Test")); } + */ } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/config/VisualizationConfigTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/config/VisualizationConfigTest.java index ea0c6f4..fb5e7a5 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/config/VisualizationConfigTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/config/VisualizationConfigTest.java @@ -1,81 +1,85 @@ package org.onap.aai.sparky.viewandinspect.config; -public class VisualizationConfigTest { -} +public class VisualizationConfigTest {} /* - * - * private VisualizationConfig visualConfig,visualNullConfig; - * - * @Before public void init() throws Exception { visualConfig = new VisualizationConfig(); - * - * } - * - * @Test public void successfullInitialization() { - * assertFalse(visualConfig.makeAllNeighborsBidirectional()); - * assertFalse(visualConfig.isAquariusEnabled()); - * assertFalse(visualConfig.isVisualizationDebugEnabled()); - * assertFalse(visualConfig.isExternalGraphServiceEnabled()); - * assertEquals(2,visualConfig.getMaxSelfLinkTraversalDepth()); - * assertEquals(3,visualConfig.getNumOfThreadsToFetchNodeIntegrity()); - * assertNotNull(visualConfig.getExternalGraphServiceAuthenticationMode()); - * assertNull(visualConfig.getAquariusEndpoint()); - * assertNotNull(visualConfig.getSelectedSearchedNodeClassName()); - * assertNotNull(visualConfig.getGeneralNodeClassName()); - * assertNotNull(visualConfig.getSearchNodeClassName()); - * assertNull(visualConfig.getAaiEntityNodeDescriptors()); - * assertNotNull(visualConfig.getEntityTypesToSummarize()); - * assertNotNull(visualConfig.getVnfEntityTypes()); - * assertNotNull(visualConfig.getExternalGraphServiceEndpoint()); - * assertNotNull(visualNullConfig.getConfig()); } - * - * @Test public void updateValues() { - * - * visualConfig.setMakeAllNeighborsBidirectional(true); - * assertTrue(visualConfig.makeAllNeighborsBidirectional()); - * - * visualConfig.setAquariusEnabled(true); assertTrue(visualConfig.isAquariusEnabled()); - * - * visualConfig.setVisualizationDebugEnabled(true); - * assertTrue(visualConfig.isVisualizationDebugEnabled()); - * - * visualConfig.setExternalGraphServiceEnabled(true); - * assertTrue(visualConfig.isExternalGraphServiceEnabled()); - * - * visualConfig.setMaxSelfLinkTraversalDepth(3); - * assertEquals(3,visualConfig.getMaxSelfLinkTraversalDepth()); - * - * visualConfig.setNumOfThreadsToFetchNodeIntegrity(2); - * assertEquals(2,visualConfig.getNumOfThreadsToFetchNodeIntegrity()); - * - * visualConfig.setExternalGraphServiceEndpoint("EndpointUnkown"); - * assertNotNull(visualConfig.getExternalGraphServiceAuthenticationMode()); - * - * visualConfig.setAquariusEndpoint("EndpointUnkown"); - * assertNotNull(visualConfig.getAquariusEndpoint()); - * - * visualConfig.setSelectedSearchedNodeClassName("ClassNameUnkown"); - * assertNotNull(visualConfig.getSelectedSearchedNodeClassName()); - * - * visualConfig.setGeneralNodeClassName("ClassNameUnknown"); - * assertNotNull(visualConfig.getGeneralNodeClassName()); - * - * visualConfig.setSearchNodeClassName("ClassNameUnknown"); - * assertNotNull(visualConfig.getSearchNodeClassName()); - * - * visualConfig.setAaiEntityNodeDescriptors("NotNull"); - * assertNotNull(visualConfig.getAaiEntityNodeDescriptors()); - * - * visualConfig.setEntityTypesToSummarize("complex,pserver,vserver,vnf"); - * assertNotNull(visualConfig.getEntityTypesToSummarize()); - * - * visualConfig.setVnfEntityTypes("generic-vnf,vce,vpe"); - * assertNotNull(visualConfig.getVnfEntityTypes()); - * - * visualConfig.setExternalGraphServiceAuthenticationMode(RestAuthenticationMode.SSL_BASIC); - * assertNotNull(visualConfig.getVnfEntityTypes()); - * - * - * } - * - * } - */ + + private VisualizationConfig visualConfig,visualNullConfig; + + @Before + public void init() throws Exception { + visualConfig = new VisualizationConfig(); + + } + + @Test + public void successfullInitialization() { + assertFalse(visualConfig.makeAllNeighborsBidirectional()); + assertFalse(visualConfig.isAquariusEnabled()); + assertFalse(visualConfig.isVisualizationDebugEnabled()); + assertFalse(visualConfig.isExternalGraphServiceEnabled()); + assertEquals(2,visualConfig.getMaxSelfLinkTraversalDepth()); + assertEquals(3,visualConfig.getNumOfThreadsToFetchNodeIntegrity()); + assertNotNull(visualConfig.getExternalGraphServiceAuthenticationMode()); + assertNull(visualConfig.getAquariusEndpoint()); + assertNotNull(visualConfig.getSelectedSearchedNodeClassName()); + assertNotNull(visualConfig.getGeneralNodeClassName()); + assertNotNull(visualConfig.getSearchNodeClassName()); + assertNull(visualConfig.getAaiEntityNodeDescriptors()); + assertNotNull(visualConfig.getEntityTypesToSummarize()); + assertNotNull(visualConfig.getVnfEntityTypes()); + assertNotNull(visualConfig.getExternalGraphServiceEndpoint()); + assertNotNull(visualNullConfig.getConfig()); + } + + @Test + public void updateValues() { + + visualConfig.setMakeAllNeighborsBidirectional(true); + assertTrue(visualConfig.makeAllNeighborsBidirectional()); + + visualConfig.setAquariusEnabled(true); + assertTrue(visualConfig.isAquariusEnabled()); + + visualConfig.setVisualizationDebugEnabled(true); + assertTrue(visualConfig.isVisualizationDebugEnabled()); + + visualConfig.setExternalGraphServiceEnabled(true); + assertTrue(visualConfig.isExternalGraphServiceEnabled()); + + visualConfig.setMaxSelfLinkTraversalDepth(3); + assertEquals(3,visualConfig.getMaxSelfLinkTraversalDepth()); + + visualConfig.setNumOfThreadsToFetchNodeIntegrity(2); + assertEquals(2,visualConfig.getNumOfThreadsToFetchNodeIntegrity()); + + visualConfig.setExternalGraphServiceEndpoint("EndpointUnkown"); + assertNotNull(visualConfig.getExternalGraphServiceAuthenticationMode()); + + visualConfig.setAquariusEndpoint("EndpointUnkown"); + assertNotNull(visualConfig.getAquariusEndpoint()); + + visualConfig.setSelectedSearchedNodeClassName("ClassNameUnkown"); + assertNotNull(visualConfig.getSelectedSearchedNodeClassName()); + + visualConfig.setGeneralNodeClassName("ClassNameUnknown"); + assertNotNull(visualConfig.getGeneralNodeClassName()); + + visualConfig.setSearchNodeClassName("ClassNameUnknown"); + assertNotNull(visualConfig.getSearchNodeClassName()); + + visualConfig.setAaiEntityNodeDescriptors("NotNull"); + assertNotNull(visualConfig.getAaiEntityNodeDescriptors()); + + visualConfig.setEntityTypesToSummarize("complex,pserver,vserver,vnf"); + assertNotNull(visualConfig.getEntityTypesToSummarize()); + + visualConfig.setVnfEntityTypes("generic-vnf,vce,vpe"); + assertNotNull(visualConfig.getVnfEntityTypes()); + + visualConfig.setExternalGraphServiceAuthenticationMode(RestAuthenticationMode.SSL_BASIC); + assertNotNull(visualConfig.getVnfEntityTypes()); + + + } + +}*/ diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/ActiveInventoryNodeTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/ActiveInventoryNodeTest.java index d9e25a6..18cb953 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/ActiveInventoryNodeTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/ActiveInventoryNodeTest.java @@ -25,77 +25,94 @@ package org.onap.aai.sparky.viewandinspect.entity; -public class ActiveInventoryNodeTest { -} +public class ActiveInventoryNodeTest {} /* - * private ActiveInventoryNode activeInventoryNode; private List<String> lst = new - * ArrayList<String>(); private OperationResult opResult; private VisualizationConfig visualConfig; - * private DataIntegrityEntity dataIntegrity; private NodeIntegrity nodeIntegrity; - * - * @Before public void init() throws Exception { activeInventoryNode = new - * ActiveInventoryNode("Key-1"); visualConfig = new VisualizationConfig(); dataIntegrity = new - * DataIntegrityEntity(); nodeIntegrity = new NodeIntegrity(); } - * - * @Test public void successfulInitializationAndUpdate() { - * - * activeInventoryNode.addQueryParam("query-1"); activeInventoryNode.clearQueryParams(); - * activeInventoryNode.addQueryParams(lst); assertNotNull(activeInventoryNode.getQueryParams()); - * assertNull(activeInventoryNode.getOxmModelLoader()); - * activeInventoryNode.setSelfLinkDeterminationPending(true); - * assertTrue(activeInventoryNode.isSelfLinkDeterminationPending()); - * assertNotNull(activeInventoryNode.getState()); - * assertNotNull(activeInventoryNode.getComplexGroups()); - * assertNotNull(activeInventoryNode.getRelationshipLists()); - * activeInventoryNode.setOpResult(opResult); assertNull(activeInventoryNode.getOpResult()); - * activeInventoryNode.setDataIntegrityEntity(dataIntegrity); - * assertNotNull(activeInventoryNode.getDataIntegrityEntity()); - * activeInventoryNode.setPrimaryKeyName("PrimaryKeyName"); - * assertNotNull(activeInventoryNode.getPrimaryKeyName()); activeInventoryNode.setNodeDepth(2); - * assertEquals(2,activeInventoryNode.getNodeDepth()); - * activeInventoryNode.setvisualizationConfig(visualConfig); - * assertNotNull(activeInventoryNode.getvisualizationConfig()); - * activeInventoryNode.setNodeValidated(true); assertTrue(activeInventoryNode.isNodeValidated()); - * activeInventoryNode.setPrimaryKeyValue("PrimaryKeyValue"); - * assertNotNull(activeInventoryNode.getPrimaryKeyValue()); - * activeInventoryNode.setIgnoredByFilter(true); - * assertTrue(activeInventoryNode.isIgnoredByFilter()); activeInventoryNode.setNodeIssue(true); - * assertTrue(activeInventoryNode.isNodeIssue()); activeInventoryNode.setProcessedNeighbors(true); - * assertTrue(activeInventoryNode.hasProcessedNeighbors()); - * activeInventoryNode.setResolvedSelfLink(true); - * assertTrue(activeInventoryNode.hasResolvedSelfLink()); - * activeInventoryNode.setItemIntegrity(nodeIntegrity); - * assertNotNull(activeInventoryNode.getItemIntegrity()); - * activeInventoryNode.addInboundNeighbor("InBoundNodeID"); - * activeInventoryNode.addOutboundNeighbor("OutBoundNodeID"); - * assertTrue(activeInventoryNode.hasNeighbors()); activeInventoryNode.addInboundNeighbor(null); - * activeInventoryNode.addOutboundNeighbor(null); - * assertNotNull(activeInventoryNode.getInboundNeighbors()); - * assertNotNull(activeInventoryNode.getOutboundNeighbors()); - * assertTrue(activeInventoryNode.isAtMaxDepth()); - * activeInventoryNode.setSelfLinkPendingResolve(true); - * assertTrue(activeInventoryNode.isSelfLinkPendingResolve()); - * activeInventoryNode.setRootNode(true); assertTrue(activeInventoryNode.isRootNode()); - * activeInventoryNode.setSelflinkRetrievalFailure(true); - * assertTrue(activeInventoryNode.isSelflinkRetrievalFailure()); - * activeInventoryNode.setSelfLinkProcessed(true); - * assertTrue(activeInventoryNode.getSelfLinkProcessed()); - * activeInventoryNode.setNodeIntegrityProcessed(true); - * assertTrue(activeInventoryNode.getNodeIntegrityProcessed()); - * assertFalse(activeInventoryNode.isDirectSelfLink("NoDirectLink")); - * activeInventoryNode.setProcessingErrorOccurred(true); - * assertTrue(activeInventoryNode.isProcessingErrorOccurred()); - * activeInventoryNode.setNodeId("NodeId-1"); assertNotNull(activeInventoryNode.getNodeId()); - * activeInventoryNode.setSelfLink("selfLinkSet"); assertNotNull(activeInventoryNode.getSelfLink()); - * activeInventoryNode.setEntityType("EntityId-1"); - * assertNotNull(activeInventoryNode.getEntityType()); - * assertNotNull(activeInventoryNode.dumpNodeTree(true)); - * assertNotNull(activeInventoryNode.getProcessingErrorCauses()); - * assertNull(activeInventoryNode.calculateEditAttributeUri("Invalid-link")); - * assertNull(activeInventoryNode.calculateEditAttributeUri("aai/v[\\d]/")); - * activeInventoryNode.processPathedSelfLinkResponse("jsonResp","startNodeType", - * "startNodeResourceKey"); - * activeInventoryNode.processPathedSelfLinkResponse(null,"startNodeType","startNodeResourceKey"); - * activeInventoryNode.processPathedSelfLinkResponse("","startNodeType","startNodeResourceKey"); - * - * } } - */ + private ActiveInventoryNode activeInventoryNode; + private List<String> lst = new ArrayList<String>(); + private OperationResult opResult; + private VisualizationConfig visualConfig; + private DataIntegrityEntity dataIntegrity; + private NodeIntegrity nodeIntegrity; + + @Before + public void init() throws Exception { + activeInventoryNode = new ActiveInventoryNode("Key-1"); + visualConfig = new VisualizationConfig(); + dataIntegrity = new DataIntegrityEntity(); + nodeIntegrity = new NodeIntegrity(); + } + + @Test + public void successfulInitializationAndUpdate() { + + activeInventoryNode.addQueryParam("query-1"); + activeInventoryNode.clearQueryParams(); + activeInventoryNode.addQueryParams(lst); + assertNotNull(activeInventoryNode.getQueryParams()); + assertNull(activeInventoryNode.getOxmModelLoader()); + activeInventoryNode.setSelfLinkDeterminationPending(true); + assertTrue(activeInventoryNode.isSelfLinkDeterminationPending()); + assertNotNull(activeInventoryNode.getState()); + assertNotNull(activeInventoryNode.getComplexGroups()); + assertNotNull(activeInventoryNode.getRelationshipLists()); + activeInventoryNode.setOpResult(opResult); + assertNull(activeInventoryNode.getOpResult()); + activeInventoryNode.setDataIntegrityEntity(dataIntegrity); + assertNotNull(activeInventoryNode.getDataIntegrityEntity()); + activeInventoryNode.setPrimaryKeyName("PrimaryKeyName"); + assertNotNull(activeInventoryNode.getPrimaryKeyName()); + activeInventoryNode.setNodeDepth(2); + assertEquals(2,activeInventoryNode.getNodeDepth()); + activeInventoryNode.setvisualizationConfig(visualConfig); + assertNotNull(activeInventoryNode.getvisualizationConfig()); + activeInventoryNode.setNodeValidated(true); + assertTrue(activeInventoryNode.isNodeValidated()); + activeInventoryNode.setPrimaryKeyValue("PrimaryKeyValue"); + assertNotNull(activeInventoryNode.getPrimaryKeyValue()); + activeInventoryNode.setIgnoredByFilter(true); + assertTrue(activeInventoryNode.isIgnoredByFilter()); + activeInventoryNode.setNodeIssue(true); + assertTrue(activeInventoryNode.isNodeIssue()); + activeInventoryNode.setProcessedNeighbors(true); + assertTrue(activeInventoryNode.hasProcessedNeighbors()); + activeInventoryNode.setResolvedSelfLink(true); + assertTrue(activeInventoryNode.hasResolvedSelfLink()); + activeInventoryNode.setItemIntegrity(nodeIntegrity); + assertNotNull(activeInventoryNode.getItemIntegrity()); + activeInventoryNode.addInboundNeighbor("InBoundNodeID"); + activeInventoryNode.addOutboundNeighbor("OutBoundNodeID"); + assertTrue(activeInventoryNode.hasNeighbors()); + activeInventoryNode.addInboundNeighbor(null); + activeInventoryNode.addOutboundNeighbor(null); + assertNotNull(activeInventoryNode.getInboundNeighbors()); + assertNotNull(activeInventoryNode.getOutboundNeighbors()); + assertTrue(activeInventoryNode.isAtMaxDepth()); + activeInventoryNode.setSelfLinkPendingResolve(true); + assertTrue(activeInventoryNode.isSelfLinkPendingResolve()); + activeInventoryNode.setRootNode(true); + assertTrue(activeInventoryNode.isRootNode()); + activeInventoryNode.setSelflinkRetrievalFailure(true); + assertTrue(activeInventoryNode.isSelflinkRetrievalFailure()); + activeInventoryNode.setSelfLinkProcessed(true); + assertTrue(activeInventoryNode.getSelfLinkProcessed()); + activeInventoryNode.setNodeIntegrityProcessed(true); + assertTrue(activeInventoryNode.getNodeIntegrityProcessed()); + assertFalse(activeInventoryNode.isDirectSelfLink("NoDirectLink")); + activeInventoryNode.setProcessingErrorOccurred(true); + assertTrue(activeInventoryNode.isProcessingErrorOccurred()); + activeInventoryNode.setNodeId("NodeId-1"); + assertNotNull(activeInventoryNode.getNodeId()); + activeInventoryNode.setSelfLink("selfLinkSet"); + assertNotNull(activeInventoryNode.getSelfLink()); + activeInventoryNode.setEntityType("EntityId-1"); + assertNotNull(activeInventoryNode.getEntityType()); + assertNotNull(activeInventoryNode.dumpNodeTree(true)); + assertNotNull(activeInventoryNode.getProcessingErrorCauses()); + assertNull(activeInventoryNode.calculateEditAttributeUri("Invalid-link")); + assertNull(activeInventoryNode.calculateEditAttributeUri("aai/v[\\d]/")); + activeInventoryNode.processPathedSelfLinkResponse("jsonResp","startNodeType","startNodeResourceKey"); + activeInventoryNode.processPathedSelfLinkResponse(null,"startNodeType","startNodeResourceKey"); + activeInventoryNode.processPathedSelfLinkResponse("","startNodeType","startNodeResourceKey"); + + } +}*/ diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/EntityEntryTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/EntityEntryTest.java index 8325a8b..9584d2b 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/EntityEntryTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/EntityEntryTest.java @@ -71,7 +71,7 @@ public class EntityEntryTest { assertEquals("ShinyEntityType", entityEntry.getEntityType()); assertEquals("primary_key_value", entityEntry.getEntityPrimaryKeyValue()); assertEquals("t1 t2 t3", entityEntry.getSearchTags()); - assertEquals("Id-1", entityEntry.getEntityId()); + assertEquals("Id-1",entityEntry.getEntityId()); assertNotNull(entityEntry.toString()); } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/GraphRequestTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/GraphRequestTest.java index 33d3ad8..e7ed344 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/GraphRequestTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/GraphRequestTest.java @@ -34,23 +34,23 @@ import org.onap.aai.sparky.viewandinspect.entity.GraphRequest; public class GraphRequestTest { - private GraphRequest graphRequest; - - @Before - public void init() throws Exception { - graphRequest = new GraphRequest(); - - } - - @Test - public void updateValues() { - - graphRequest.setHashId("HashID"); - assertNotNull(graphRequest.getHashId()); - graphRequest.setIncludeGraphMeta(true); - assertTrue(graphRequest.isIncludeGraphMeta()); - assertNotNull(graphRequest.toString()); - - } + private GraphRequest graphRequest; + + @Before + public void init() throws Exception { + graphRequest = new GraphRequest(); + + } + + @Test + public void updateValues() { + + graphRequest.setHashId("HashID"); + assertNotNull(graphRequest.getHashId()); + graphRequest.setIncludeGraphMeta(true); + assertTrue(graphRequest.isIncludeGraphMeta()); + assertNotNull(graphRequest.toString()); + + } } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/InlineMessageTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/InlineMessageTest.java index 849a58f..eebc821 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/InlineMessageTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/InlineMessageTest.java @@ -33,23 +33,23 @@ import org.onap.aai.sparky.viewandinspect.entity.InlineMessage; public class InlineMessageTest { - private InlineMessage inlineMsg; - - @Before - public void init() throws Exception { - inlineMsg = new InlineMessage("InlineMessage1", "InlineMessage2"); - - } - - @Test - public void successfulInitializationAndUpdate() { - - inlineMsg.setLevel("Level-1"); - assertNotNull(inlineMsg.getLevel()); - inlineMsg.setMessage("InlineMessage3"); - assertNotNull(inlineMsg.getMessage()); - assertNotNull(inlineMsg.toString()); - } - - + private InlineMessage inlineMsg; + + @Before + public void init() throws Exception { + inlineMsg = new InlineMessage("InlineMessage1","InlineMessage2"); + + } + + @Test + public void successfulInitializationAndUpdate() { + + inlineMsg.setLevel("Level-1"); + assertNotNull(inlineMsg.getLevel()); + inlineMsg.setMessage("InlineMessage3"); + assertNotNull(inlineMsg.getMessage()); + assertNotNull(inlineMsg.toString()); + } + + } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/NodeDebugTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/NodeDebugTest.java index ff273fa..b8450be 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/NodeDebugTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/NodeDebugTest.java @@ -34,24 +34,24 @@ import org.onap.aai.sparky.viewandinspect.entity.NodeDebug; public class NodeDebugTest { - - - private NodeDebug nodeDebug; - - @Before - public void init() throws Exception { - nodeDebug = new NodeDebug(); - - } - - @Test - public void updateValues() { - - nodeDebug.setProcessingErrorCauses("NullPointerException"); - assertNotNull(nodeDebug.getProcessingErrorCauses()); - nodeDebug.setProcessingError(true); - assertTrue(nodeDebug.isProcessingError()); - nodeDebug.setMaxTraversalDepthReached(true); - assertTrue(nodeDebug.isMaxTraversalDepthReached()); - } + + + private NodeDebug nodeDebug; + + @Before + public void init() throws Exception { + nodeDebug = new NodeDebug(); + + } + + @Test + public void updateValues() { + + nodeDebug.setProcessingErrorCauses("NullPointerException"); + assertNotNull(nodeDebug.getProcessingErrorCauses()); + nodeDebug.setProcessingError(true); + assertTrue(nodeDebug.isProcessingError()); + nodeDebug.setMaxTraversalDepthReached(true); + assertTrue(nodeDebug.isMaxTraversalDepthReached()); + } } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/NodeMetaTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/NodeMetaTest.java index f8b46e7..7ebe3c6 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/NodeMetaTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/NodeMetaTest.java @@ -36,52 +36,53 @@ import org.onap.aai.sparky.viewandinspect.enumeration.NodeProcessingState; public class NodeMetaTest { - private NodeMeta nodeMeta; - private NodeProcessingState nodeProcessingState; - private NodeDebug nodeDebug; - private VisualizationConfigs visualizationConfigs; + private NodeMeta nodeMeta; + private NodeProcessingState nodeProcessingState; + private NodeDebug nodeDebug; + private VisualizationConfigs visualizationConfigs; + + @Before + public void init() throws Exception { + this.visualizationConfigs = new VisualizationConfigs(); + nodeMeta = new NodeMeta(visualizationConfigs); + nodeDebug = new NodeDebug(); + + } + + @Test + public void updateValues() { + + nodeMeta.setAtMaxDepth(true); + assertTrue(nodeMeta.isAtMaxDepth()); + nodeMeta.setSelfLinkResolved(true); + assertTrue(nodeMeta.isSelfLinkResolved()); + nodeMeta.setProcessingState(nodeProcessingState.READY); + assertNotNull(nodeMeta.getProcessingState()); + nodeMeta.setProcessingErrorOccurred(true); + assertTrue(nodeMeta.isProcessingErrorOccurred()); + nodeMeta.setHasNeighbors(true); + assertTrue(nodeMeta.isHasNeighbors()); + nodeMeta.setNeighborsProcessed(true); + assertTrue(nodeMeta.isNeighborsProcessed()); + nodeMeta.setNodeDepth(3); + assertEquals(3,nodeMeta.getNodeDepth()); + nodeMeta.setNodeDebug(nodeDebug); + assertNotNull(nodeMeta.getNodeDebug()); + nodeMeta.setClassName("generalNodeClass"); + assertNotNull(nodeMeta.getClassName()); + nodeMeta.setNumInboundNeighbors(34); + assertEquals(34,nodeMeta.getNumInboundNeighbors()); + nodeMeta.setNumOutboundNeighbors(43); + assertEquals(43,nodeMeta.getNumOutboundNeighbors()); + nodeMeta.setSelfLinkResponseTimeInMs(43); + assertEquals(43,nodeMeta.getSelfLinkResponseTimeInMs()); + nodeMeta.setNodeIssue(true); + assertTrue(nodeMeta.isNodeIssue()); + nodeMeta.setNodeValidated(true); + assertTrue(nodeMeta.isNodeValidated()); + nodeMeta.setSearchTarget(true); + assertTrue(nodeMeta.isSearchTarget()); + - @Before - public void init() throws Exception { - nodeMeta = new NodeMeta(new VisualizationConfigs()); - nodeDebug = new NodeDebug(); - - } - - @Test - public void updateValues() { - - nodeMeta.setAtMaxDepth(true); - assertTrue(nodeMeta.isAtMaxDepth()); - nodeMeta.setSelfLinkResolved(true); - assertTrue(nodeMeta.isSelfLinkResolved()); - nodeMeta.setProcessingState(nodeProcessingState.READY); - assertNotNull(nodeMeta.getProcessingState()); - nodeMeta.setProcessingErrorOccurred(true); - assertTrue(nodeMeta.isProcessingErrorOccurred()); - nodeMeta.setHasNeighbors(true); - assertTrue(nodeMeta.isHasNeighbors()); - nodeMeta.setNeighborsProcessed(true); - assertTrue(nodeMeta.isNeighborsProcessed()); - nodeMeta.setNodeDepth(3); - assertEquals(3, nodeMeta.getNodeDepth()); - nodeMeta.setNodeDebug(nodeDebug); - assertNotNull(nodeMeta.getNodeDebug()); - nodeMeta.setClassName("generalNodeClass"); - assertNotNull(nodeMeta.getClassName()); - nodeMeta.setNumInboundNeighbors(34); - assertEquals(34, nodeMeta.getNumInboundNeighbors()); - nodeMeta.setNumOutboundNeighbors(43); - assertEquals(43, nodeMeta.getNumOutboundNeighbors()); - nodeMeta.setSelfLinkResponseTimeInMs(43); - assertEquals(43, nodeMeta.getSelfLinkResponseTimeInMs()); - nodeMeta.setNodeIssue(true); - assertTrue(nodeMeta.isNodeIssue()); - nodeMeta.setNodeValidated(true); - assertTrue(nodeMeta.isNodeValidated()); - nodeMeta.setSearchTarget(true); - assertTrue(nodeMeta.isSearchTarget()); - - - } + } } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/QueryParamsTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/QueryParamsTest.java index e886720..d1bd60b 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/QueryParamsTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/QueryParamsTest.java @@ -34,23 +34,23 @@ import org.onap.aai.sparky.viewandinspect.entity.QueryParams; public class QueryParamsTest { - private QueryParams parameterQuery; - - @Before - public void init() throws Exception { - parameterQuery = new QueryParams(); - - } - - @Test - public void updateValues() { - - parameterQuery.setSearchTargetPrimaryKeyValues("Internet Network"); - assertNotNull(parameterQuery.getSearchTargetPrimaryKeyValues()); - parameterQuery.setSearchTargetNodeId("Internet Network"); - assertNotNull(parameterQuery.getSearchTargetNodeId()); - } - - - + private QueryParams parameterQuery; + + @Before + public void init() throws Exception { + parameterQuery = new QueryParams(); + + } + + @Test + public void updateValues() { + + parameterQuery.setSearchTargetPrimaryKeyValues("Internet Network"); + assertNotNull(parameterQuery.getSearchTargetPrimaryKeyValues()); + parameterQuery.setSearchTargetNodeId("Internet Network"); + assertNotNull(parameterQuery.getSearchTargetNodeId()); + } + + + } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/QueryRequestTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/QueryRequestTest.java index c578d55..fca4051 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/QueryRequestTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/QueryRequestTest.java @@ -32,23 +32,23 @@ import org.junit.Test; import org.onap.aai.sparky.viewandinspect.entity.QueryRequest; public class QueryRequestTest { - - private QueryRequest requestQuery; - - @Before - public void init() throws Exception { - requestQuery = new QueryRequest(); - - } - - @Test - public void updateValues() { - - requestQuery.setHashId("claymore-service-tree"); - assertNotNull(requestQuery.getHashId()); - assertNotNull(requestQuery.toString()); - requestQuery.setHashId(null); - assertNotNull(requestQuery.toString()); - } + + private QueryRequest requestQuery; + + @Before + public void init() throws Exception { + requestQuery = new QueryRequest(); + + } + + @Test + public void updateValues() { + + requestQuery.setHashId("claymore-service-tree"); + assertNotNull(requestQuery.getHashId()); + assertNotNull(requestQuery.toString()); + requestQuery.setHashId(null); + assertNotNull(requestQuery.toString()); + } } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/RelatedToPropertyTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/RelatedToPropertyTest.java index 2db40a5..48a724b 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/RelatedToPropertyTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/RelatedToPropertyTest.java @@ -33,22 +33,22 @@ import org.onap.aai.sparky.viewandinspect.entity.RelatedToProperty; public class RelatedToPropertyTest { - private RelatedToProperty relatedToProperty; - - @Before - public void init() throws Exception { - relatedToProperty = new RelatedToProperty(); - - } - - @Test - public void successfulInitializationAndUpdate() { - - relatedToProperty.setPropertyKey("PropertyKey-1"); - assertNotNull(relatedToProperty.getPropertyKey()); - relatedToProperty.setPropertyValue("PropertyValue-1"); - assertNotNull(relatedToProperty.getPropertyValue()); - assertNotNull(relatedToProperty.toString()); - } - + private RelatedToProperty relatedToProperty; + + @Before + public void init() throws Exception { + relatedToProperty = new RelatedToProperty(); + + } + + @Test + public void successfulInitializationAndUpdate() { + + relatedToProperty.setPropertyKey("PropertyKey-1"); + assertNotNull(relatedToProperty.getPropertyKey()); + relatedToProperty.setPropertyValue("PropertyValue-1"); + assertNotNull(relatedToProperty.getPropertyValue()); + assertNotNull(relatedToProperty.toString()); + } + } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipDataTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipDataTest.java index ad80a05..e20e720 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipDataTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/RelationshipDataTest.java @@ -34,21 +34,21 @@ import org.onap.aai.sparky.viewandinspect.entity.RelationshipData; public class RelationshipDataTest { - private RelationshipData relationshipData; - - @Before - public void init() throws Exception { - relationshipData = new RelationshipData(); - - } - - @Test - public void updateValues() { - - relationshipData.setRelationshipKey("RelationshipKey"); - assertNotNull(relationshipData.getRelationshipKey()); - relationshipData.setRelationshipValue("RelationshipValues"); - assertNotNull(relationshipData.getRelationshipValue()); - assertNotNull(relationshipData.toString()); - } + private RelationshipData relationshipData; + + @Before + public void init() throws Exception { + relationshipData = new RelationshipData(); + + } + + @Test + public void updateValues() { + + relationshipData.setRelationshipKey("RelationshipKey"); + assertNotNull(relationshipData.getRelationshipKey()); + relationshipData.setRelationshipValue("RelationshipValues"); + assertNotNull(relationshipData.getRelationshipValue()); + assertNotNull(relationshipData.toString()); + } } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/SearchResponseTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/SearchResponseTest.java index 6eac2bb..6c08c8c 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/SearchResponseTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/SearchResponseTest.java @@ -33,20 +33,20 @@ import org.onap.aai.sparky.search.SearchResponse; public class SearchResponseTest { - private SearchResponse searchResponse; - - @Before - public void init() throws Exception { - searchResponse = new SearchResponse(); - - } - - @Test - public void updateValues() { - - assertNotNull(searchResponse.toString()); - searchResponse.setSuggestions(null); - assertNotNull(searchResponse.toString()); - - } + private SearchResponse searchResponse; + + @Before + public void init() throws Exception { + searchResponse = new SearchResponse(); + + } + + @Test + public void updateValues() { + + assertNotNull(searchResponse.toString()); + searchResponse.setSuggestions(null); + assertNotNull(searchResponse.toString()); + + } } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/SelfLinkDeterminationTransactionTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/SelfLinkDeterminationTransactionTest.java index 9b1487e..8dd862a 100644 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/SelfLinkDeterminationTransactionTest.java +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/SelfLinkDeterminationTransactionTest.java @@ -30,38 +30,39 @@ import static org.junit.Assert.assertNotNull; import org.junit.Before; import org.junit.Test; import org.onap.aai.restclient.client.OperationResult; +import org.onap.aai.sparky.config.oxm.OxmEntityLookup; import org.onap.aai.sparky.viewandinspect.config.VisualizationConfigs; -import org.onap.aai.sparky.viewandinspect.entity.ActiveInventoryNode; -import org.onap.aai.sparky.viewandinspect.entity.SelfLinkDeterminationTransaction; public class SelfLinkDeterminationTransactionTest { - private SelfLinkDeterminationTransaction selfLinkDeterminationTransaction; - private OperationResult opResult; - private ActiveInventoryNode activeInventoryNode; - private VisualizationConfigs visualizationConfigs; - - @Before - public void init() throws Exception { - selfLinkDeterminationTransaction = new SelfLinkDeterminationTransaction(); - opResult = new OperationResult(); - activeInventoryNode = new ActiveInventoryNode(visualizationConfigs); - - } - - @Test - public void updateValues() { - - selfLinkDeterminationTransaction.setParentNodeId("ID-1"); - assertNotNull(selfLinkDeterminationTransaction.getParentNodeId()); - selfLinkDeterminationTransaction.setOpResult(opResult); - assertNotNull(selfLinkDeterminationTransaction.getOpResult()); - selfLinkDeterminationTransaction.setQueryString("QueryString"); - assertNotNull(selfLinkDeterminationTransaction.getQueryString()); - selfLinkDeterminationTransaction.setEntityUrl("EntityURL"); - assertNotNull(selfLinkDeterminationTransaction.getEntityUrl()); - selfLinkDeterminationTransaction.setNewNode(activeInventoryNode); - assertNotNull(selfLinkDeterminationTransaction.getNewNode()); - } + private SelfLinkDeterminationTransaction selfLinkDeterminationTransaction; + private OperationResult opResult; + private ActiveInventoryNode activeInventoryNode; + private VisualizationConfigs visualizationConfigs; + private OxmEntityLookup oxmEntityLookup; + + @Before + public void init() throws Exception { + selfLinkDeterminationTransaction = new SelfLinkDeterminationTransaction(); + opResult = new OperationResult(); + oxmEntityLookup = new OxmEntityLookup(); + activeInventoryNode = new ActiveInventoryNode(visualizationConfigs, oxmEntityLookup); + + } + + @Test + public void updateValues() { + + selfLinkDeterminationTransaction.setParentNodeId("ID-1"); + assertNotNull(selfLinkDeterminationTransaction.getParentNodeId()); + selfLinkDeterminationTransaction.setOpResult(opResult); + assertNotNull(selfLinkDeterminationTransaction.getOpResult()); + selfLinkDeterminationTransaction.setQueryString("QueryString"); + assertNotNull(selfLinkDeterminationTransaction.getQueryString()); + selfLinkDeterminationTransaction.setEntityUrl("EntityURL"); + assertNotNull(selfLinkDeterminationTransaction.getEntityUrl()); + selfLinkDeterminationTransaction.setNewNode(activeInventoryNode); + assertNotNull(selfLinkDeterminationTransaction.getNewNode()); + } } diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/entity/SparkyGraphLinkTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/SparkyGraphLinkTest.java new file mode 100644 index 0000000..20d6825 --- /dev/null +++ b/src/test/java/org/onap/aai/sparky/viewandinspect/entity/SparkyGraphLinkTest.java @@ -0,0 +1,56 @@ +/** + * ============LICENSE_START=================================================== + * SPARKY (AAI UI service) + * ============================================================================ + * Copyright © 2017 AT&T Intellectual Property. + * Copyright © 2017 Amdocs + * All rights reserved. + * ============================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END===================================================== + * + * ECOMP and OpenECOMP are trademarks + * and service marks of AT&T Intellectual Property. + */ + +package org.onap.aai.sparky.viewandinspect.entity; + +import static org.junit.Assert.assertNotNull; + +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.sparky.viewandinspect.entity.SparkyGraphLink; + +public class SparkyGraphLinkTest { + + private SparkyGraphLink jsonNodeLink; + + @Before + public void init() throws Exception { + jsonNodeLink = new SparkyGraphLink(); + + } + + @Test + public void updateValues() { + + jsonNodeLink.setId("ID-1"); + assertNotNull(jsonNodeLink.getId()); + jsonNodeLink.setSource("SourceSet"); + assertNotNull(jsonNodeLink.getSource()); + jsonNodeLink.setTarget("targetSet"); + assertNotNull(jsonNodeLink.getTarget()); + assertNotNull(jsonNodeLink.toString()); + } + +} diff --git a/src/test/java/org/onap/aai/sparky/viewandinspect/task/PerformNodeSelfLinkProcessingTaskTest.java b/src/test/java/org/onap/aai/sparky/viewandinspect/task/PerformNodeSelfLinkProcessingTaskTest.java deleted file mode 100644 index c46161f..0000000 --- a/src/test/java/org/onap/aai/sparky/viewandinspect/task/PerformNodeSelfLinkProcessingTaskTest.java +++ /dev/null @@ -1,232 +0,0 @@ -/** - * ============LICENSE_START=================================================== - * SPARKY (AAI UI service) - * ============================================================================ - * Copyright © 2017 AT&T Intellectual Property. - * Copyright © 2017 Amdocs - * All rights reserved. - * ============================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END===================================================== - * - * ECOMP and OpenECOMP are trademarks - * and service marks of AT&T Intellectual Property. - */ - -package org.onap.aai.sparky.viewandinspect.task; - -import java.util.Properties; - -import org.junit.Before; -import org.junit.Test; -import org.mockito.Mockito; -import org.onap.aai.cl.mdc.MdcContext; -import org.onap.aai.sparky.dal.aai.ActiveInventoryDataProvider; -import org.onap.aai.sparky.dal.aai.config.ActiveInventoryConfig; -import org.onap.aai.sparky.util.NodeUtils; -import org.onap.aai.sparky.viewandinspect.entity.ActiveInventoryNode; -import org.onap.aai.sparky.viewandinspect.entity.NodeProcessingTransaction; -import org.onap.aai.sparky.viewandinspect.task.PerformNodeSelfLinkProcessingTask; - - -public class PerformNodeSelfLinkProcessingTaskTest { - - private NodeProcessingTransaction mockTransaction; - private ActiveInventoryDataProvider mockAaiProvider; - private ActiveInventoryNode mockActiveInventoryNode; - private ActiveInventoryConfig aaiConfig; - PerformNodeSelfLinkProcessingTask testTask; - - private Properties getTestProperties() { - - Properties props = new Properties(); - - props.put("aai.rest.host", "aai-host"); - props.put("aai.rest.port", "8443"); - props.put("aai.rest.resourceBasePath", "/aai/v10"); - props.put("aai.rest.connectTimeoutInMs", "30000"); - props.put("aai.rest.readTimeoutInMs", "60000"); - props.put("aai.rest.numRequestRetries", "5"); - props.put("aai.rest.numResolverWorkers", "15"); - - props.put("aai.rest.cache.enabled", "false"); - props.put("aai.rest.cache.numWorkers", "10"); - props.put("aai.rest.cache.cacheFailures", "false"); - props.put("aai.rest.cache.useCacheOnly", "false"); - props.put("aai.rest.cache.storageFolderOverride", ""); - props.put("aai.rest.cache.maxTimeToLiveInMs", "-1"); - - props.put("aai.rest.shallowEntities", "cloud-region,complex,vnf-image,att-aic,image"); - - props.put("aai.ssl.truststore.filename", "synchronizer.jks"); - props.put("aai.ssl.truststore.type", "jks"); - - props.put("aai.ssl.keystore.filename", "aai-client-cert.p12"); - props.put("aai.ssl.keystore.pass", "70c87528c88dcd9f9c2558d30e817868"); - props.put("aai.ssl.keystore.type", "pkcs12"); - - props.put("aai.ssl.enableDebug", "false"); - props.put("aai.ssl.validateServerHostName", "false"); - props.put("aai.ssl.validateServerCertificateChain", "false"); - - props.put("aai.rest.authenticationMode", "SSL_CERT"); - props.put("aai.ssl.basicAuth.username", ""); - props.put("aai.ssl.basicAuth.password", ""); - - props.put("aai.taskProcessor.maxConcurrentWorkers", "5"); - - props.put("aai.taskProcessor.transactionRateControllerEnabled", "false"); - props.put("aai.taskProcessor.numSamplesPerThreadForRunningAverage", "100"); - props.put("aai.taskProcessor.targetTPS", "100"); - - props.put("aai.taskProcessor.bytesHistogramLabel", "[Response Size In Bytes]"); - props.put("aai.taskProcessor.bytesHistogramMaxYAxis", "1000000"); - props.put("aai.taskProcessor.bytesHistogramNumBins", "20"); - props.put("aai.taskProcessor.bytesHistogramNumDecimalPoints", "2"); - - props.put("aai.taskProcessor.queueLengthHistogramLabel", "[Queue Item Length]"); - props.put("aai.taskProcessor.queueLengthHistogramMaxYAxis", "20000"); - props.put("aai.taskProcessor.queueLengthHistogramNumBins", "20"); - props.put("aai.taskProcessor.queueLengthHistogramNumDecimalPoints", "2"); - - props.put("aai.taskProcessor.taskAgeHistogramLabel", "[Task Age In Ms]"); - props.put("aai.taskProcessor.taskAgeHistogramMaxYAxis", "600000"); - props.put("aai.taskProcessor.taskAgeHistogramNumBins", "20"); - props.put("aai.taskProcessor.taskAgeHistogramNumDecimalPoints", "2"); - - props.put("aai.taskProcessor.responseTimeHistogramLabel", "[Response Time In Ms]"); - props.put("aai.taskProcessor.responseTimeHistogramMaxYAxis", "10000"); - props.put("aai.taskProcessor.responseTimeHistogramNumBins", "20"); - props.put("aai.taskProcessor.responseTimeHistogramNumDecimalPoints", "2"); - - props.put("aai.taskProcessor.tpsHistogramLabel", "[Transactions Per Second]"); - props.put("aai.taskProcessor.tpsHistogramMaxYAxis", "100"); - props.put("aai.taskProcessor.tpsHistogramNumBins", "20"); - props.put("aai.taskProcessor.tpsHistogramNumDecimalPoints", "2"); - - - return props; - - } - - @Before - public void init() throws Exception { - - mockTransaction = Mockito.mock(NodeProcessingTransaction.class); - mockAaiProvider = Mockito.mock(ActiveInventoryDataProvider.class); - mockActiveInventoryNode = Mockito.mock(ActiveInventoryNode.class); - - String txnID = NodeUtils.getRandomTxnId(); - String partnerName = "Browser"; - - MdcContext.initialize(txnID, "AAI-UI", "", partnerName, "localhost"); - - aaiConfig = new ActiveInventoryConfig(getTestProperties()); - - } - - - @Test - public void validateDefaultConstructor() { - - /* - * ArgumentCaptor<String> linkCaptor = ArgumentCaptor.forClass(String.class); - * - * Mockito.when( mockActiveInventoryNode.getEntityType()).thenReturn("logical-link"); - * Mockito.when( mockTransaction.getProcessingNode() ).thenReturn(mockActiveInventoryNode); - * Mockito.when( mockTransaction.getRequestParameters()).thenReturn("?p1=v1&p2=v2&p3=v3"); - * Mockito.when( mockTransaction.getSelfLink()).thenReturn( - * "/aai/v10/network/logical-links/logical-link/alrga392ve2%20-%20xe-%2010%2F3%2F2.270%7Car4ga01pbg" - * ); - * - * String requestParameters = ""; - * - * // test method testTask.get(); - * - * assertEquals( - * "https://aai-host:8443/aai/v10/network/logical-links/logical-link/alrga392ve2%20-%20xe-%2010%2F3%2F2.270%7Car4ga01pbg?p1=v1&p2=v2&p3=v3", - * linkCaptor.getValue()); - */ - - } - - @Test - public void validateLinkEncoding_withoutParameters() { - - /* - * ArgumentCaptor<String> linkCaptor = ArgumentCaptor.forClass(String.class); - * - * Mockito.when( mockActiveInventoryNode.getEntityType()).thenReturn("logical-link"); - * Mockito.when( mockTransaction.getProcessingNode() ).thenReturn(mockActiveInventoryNode); - * Mockito.when( mockTransaction.getSelfLink()).thenReturn( - * "/aai/v10/network/logical-links/logical-link/alrga392ve2%20-%20xe-%2010%2F3%2F2.270%7Car4ga01pbg" - * ); - * - * String requestParameters = ""; - * - * // test method testTask.get(); - * - * assertEquals( - * "https://aai-host:8443/aai/v10/network/logical-links/logical-link/alrga392ve2%20-%20xe-%2010%2F3%2F2.270%7Car4ga01pbg", - * linkCaptor.getValue()); - */ - - } - - @Test - public void validateLinkEncoding_nullLink() { - - /* - * ArgumentCaptor<OperationResult> opResultCaptor = - * ArgumentCaptor.forClass(OperationResult.class); - * - * Mockito.when( mockActiveInventoryNode.getEntityType()).thenReturn("logical-link"); - * Mockito.when( mockTransaction.getProcessingNode() ).thenReturn(mockActiveInventoryNode); - * Mockito.when( mockTransaction.getSelfLink()).thenReturn(null); - * - * String requestParameters = ""; - * - * // test method testTask.get(); - * - * Mockito.verify(mockTransaction, Mockito.atLeast(1)).setOpResult(opResultCaptor.capture()); - * - * assertNotNull(opResultCaptor.getValue()); assertEquals(500, - * opResultCaptor.getValue().getResultCode()); - */ - - } - - @Test - public void validateLinkEncoding_withoutParameters_and_providerSuccess() { - - /* - * ArgumentCaptor<String> linkCaptor = ArgumentCaptor.forClass(String.class); - * - * Mockito.when( mockActiveInventoryNode.getEntityType()).thenReturn("logical-link"); - * Mockito.when( mockTransaction.getProcessingNode() ).thenReturn(mockActiveInventoryNode); - * Mockito.when( mockTransaction.getSelfLink()).thenReturn( - * "/aai/v10/network/logical-links/logical-link/alrga392ve2%20-%20xe-%2010%2F3%2F2.270%7Car4ga01pbg" - * ); Mockito.when( mockAaiProvider.queryActiveInventoryWithRetries(anyString(), anyString(), - * anyInt())).thenReturn(new OperationResult(200,"OK")); - * - * String requestParameters = ""; - * - * // test method testTask.get(); - * - * assertEquals( - * "https://aai-host:8443/aai/v10/network/logical-links/logical-link/alrga392ve2%20-%20xe-%2010%2F3%2F2.270%7Car4ga01pbg", - * linkCaptor.getValue()); - */ - } - -} |