diff options
Diffstat (limited to 'src/test/java/org')
55 files changed, 8819 insertions, 0 deletions
diff --git a/src/test/java/org/openecomp/sparky/analytics/AveragingRingBufferTest.java b/src/test/java/org/openecomp/sparky/analytics/AveragingRingBufferTest.java new file mode 100644 index 0000000..d8a558c --- /dev/null +++ b/src/test/java/org/openecomp/sparky/analytics/AveragingRingBufferTest.java @@ -0,0 +1,133 @@ +/* +* ============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.openecomp.sparky.analytics; + +import static org.junit.Assert.assertEquals; + +import java.security.SecureRandom; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.modules.junit4.PowerMockRunner; + +/** + * The Class AveragingRingBufferTest. + */ +@RunWith(PowerMockRunner.class) +public class AveragingRingBufferTest { + + protected SecureRandom random = new SecureRandom(); + + /** + * Inits the. + * + * @throws Exception the exception + */ + @Before + public void init() throws Exception { + // nothing at the moment + } + + /** + * Validate pre index roll averaging. + */ + @Test + public void validatePreIndexRollAveraging() { + + AveragingRingBuffer arb = new AveragingRingBuffer(5); + assertEquals(0, arb.getAvg()); + + /* + * On initial buffer fill, the average will be re-calculated on the fly for the first nth data + * points until the data buffer has been filled the first time, and then the buffer + * automatically recalculates the average every time the buffer index rolls over, to the keep + * the average relative to the last "nth" data points. + */ + + // [ 1, 0, 0, 0, 0 ], sum = 1, avg = 1/1 =1 + arb.addSample(1); + assertEquals(1, arb.getAvg()); + + // [ 1, 2, 0, 0, 0 ], sum = 3, avg = 3/2 = 1 + arb.addSample(2); + assertEquals(1, arb.getAvg()); + + // [ 1, 2, 3, 0, 0 ], sum = 6, avg = 6/3 = 2 + arb.addSample(3); + assertEquals(2, arb.getAvg()); + + // [ 1, 2, 3, 4, 0 ], sum = 10, avg = 10/4 = 2 + arb.addSample(4); + assertEquals(2, arb.getAvg()); + + // [ 1, 2, 3, 4, 5 ], sum = 15, avg = 15/5 = 3 + arb.addSample(5); + assertEquals(3, arb.getAvg()); + + } + + /** + * Validate post index roll averaging. + */ + @Test + public void validatePostIndexRollAveraging() { + + AveragingRingBuffer arb = new AveragingRingBuffer(5); + arb.addSample(1); + arb.addSample(2); + arb.addSample(3); + arb.addSample(4); + arb.addSample(5); + + /* + * The behavior switches, and now doesn't re-calculate the average until each nth data point, to + * reduce the computational over-head of re-calculating on each value. + */ + + // [ 10, 2, 3, 4, 5 ], + arb.addSample(10); + assertEquals(3, arb.getAvg()); + + // [ 10, 20, 3, 4, 5 ], + arb.addSample(20); + assertEquals(3, arb.getAvg()); + + // [ 10, 20, 30, 4, 5 ], + arb.addSample(30); + assertEquals(3, arb.getAvg()); + + // [ 10, 20, 30, 40, 5 ], + arb.addSample(40); + assertEquals(3, arb.getAvg()); + + // [ 10, 20, 30, 40, 50 ], s=150, avg=150/5=30 + arb.addSample(50); + assertEquals(30, arb.getAvg()); + + } + +} diff --git a/src/test/java/org/openecomp/sparky/analytics/HistogramSamplerTest.java b/src/test/java/org/openecomp/sparky/analytics/HistogramSamplerTest.java new file mode 100644 index 0000000..70e9e3c --- /dev/null +++ b/src/test/java/org/openecomp/sparky/analytics/HistogramSamplerTest.java @@ -0,0 +1,90 @@ +/* +* ============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.openecomp.sparky.analytics; + +import java.security.SecureRandom; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.modules.junit4.PowerMockRunner; + +/** + * The Class HistogramSamplerTest. + */ +@RunWith(PowerMockRunner.class) +public class HistogramSamplerTest { + + protected SecureRandom random = new SecureRandom(); + + /** + * Inits the. + * + * @throws Exception the exception + */ + @Before + public void init() throws Exception { + // nothing at the moment + } + + /** + * Validate basic construction and delimited reporting. + */ + @Test + public void validateBasicConstructionAndDelimitedReporting() { + + HistogramSampler histoSampler = new HistogramSampler("[File byte size]", 500000, 22, 3); + + SecureRandom random = new SecureRandom(); + + for (int x = 0; x < 100000; x++) { + histoSampler.track(random.nextInt(9999999)); + } + + System.out.println(histoSampler.getStats(false, " ")); + + } + + + /** + * Validate basic construction and formatted reporting. + */ + @Test + public void validateBasicConstructionAndFormattedReporting() { + + HistogramSampler histoSampler = new HistogramSampler("[Queue Length Samples]", 100000, 15, 3); + + SecureRandom random = new SecureRandom(); + + for (int x = 0; x < 100000; x++) { + histoSampler.track(random.nextInt(9999999)); + } + + System.out.println(histoSampler.getStats(true, " ")); + + } + +} diff --git a/src/test/java/org/openecomp/sparky/analytics/TransactionRateControllerTest.java b/src/test/java/org/openecomp/sparky/analytics/TransactionRateControllerTest.java new file mode 100644 index 0000000..c5f14e6 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/analytics/TransactionRateControllerTest.java @@ -0,0 +1,217 @@ +/* +* ============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.openecomp.sparky.analytics; + +import org.junit.Before; + + +/** + * The Class TransactionRateControllerTest. + */ +public class TransactionRateControllerTest { + + /** + * Inits the. + * + * @throws Exception the exception + */ + @Before + public void init() throws Exception { + // nothing at the moment + } + /* + * @Test public void tenTPS_oneThread_validateRateEnforcementWhenAvgResposneTimeIsUnderBudget() { + * + * TransactionRateController trc = new TransactionRateController(10.0, 1, 5); + * + * trc.trackResponseTime(25); trc.trackResponseTime(35); trc.trackResponseTime(45); + * trc.trackResponseTime(55); trc.trackResponseTime(70); + * + * // avg should be 46 ms + * + * assertEquals(54, trc.getFixedDelayInMs()); + * + * } + * + * @Test public void tenTPS_oneThread_validateRateEnforcementWhenAvgResposneTimeIsOverBudget() { + * + * TransactionRateController trc = new TransactionRateController(10.0, 1, 5); + * + * trc.trackResponseTime(75); trc.trackResponseTime(125); trc.trackResponseTime(250); + * trc.trackResponseTime(105); trc.trackResponseTime(23); + * + * // avg should be 115 ms + * + * assertEquals(0, trc.getFixedDelayInMs()); + * + * } + * + * @Test public void oneTPS_oneThread_validateRateEnforcementWhenAvgResposneTimeIsUnderBudget() { + * + * TransactionRateController trc = new TransactionRateController(1.0, 1, 5); + * + * trc.trackResponseTime(25); trc.trackResponseTime(35); trc.trackResponseTime(45); + * trc.trackResponseTime(55); trc.trackResponseTime(70); + * + * // avg should be 46 ms + * + * assertEquals(954, trc.getFixedDelayInMs()); + * + * } + * + * @Test public void oneTPS_oneThread_validateRateEnforcementWhenAvgResposneTimeIsOverBudget() { + * + * TransactionRateController trc = new TransactionRateController(1.0, 1, 5); + * + * trc.trackResponseTime(75); trc.trackResponseTime(125); trc.trackResponseTime(250); + * trc.trackResponseTime(105); trc.trackResponseTime(23); + * + * // avg should be 115 ms + * + * assertEquals(885, trc.getFixedDelayInMs()); + * + * } + * + * @Test public void halfTPS_oneThread_validateRateEnforcementWhenAvgResposneTimeIsUnderBudget() { + * + * TransactionRateController trc = new TransactionRateController(0.5, 1, 5); + * + * trc.trackResponseTime(25); trc.trackResponseTime(35); trc.trackResponseTime(45); + * trc.trackResponseTime(55); trc.trackResponseTime(70); + * + * // avg should be 46 ms + * + * assertEquals(1954, trc.getFixedDelayInMs()); + * + * } + * + * @Test public void halfTPS_oneThread_validateRateEnforcementWhenAvgResposneTimeIsOverBudget() { + * + * TransactionRateController trc = new TransactionRateController(0.5, 1, 5); + * + * trc.trackResponseTime(75); trc.trackResponseTime(125); trc.trackResponseTime(250); + * trc.trackResponseTime(105); trc.trackResponseTime(23); + * + * // avg should be 115 ms + * + * assertEquals(1885, trc.getFixedDelayInMs()); + * + * } + * + * @Test public void tenTPS_tenThreads_validateRateEnforcementWhenAvgResposneTimeIsUnderBudget() { + * + * TransactionRateController trc = new TransactionRateController(10.0, 10, 5); + * + * trc.trackResponseTime(25); trc.trackResponseTime(35); trc.trackResponseTime(45); + * trc.trackResponseTime(55); trc.trackResponseTime(70); + * + * // avg should be 46 ms + * + * assertEquals(540, trc.getFixedDelayInMs()); + * + * } + * + * @Test public void tenTPS_tenThreads_validateRateEnforcementWhenAvgResposneTimeIsOverBudget() { + * + * TransactionRateController trc = new TransactionRateController(10.0, 10, 5); + * + * trc.trackResponseTime(75); trc.trackResponseTime(125); trc.trackResponseTime(250); + * trc.trackResponseTime(105); trc.trackResponseTime(23); + * + * // avg should be 115 ms + * + * assertEquals(0, trc.getFixedDelayInMs()); + * + * } + * + * @Test public void oneTPS_tenThreads_validateRateEnforcementWhenAvgResposneTimeIsUnderBudget() { + * + * TransactionRateController trc = new TransactionRateController(1.0, 10, 5); + * + * trc.trackResponseTime(25); trc.trackResponseTime(35); trc.trackResponseTime(45); + * trc.trackResponseTime(55); trc.trackResponseTime(70); + * + * // avg should be 46 ms + * + * assertEquals(9540, trc.getFixedDelayInMs()); + * + * } + * + * @Test public void oneTPS_tenThreads_validateRateEnforcementWhenAvgResposneTimeIsOverBudget() { + * + * TransactionRateController trc = new TransactionRateController(1.0, 10, 5); + * + * trc.trackResponseTime(75); trc.trackResponseTime(125); trc.trackResponseTime(250); + * trc.trackResponseTime(105); trc.trackResponseTime(23); + * + * // avg should be 115 ms + * + * assertEquals(8850, trc.getFixedDelayInMs()); + * + * } + * + * @Test public void halfTPS_tenThreads_validateRateEnforcementWhenAvgResposneTimeIsUnderBudget() + * { + * + * TransactionRateController trc = new TransactionRateController(0.5, 10, 5); + * + * trc.trackResponseTime(25); trc.trackResponseTime(35); trc.trackResponseTime(45); + * trc.trackResponseTime(55); trc.trackResponseTime(70); + * + * // avg should be 46 ms + * + * assertEquals(19540, trc.getFixedDelayInMs()); + * + * } + * + * @Test public void halfTPS_tenThreads_validateRateEnforcementWhenAvgResposneTimeIsOverBudget() { + * + * TransactionRateController trc = new TransactionRateController(0.5, 10, 5); + * + * trc.trackResponseTime(75); trc.trackResponseTime(125); trc.trackResponseTime(250); + * trc.trackResponseTime(105); trc.trackResponseTime(23); + * + * // avg should be 115 ms + * + * assertEquals(18850, trc.getFixedDelayInMs()); + * + * } + * + * @Test public void oneTPS_fiveThreads_validateRateEnforcementWhenAvgResposneTimeIsOverBudget() { + * + * TransactionRateController trc = new TransactionRateController(1, 5, 5); + * + * trc.trackResponseTime(0); trc.trackResponseTime(0); trc.trackResponseTime(0); + * trc.trackResponseTime(0); trc.trackResponseTime(0); + * + * // avg should be 0 ms + * + * assertEquals(5000, trc.getFixedDelayInMs()); + * + * } + */ + +} diff --git a/src/test/java/org/openecomp/sparky/dal/aai/config/ActiveInventoryConfigTest.java b/src/test/java/org/openecomp/sparky/dal/aai/config/ActiveInventoryConfigTest.java new file mode 100644 index 0000000..24cb405 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/aai/config/ActiveInventoryConfigTest.java @@ -0,0 +1,182 @@ +package org.openecomp.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 java.util.Properties; + +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sparky.dal.aai.enums.RestAuthenticationMode; +import org.openecomp.sparky.synchronizer.config.TaskProcessorConfig; + +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(getTestProperties()); + + assertNotNull(config); + + } + + 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; + + + } + + @Test + public void validateAccessors() throws Exception { + + ActiveInventoryConfig config = new ActiveInventoryConfig(getTestProperties()); + + ActiveInventoryRestConfig airc = config.getAaiRestConfig(); + ActiveInventorySslConfig sslConfig = config.getAaiSslConfig(); + TaskProcessorConfig tpc = config.getTaskProcessorConfig(); + + assertNotNull(airc); + assertNotNull(sslConfig); + assertNotNull(tpc); + + assertEquals("https://aai-host:8443/aai/v10", config.getBaseUri().toString()); + + assertTrue(config.toString().contains("ActiveInventoryConfig")); + + config.setAaiRestConfig(null); + config.setAaiSslConfig(null); + config.setTaskProcessorConfig(null); + + assertNull(config.getAaiRestConfig()); + assertNull(config.getAaiSslConfig()); + assertNull(config.getTaskProcessorConfig()); + + config.setAaiRestConfig(airc); + config.setAaiSslConfig(sslConfig); + config.setTaskProcessorConfig(tpc); + + + } + + @Test + public void validateRepairSelfLink_nullLink() throws Exception { + + ActiveInventoryConfig config = new ActiveInventoryConfig(getTestProperties()); + + ActiveInventoryRestConfig restConfig = config.getAaiRestConfig(); + + restConfig.setAuthenticationMode(RestAuthenticationMode.UNKNOWN_MODE); + restConfig.setHost("aai-host"); + restConfig.setPort("9191"); + + assertNull(config.repairSelfLink(null)); + } + + @Test + public void validateRepairSelfLink_emptyString() throws Exception { + + ActiveInventoryConfig config = new ActiveInventoryConfig(getTestProperties()); + + ActiveInventoryRestConfig restConfig = config.getAaiRestConfig(); + + restConfig.setAuthenticationMode(RestAuthenticationMode.UNKNOWN_MODE); + restConfig.setHost("aai-host"); + restConfig.setPort("9191"); + + assertEquals("http://aai-host:9191", config.repairSelfLink("")); + } + + @Test + public void validateRepairSelfLink_withResourceUrl() throws Exception { + + ActiveInventoryConfig config = new ActiveInventoryConfig(getTestProperties()); + + ActiveInventoryRestConfig restConfig = config.getAaiRestConfig(); + + restConfig.setAuthenticationMode(RestAuthenticationMode.SSL_CERT); + restConfig.setHost("aai-host"); + restConfig.setPort("9191"); + + assertEquals("https://aai-host:9191/aai/v10/business/customers/customer/1234", + config.repairSelfLink("/aai/v10/business/customers/customer/1234")); + } +}
\ No newline at end of file diff --git a/src/test/java/org/openecomp/sparky/dal/aai/config/ActiveInventoryRestConfigTest.java b/src/test/java/org/openecomp/sparky/dal/aai/config/ActiveInventoryRestConfigTest.java new file mode 100644 index 0000000..e1421c4 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/aai/config/ActiveInventoryRestConfigTest.java @@ -0,0 +1,293 @@ +/* +* ============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.openecomp.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.openecomp.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.getResourceBasePath(), "/aai/v9"); + 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); + + assertTrue(config.isCacheEnabled()); + assertEquals(config.getStorageFolderOverride(), "folderOverride"); + assertTrue(config.shouldCacheFailures()); + assertTrue(config.isUseCacheOnly()); + assertEquals(config.getNumCacheWorkers(), 50); + assertEquals(config.getMaxTimeToLiveInMs(), 500); + + + } + + /** + * 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.getResourceBasePath()); + 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()); + + assertFalse(config.isCacheEnabled()); + assertNull(config.getStorageFolderOverride()); + assertFalse(config.shouldCacheFailures()); + assertFalse(config.isUseCacheOnly()); + assertEquals(config.getNumCacheWorkers(), 0); + assertEquals(config.getMaxTimeToLiveInMs(), 0); + + } + + /** + * Failed path initialization + * + * @throws Exception + */ + @Test + public void validateInitializationWithInvalidProperties() throws Exception { + + /* + * Setup encryptor expectations + */ + + ActiveInventoryRestConfig config = new ActiveInventoryRestConfig(new Properties()); + + /* + * Now verify that all the internal members have been set to default values + */ + + assertEquals(config.getResourceBasePath(), "/aai/v7"); + 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); + + assertFalse(config.isCacheEnabled()); + assertNull(config.getStorageFolderOverride()); + assertFalse(config.shouldCacheFailures()); + assertFalse(config.isUseCacheOnly()); + assertEquals(config.getNumCacheWorkers(), 5); + assertEquals(config.getMaxTimeToLiveInMs(), -1); + + } + + /** + * 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.setCacheEnabled(true); + config.setConnectTimeoutInMs(1000); + config.setHost("myhost"); + config.setMaxTimeToLiveInMs(1234); + config.setNumCacheWorkers(1000); + config.setNumRequestRetries(1500); + config.setNumResolverWorkers(150); + config.setPort("11223344"); + config.setReadTimeoutInMs(54321); + config.setResourceBasePath("/aai/v21"); + config.setStorageFolderOverride("override"); + config.setUseCacheOnly(true); + config.setShouldCacheFailures(true); + + assertEquals(config.getResourceBasePath(), "/aai/v21"); + assertEquals(config.getHost(), "myhost"); + assertEquals(config.getPort(), "11223344"); + assertEquals(config.getNumRequestRetries(), 1500); + assertEquals(config.getNumResolverWorkers(), 150); + assertEquals(config.getConnectTimeoutInMs(), 1000); + assertEquals(config.getReadTimeoutInMs(), 54321); + assertTrue(config.shouldCacheFailures()); + + 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.isCacheEnabled()); + assertEquals(config.getStorageFolderOverride(), "override"); + assertTrue(config.shouldCacheFailures()); + assertTrue(config.isUseCacheOnly()); + assertEquals(config.getNumCacheWorkers(), 1000); + assertEquals(config.getMaxTimeToLiveInMs(), 1234); + + 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/openecomp/sparky/dal/aai/config/ActiveInventorySslConfigTest.java b/src/test/java/org/openecomp/sparky/dal/aai/config/ActiveInventorySslConfigTest.java new file mode 100644 index 0000000..834bbd1 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/aai/config/ActiveInventorySslConfigTest.java @@ -0,0 +1,268 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.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.openecomp.sparky.util.Encryptor; + +//import com.att.aai.util.EncryptedConfiguration; + +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 { + Encryptor encryptor = new Encryptor(); + 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", encryptor.decryptValue(value)EncryptedConfiguration.encryptToTriple("AES", + Long.toString(123456789 % 10000), "aa1admin", "password"));*/ + 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/openecomp/sparky/dal/elasticsearch/ElasticSearchConfigTest.java b/src/test/java/org/openecomp/sparky/dal/elasticsearch/ElasticSearchConfigTest.java new file mode 100644 index 0000000..c9d071f --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/elasticsearch/ElasticSearchConfigTest.java @@ -0,0 +1,272 @@ +/* +* ============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.openecomp.sparky.dal.elasticsearch; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; +import static org.junit.Assert.assertNotNull; + +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.openecomp.sparky.dal.elasticsearch.config.ElasticSearchConfig; +import org.openecomp.sparky.dal.exception.ElasticSearchOperationException; + + +import ch.qos.logback.classic.Level; + +/** + * 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 { + } + + /** + * Failure to initialize properties results in config defaults. + */ + @Test + public void failureToInitializePropertiesResultsInConfigDefaults() { + try { + ElasticSearchConfig config = ElasticSearchConfig.getConfig(); + + /* + * Now verify that all the internal members have been set to default values + */ + + assertEquals(config.getIpAddress(), "localhost"); + assertEquals(config.getHttpPort(), "" + 9200); + assertEquals(config.getJavaApiPort(), "" + 9300); + assertEquals(config.getIndexName(), "entitySearchIndex"); + assertEquals(config.getType(), "aaiEntities"); + assertEquals(config.getClusterName(), "elasticsearch"); + assertEquals(config.getMappingsFileName(), null); + assertEquals(config.getSettingsFileName(), null); + assertEquals(config.getAuditIndexName(), "auditdataindex"); + + } catch (Exception exc) { + assertEquals("null", exc.getLocalizedMessage()); + } + } + + + /** + * 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"); + esConfig.setAuditIndexName("auditIndexName"); + + 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"); + assertEquals(esConfig.getAuditIndexName(), "auditIndexName"); + + String output = esConfig.toString(); + + assertNotEquals(output, null); + + } + + /** + * Gets the elastic search settings expect valid config. + * + * @return the elastic search settings expect valid config + * @throws IOException Signals that an I/O exception has occurred. + * @throws ElasticSearchOperationException the elastic search operation exception + * Need to revisit this test case and change the way this class works + */ + @Ignore + public void getElasticSearchSettings_expectValidConfig() + throws IOException, ElasticSearchOperationException { + System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/')); + + ElasticSearchConfig esConfig = new ElasticSearchConfig(); + + esConfig.setSettingsFileName("src/main/config/es_settings.json"); + + assertNotNull(esConfig.getElasticSearchSettings()); + } + + /** + * Gets the elastic search settings expect file not found exception. + * + * @return the elastic search settings expect file not found exception + * @throws IOException Signals that an I/O exception has occurred. + * @throws ElasticSearchOperationException the elastic search operation exception + * + * Need to revisit this test case and change the way this class works + */ + @Ignore + public void getElasticSearchSettings_expectFileNotFoundException() + throws IOException, ElasticSearchOperationException { + System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/')); + + ElasticSearchConfig esConfig = new ElasticSearchConfig(); + + esConfig.setSettingsFileName("src/main/config/es_setting.json"); + + esConfig.getElasticSearchSettings(); + + } + + /** + * Gets the elastic search mappings expect valid config. + * + * @return the elastic search mappings expect valid config + * @throws IOException Signals that an I/O exception has occurred. + * @throws ElasticSearchOperationException the elastic search operation exception + * + * Need to revisit this test case and change the way this class works + */ + @Ignore + public void getElasticSearchMappings_expectValidConfig() + throws IOException, ElasticSearchOperationException { + System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/')); + + ElasticSearchConfig esConfig = new ElasticSearchConfig(); + + esConfig.setMappingsFileName("src/main/config/es_mappings.json"); + + assertNotNull(esConfig.getElasticSearchMappings()); + } + + /** + * Gets the elastic search mappings expect file not found exception. + * + * @return the elastic search mappings expect file not found exception + * @throws IOException Signals that an I/O exception has occurred. + * @throws ElasticSearchOperationException the elastic search operation exception + */ + @Test(expected = ElasticSearchOperationException.class) + public void getElasticSearchMappings_expectFileNotFoundException() + throws IOException, ElasticSearchOperationException { + System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/')); + + ElasticSearchConfig esConfig = new ElasticSearchConfig(); + + esConfig.setSettingsFileName("src/main/config/es_setting.json"); + + esConfig.getElasticSearchMappings(); + + } + + /** + * Builds the elastic search table config expect valid result. + * + * @throws ElasticSearchOperationException the elastic search operation exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void buildElasticSearchTableConfig_expectValidResult() + throws ElasticSearchOperationException, IOException { + ElasticSearchConfig spyEsConfig = Mockito.spy(new ElasticSearchConfig()); + Mockito.doReturn(GOOD_MAPPINGS_FILE).when(spyEsConfig).getElasticSearchMappings(); + Mockito.doReturn(GOOD_SETTINGS_FILE).when(spyEsConfig).getElasticSearchSettings(); + Mockito.doReturn("myIndexTableType").when(spyEsConfig).getType(); + + assertNotNull(spyEsConfig.buildElasticSearchTableConfig()); + } + + /** + * Builds the elastic search table config expect exception. + * + * @throws ElasticSearchOperationException the elastic search operation exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test(expected = ElasticSearchOperationException.class) + public void buildElasticSearchTableConfig_expectException() + throws ElasticSearchOperationException, IOException { + ElasticSearchConfig spyEsConfig = Mockito.spy(new ElasticSearchConfig()); + Mockito.doReturn(GOOD_MAPPINGS_FILE).when(spyEsConfig).getElasticSearchMappings(); + Mockito.doReturn(BAD_SETTINGS_FILE).when(spyEsConfig).getElasticSearchSettings(); + Mockito.doReturn("myIndexTableType").when(spyEsConfig).getType(); + + spyEsConfig.buildElasticSearchTableConfig(); + } + +} diff --git a/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntity.java b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntity.java new file mode 100644 index 0000000..b3abd14 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntity.java @@ -0,0 +1,44 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.elasticsearch.entity; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class AutoSuggestDocumentEntity { + + @JsonProperty("entity_suggest") + AutoSuggestDocumentEntityFields fields; + + public AutoSuggestDocumentEntityFields getFields() { + return fields; + } + + public void setFields(AutoSuggestDocumentEntityFields fields) { + this.fields = fields; + } + + + +} diff --git a/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntityFields.java b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntityFields.java new file mode 100644 index 0000000..db0dc8c --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/AutoSuggestDocumentEntityFields.java @@ -0,0 +1,81 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.elasticsearch.entity; + +import java.util.ArrayList; +import java.util.List; + +import com.fasterxml.jackson.annotation.JsonInclude; +import com.fasterxml.jackson.annotation.JsonInclude.Include; + +@JsonInclude(Include.NON_NULL) +public class AutoSuggestDocumentEntityFields { + + private String output; + private List<String> input; + private PayloadEntity payload; + private int weight; + + public AutoSuggestDocumentEntityFields() { + input = new ArrayList<String>(); + } + + public String getOutput() { + return output; + } + + public void setOutput(String output) { + this.output = output; + } + + public List<String> getInput() { + return input; + } + + public void setInput(List<String> input) { + this.input = input; + } + + public PayloadEntity getPayload() { + return payload; + } + + public void setPayload(PayloadEntity payload) { + this.payload = payload; + } + + public int getWeight() { + return weight; + } + + public void setWeight(int weight) { + this.weight = weight; + } + + public void addInput(String input) { + this.input.add(input); + } + +} diff --git a/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/AutoSuggestElasticHitEntity.java b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/AutoSuggestElasticHitEntity.java new file mode 100644 index 0000000..60ac538 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/AutoSuggestElasticHitEntity.java @@ -0,0 +1,87 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.elasticsearch.entity; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class AutoSuggestElasticHitEntity { + + @JsonProperty("_index") + private String index; + + @JsonProperty("_type") + private String type; + + @JsonProperty("_id") + private String id; + + @JsonProperty("_score") + private String score; + + @JsonProperty("_source") + private AutoSuggestDocumentEntity source; + + public String getIndex() { + return index; + } + + public void setIndex(String index) { + this.index = index; + } + + public String getType() { + return type; + } + + public void setType(String type) { + this.type = type; + } + + public String getId() { + return id; + } + + public void setId(String id) { + this.id = id; + } + + public String getScore() { + return score; + } + + public void setScore(String score) { + this.score = score; + } + + public AutoSuggestDocumentEntity getSource() { + return source; + } + + public void setSource(AutoSuggestDocumentEntity source) { + this.source = source; + } + + +} diff --git a/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/AutoSuggestElasticHitsEntity.java b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/AutoSuggestElasticHitsEntity.java new file mode 100644 index 0000000..af74485 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/AutoSuggestElasticHitsEntity.java @@ -0,0 +1,50 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.elasticsearch.entity; + +import java.util.ArrayList; +import java.util.List; + +public class AutoSuggestElasticHitsEntity { + + private List<AutoSuggestElasticHitEntity> hits; + + public AutoSuggestElasticHitsEntity() { + hits = new ArrayList<AutoSuggestElasticHitEntity>(); + } + + public List<AutoSuggestElasticHitEntity> getHits() { + return hits; + } + + 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/openecomp/sparky/dal/elasticsearch/entity/AutoSuggestElasticSearchResponse.java b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/AutoSuggestElasticSearchResponse.java new file mode 100644 index 0000000..9b6c9f5 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/AutoSuggestElasticSearchResponse.java @@ -0,0 +1,85 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.elasticsearch.entity; + +import java.util.HashMap; +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 AutoSuggestElasticHitsEntity hits; + + public AutoSuggestElasticSearchResponse(){ + this.shards = new HashMap<String,String>(); + } + + public int getTook() { + return took; + } + + public void setTook(int took) { + this.took = took; + } + + public boolean isTimedOut() { + return timedOut; + } + + public void setTimedOut(boolean timedOut) { + this.timedOut = timedOut; + } + + public Map<String, String> getShards() { + return shards; + } + + public void setShards(Map<String, String> shards) { + this.shards = shards; + } + + public void addShard(String name, String value) { + shards.put(name, value); + } + + public AutoSuggestElasticHitsEntity getHits() { + return hits; + } + + public void setHits(AutoSuggestElasticHitsEntity hits) { + this.hits = hits; + } + + +} diff --git a/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/BucketEntity.java b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/BucketEntity.java new file mode 100644 index 0000000..0a1a133 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/BucketEntity.java @@ -0,0 +1,61 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.elasticsearch.entity; + +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; + } + + public void setKey(String key) { + this.key = key; + } + + public int getDocCount() { + return docCount; + } + + public void setDocCount(int docCount) { + this.docCount = docCount; + } + + +} diff --git a/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/ElasticHit.java b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/ElasticHit.java new file mode 100644 index 0000000..32dc17a --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/ElasticHit.java @@ -0,0 +1,29 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.elasticsearch.entity; + +public class ElasticHit { + +} diff --git a/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/ElasticHitsEntity.java b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/ElasticHitsEntity.java new file mode 100644 index 0000000..b10532e --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/ElasticHitsEntity.java @@ -0,0 +1,74 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.elasticsearch.entity; + +import java.util.ArrayList; +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); + } + + public int getTotal() { + return total; + } + + public void setTotal(int total) { + this.total = total; + } + + public int getMaxScore() { + return maxScore; + } + + public void setMaxScore(int maxScore) { + this.maxScore = maxScore; + } + + public List<ElasticHit> getHits() { + return hits; + } + + public void setHits(List<ElasticHit> hits) { + this.hits = hits; + } + + + +} diff --git a/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/ElasticSearchAggegrationResponse.java b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/ElasticSearchAggegrationResponse.java new file mode 100644 index 0000000..54c9278 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/ElasticSearchAggegrationResponse.java @@ -0,0 +1,109 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.elasticsearch.entity; + +import java.util.HashMap; +import java.util.Map; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class ElasticSearchAggegrationResponse { + + private int took; + + @JsonProperty("timed_out") + private boolean timedOut; + + @JsonProperty("_shards") + private Map<String, String> shards; + + private ElasticHitsEntity hits; + + private Map<String, ElasticSearchAggregation> aggregations; + + public ElasticSearchAggegrationResponse() { + this.shards = new HashMap<String, String>(); + this.aggregations = new HashMap<String,ElasticSearchAggregation>(); + } + + + public int getTook() { + return took; + } + + + public void setTook(int took) { + this.took = took; + } + + + public boolean isTimedOut() { + return timedOut; + } + + + public void setTimedOut(boolean timedOut) { + this.timedOut = timedOut; + } + + + public Map<String, String> getShards() { + return shards; + } + + + public void setShards(Map<String, String> shards) { + this.shards = shards; + } + + + public ElasticHitsEntity getHits() { + return hits; + } + + + public void setHits(ElasticHitsEntity hits) { + this.hits = hits; + } + + public void addShard(String key, String value) { + this.shards.put(key,value); + } + + + public Map<String, ElasticSearchAggregation> getAggregations() { + return aggregations; + } + + + public void setAggregations(Map<String, ElasticSearchAggregation> aggregations) { + this.aggregations = aggregations; + } + + public void addAggregation(String key, ElasticSearchAggregation agg) { + this.aggregations.put(key, agg); + } + +} diff --git a/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/ElasticSearchAggregation.java b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/ElasticSearchAggregation.java new file mode 100644 index 0000000..ea954d9 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/ElasticSearchAggregation.java @@ -0,0 +1,74 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.elasticsearch.entity; + +import java.util.ArrayList; +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>(); + } + + public int getDocCountErrorUpperBound() { + return docCountErrorUpperBound; + } + + public void setDocCountErrorUpperBound(int docCountErrorUpperBound) { + this.docCountErrorUpperBound = docCountErrorUpperBound; + } + + public int getSumOtherDocCount() { + return sumOtherDocCount; + } + + public void setSumOtherDocCount(int sumOtherDocCount) { + this.sumOtherDocCount = sumOtherDocCount; + } + + public List<BucketEntity> getBuckets() { + return buckets; + } + + public void setBuckets(List<BucketEntity> buckets) { + this.buckets = buckets; + } + + public void addBucket(BucketEntity bucket) { + buckets.add(bucket); + } + +} diff --git a/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/ElasticSearchCountResponse.java b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/ElasticSearchCountResponse.java new file mode 100644 index 0000000..4b11f8c --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/ElasticSearchCountResponse.java @@ -0,0 +1,60 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.elasticsearch.entity; + +import java.util.HashMap; +import java.util.Map; + +public class ElasticSearchCountResponse { + + private int count; + private Map<String, String> shards; + + public ElasticSearchCountResponse() { + this.shards = new HashMap<String,String>(); + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + + public Map<String, String> getShards() { + return shards; + } + + 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/openecomp/sparky/dal/elasticsearch/entity/PayloadEntity.java b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/PayloadEntity.java new file mode 100644 index 0000000..360abdf --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/elasticsearch/entity/PayloadEntity.java @@ -0,0 +1,32 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.elasticsearch.entity; + +public class PayloadEntity { + + public PayloadEntity() { + } + +} diff --git a/src/test/java/org/openecomp/sparky/dal/rest/RestClientBuilderTest.java b/src/test/java/org/openecomp/sparky/dal/rest/RestClientBuilderTest.java new file mode 100644 index 0000000..80ee21f --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/rest/RestClientBuilderTest.java @@ -0,0 +1,180 @@ +/* +* ============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.openecomp.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 com.sun.jersey.api.client.Client; +import com.sun.jersey.client.urlconnection.HTTPSProperties; + +import javax.net.ssl.SSLContext; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.openecomp.sparky.security.SecurityContextFactory; +import org.powermock.modules.junit4.PowerMockRunner; + +import ch.qos.logback.classic.Level; + +/** + * The Class RestClientBuilderTest. + */ +@RunWith(PowerMockRunner.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/openecomp/sparky/dal/rest/RestfulDataAccessorTest.java b/src/test/java/org/openecomp/sparky/dal/rest/RestfulDataAccessorTest.java new file mode 100644 index 0000000..b898d90 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/rest/RestfulDataAccessorTest.java @@ -0,0 +1,226 @@ +/* +* ============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.openecomp.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.powermock.modules.junit4.PowerMockRunner; + +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(PowerMockRunner.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/openecomp/sparky/dal/sas/entity/DocumentEntity.java b/src/test/java/org/openecomp/sparky/dal/sas/entity/DocumentEntity.java new file mode 100644 index 0000000..6285e9c --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/sas/entity/DocumentEntity.java @@ -0,0 +1,68 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.sas.entity; + +import java.util.HashMap; +import java.util.Map; + +public class DocumentEntity { + private String etag; + private String url; + private Map<String,String> content; + + public DocumentEntity() { + content = new HashMap<String,String>(); + } + + + public String getEtag() { + return etag; + } + + public void setEtag(String etag) { + this.etag = etag; + } + + public String getUrl() { + return url; + } + + public void setUrl(String url) { + this.url = url; + } + + public Map<String, String> getContent() { + return content; + } + + 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/openecomp/sparky/dal/sas/entity/EntityCountResponse.java b/src/test/java/org/openecomp/sparky/dal/sas/entity/EntityCountResponse.java new file mode 100644 index 0000000..3940b28 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/sas/entity/EntityCountResponse.java @@ -0,0 +1,55 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.sas.entity; + +import java.util.HashMap; +import java.util.Map; + +public class EntityCountResponse { + + private Map<String,String> shards; + private int count; + + public EntityCountResponse() { + this.shards = new HashMap<String,String>(); + } + + public Map<String, String> getShards() { + return shards; + } + + public void setShards(Map<String, String> shards) { + this.shards = shards; + } + + public int getCount() { + return count; + } + + public void setCount(int count) { + this.count = count; + } + +} diff --git a/src/test/java/org/openecomp/sparky/dal/sas/entity/GroupByAggregationEntity.java b/src/test/java/org/openecomp/sparky/dal/sas/entity/GroupByAggregationEntity.java new file mode 100644 index 0000000..3ab5e30 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/sas/entity/GroupByAggregationEntity.java @@ -0,0 +1,60 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.sas.entity; + +import java.util.ArrayList; +import java.util.List; + +import org.openecomp.sparky.dal.elasticsearch.entity.BucketEntity; + +public class GroupByAggregationEntity { + private int totalChartHits; + List<BucketEntity> buckets; + + public GroupByAggregationEntity() { + this.buckets = new ArrayList<BucketEntity>(); + } + + public int getTotalChartHits() { + return totalChartHits; + } + + public void setTotalChartHits(int totalChartHits) { + this.totalChartHits = totalChartHits; + } + + public List<BucketEntity> getBuckets() { + return buckets; + } + + public void setBuckets(List<BucketEntity> buckets) { + this.buckets = buckets; + } + + public void addBucket(BucketEntity bucket) { + this.buckets.add(bucket); + } + +} diff --git a/src/test/java/org/openecomp/sparky/dal/sas/entity/GroupByAggregationResponseEntity.java b/src/test/java/org/openecomp/sparky/dal/sas/entity/GroupByAggregationResponseEntity.java new file mode 100644 index 0000000..4ef3be1 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/sas/entity/GroupByAggregationResponseEntity.java @@ -0,0 +1,48 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.sas.entity; + +import com.fasterxml.jackson.annotation.JsonProperty; + +public class GroupByAggregationResponseEntity { + + @JsonProperty("groupby_aggregation") + private GroupByAggregationEntity aggEntity; + + public GroupByAggregationResponseEntity() { + + } + + public GroupByAggregationEntity getAggEntity() { + return aggEntity; + } + + public void setAggEntity(GroupByAggregationEntity aggEntity) { + this.aggEntity = aggEntity; + } + + + +} diff --git a/src/test/java/org/openecomp/sparky/dal/sas/entity/HitEntity.java b/src/test/java/org/openecomp/sparky/dal/sas/entity/HitEntity.java new file mode 100644 index 0000000..f5036e7 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/sas/entity/HitEntity.java @@ -0,0 +1,48 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.sas.entity; + +public class HitEntity { + + private String score; + private DocumentEntity document; + + public String getScore() { + return score; + } + + public void setScore(String score) { + this.score = score; + } + + public DocumentEntity getDocument() { + return document; + } + + public void setDocument(DocumentEntity document) { + this.document = document; + } + +} diff --git a/src/test/java/org/openecomp/sparky/dal/sas/entity/SearchAbstractionEntityBuilder.java b/src/test/java/org/openecomp/sparky/dal/sas/entity/SearchAbstractionEntityBuilder.java new file mode 100644 index 0000000..fa3d463 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/sas/entity/SearchAbstractionEntityBuilder.java @@ -0,0 +1,295 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.sas.entity; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; + +public class SearchAbstractionEntityBuilder { + + + public static HitEntity getHitSample1() { + + HitEntity hitEntity = new HitEntity(); + DocumentEntity doc = new DocumentEntity(); + + hitEntity.setDocument(doc); + 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.setEtag("1"); + + + return hitEntity; + + } + + public static HitEntity getHitSample2() { + + HitEntity hitEntity = new HitEntity(); + DocumentEntity doc = new DocumentEntity(); + + hitEntity.setDocument(doc); + 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.setEtag("1"); + + + return hitEntity; + + } + + public static HitEntity getHitSample3() { + + HitEntity hitEntity = new HitEntity(); + DocumentEntity doc = new DocumentEntity(); + + hitEntity.setDocument(doc); + 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.setEtag("1"); + + + return hitEntity; + + } + + public static HitEntity getHitSample4() { + + HitEntity hitEntity = new HitEntity(); + DocumentEntity doc = new DocumentEntity(); + + hitEntity.setDocument(doc); + 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.setEtag("1"); + + + return hitEntity; + + } + + public static HitEntity getHitSample5() { + + HitEntity hitEntity = new HitEntity(); + DocumentEntity doc = new DocumentEntity(); + + hitEntity.setDocument(doc); + 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.setEtag("1"); + + + return hitEntity; + + } + + public static HitEntity getHitSample6() { + + HitEntity hitEntity = new HitEntity(); + DocumentEntity doc = new DocumentEntity(); + + hitEntity.setDocument(doc); + 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.setEtag("1"); + + + return hitEntity; + + } + + public static HitEntity getHitSample7() { + + HitEntity hitEntity = new HitEntity(); + DocumentEntity doc = new DocumentEntity(); + + hitEntity.setDocument(doc); + 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.setEtag("1"); + + + return hitEntity; + + } + + public static HitEntity getHitSample8() { + + HitEntity hitEntity = new HitEntity(); + DocumentEntity doc = new DocumentEntity(); + + hitEntity.setDocument(doc); + 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.setEtag("1"); + + + return hitEntity; + + } + + public static HitEntity getHitSample9() { + + HitEntity hitEntity = new HitEntity(); + DocumentEntity doc = new DocumentEntity(); + + hitEntity.setDocument(doc); + 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.setEtag("1"); + + + return hitEntity; + + } + + public static HitEntity getHitSample10() { + + HitEntity hitEntity = new HitEntity(); + DocumentEntity doc = new DocumentEntity(); + + hitEntity.setDocument(doc); + 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.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()); + hits.add(getHitSample4()); + hits.add(getHitSample5()); + hits.add(getHitSample6()); + hits.add(getHitSample7()); + hits.add(getHitSample8()); + hits.add(getHitSample9()); + hits.add(getHitSample10()); + + searchResult.setHits(hits); + + return sasResponse; + + } + + +} diff --git a/src/test/java/org/openecomp/sparky/dal/sas/entity/SearchAbstractionResponse.java b/src/test/java/org/openecomp/sparky/dal/sas/entity/SearchAbstractionResponse.java new file mode 100644 index 0000000..0e6398f --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/sas/entity/SearchAbstractionResponse.java @@ -0,0 +1,39 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.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/openecomp/sparky/dal/sas/entity/SearchResult.java b/src/test/java/org/openecomp/sparky/dal/sas/entity/SearchResult.java new file mode 100644 index 0000000..992d5b5 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/dal/sas/entity/SearchResult.java @@ -0,0 +1,49 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.dal.sas.entity; + +import java.util.List; + +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/openecomp/sparky/inventory/GeoIndexDocumentTest.java b/src/test/java/org/openecomp/sparky/inventory/GeoIndexDocumentTest.java new file mode 100644 index 0000000..9274c30 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/inventory/GeoIndexDocumentTest.java @@ -0,0 +1,121 @@ +/* +* ============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.openecomp.sparky.inventory; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sparky.inventory.entity.GeoIndexDocument; +import org.powermock.modules.junit4.PowerMockRunner; + +/** + * The Class GeoIndexDocumentTest. + */ +@RunWith(PowerMockRunner.class) +public class GeoIndexDocumentTest { + + /** + * Inits the. + * + * @throws Exception the exception + */ + @Before + public void init() throws Exception {} + + /** + * Checks if is valid geo index document success path. + */ + @Test + public void isValidGeoIndexDocument_successPath() { + + GeoIndexDocument geoDoc = new GeoIndexDocument(); + + geoDoc.setEntityPrimaryKeyName("pkeyName"); + geoDoc.setEntityPrimaryKeyValue("pkeyValue"); + geoDoc.setEntityType("type"); + geoDoc.setId("12312"); + geoDoc.setLatitude("-45.123"); + geoDoc.setLongitude("181.321"); + geoDoc.setSelfLink("https://server.somewhere.com:8443/aai/v7/id"); + + assertTrue(geoDoc.isValidGeoDocument()); + + } + + /** + * Checks if is valid geo index document fail no geo coordinates. + */ + @Test + public void isValidGeoIndexDocument_fail_no_geoCoordinates() { + + GeoIndexDocument geoIndexDoc = new GeoIndexDocument(); + + geoIndexDoc.setEntityPrimaryKeyName("pkeyName"); + geoIndexDoc.setEntityPrimaryKeyValue("pkeyValue"); + geoIndexDoc.setEntityType("type"); + geoIndexDoc.setId("12312"); + geoIndexDoc.setSelfLink("https://server.somewhere.com:8443/aai/v7/id"); + + assertFalse(geoIndexDoc.isValidGeoDocument()); + + } + + /** + * Checks if is valid geo index document fail invalid geo coordinates. + */ + @Test + public void isValidGeoIndexDocument_fail_invalid_geoCoordinates() { + + GeoIndexDocument geoIndexDoc = new GeoIndexDocument(); + + geoIndexDoc.setEntityPrimaryKeyName("pkeyName"); + geoIndexDoc.setEntityPrimaryKeyValue("pkeyValue"); + geoIndexDoc.setEntityType("type"); + geoIndexDoc.setId("12312"); + geoIndexDoc.setLatitude("not_a_valid"); + geoIndexDoc.setLongitude("geo point"); + + geoIndexDoc.setSelfLink("https://server.somewhere.com:8443/aai/v7/id"); + + assertFalse(geoIndexDoc.isValidGeoDocument()); + + } + + /** + * Checks if is valid geo index document fail nothing set. + */ + @Test + public void isValidGeoIndexDocument_fail_nothing_set() { + + GeoIndexDocument geoIndexDoc = new GeoIndexDocument(); + + assertFalse(geoIndexDoc.isValidGeoDocument()); + + } +} diff --git a/src/test/java/org/openecomp/sparky/security/SecurityContextFactoryImplTest.java b/src/test/java/org/openecomp/sparky/security/SecurityContextFactoryImplTest.java new file mode 100644 index 0000000..c387e49 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/security/SecurityContextFactoryImplTest.java @@ -0,0 +1,141 @@ +/* +* ============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.openecomp.sparky.security; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; + +import java.io.FileInputStream; + +import javax.net.ssl.SSLContext; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.openecomp.sparky.util.LogValidator; + +import ch.qos.logback.classic.Level; + +/** + * The Class SecurityContextFactoryImplTest. + */ +public class SecurityContextFactoryImplTest { + + private LogValidator logValidator; + + /** + * Inits the. + * + * @throws Exception the exception + */ + @Before + public void init() throws Exception { + logValidator = new LogValidator(); + logValidator.initializeLogger(Level.WARN); + } + + /** + * Basic construction test. + * + * @throws Exception the exception + */ + @Test + public void basicConstructionTest() throws Exception { + + SecurityContextFactory sslContextFactory = new SecurityContextFactoryImpl(); + + assertEquals("TLS", sslContextFactory.getSslAlgorithm()); + assertEquals("SunX509", sslContextFactory.getKeyManagerAlgortihm()); + assertEquals("PKCS12", sslContextFactory.getKeyStoreType()); + assertEquals(false, sslContextFactory.isServerCertificationChainValidationEnabled()); + assertEquals(null, sslContextFactory.getClientCertFileInputStream()); + } + + /** + * Validate secure context. + * + * @throws Exception the exception + */ + @Test + public void validateSecureContext() throws Exception { + + SecurityContextFactory sslContextFactory = new SecurityContextFactoryImpl(); + + SSLContext sslContext = sslContextFactory.getSecureContext(); + + assertNotNull(sslContext); + } + + /** + * Validate secure context with server cert chain validation. + * + * @throws Exception the exception + */ + @Test + public void validateSecureContext_withServerCertChainValidation() throws Exception { + + SecurityContextFactory sslContextFactory = new SecurityContextFactoryImpl(); + sslContextFactory.setServerCertificationChainValidationEnabled(true); + sslContextFactory.setTrustStoreFileName("filename"); + + sslContextFactory.setClientCertFileName(null); + + SSLContext sslContext = sslContextFactory.getSecureContext(); + + assertNotNull(sslContext); + } + + /** + * Validate accessors. + * + * @throws Exception the exception + */ + @Test + public void validateAccessors() throws Exception { + + SecurityContextFactory sslContextFactory = new SecurityContextFactoryImpl(); + + FileInputStream mockInputStream = Mockito.mock(FileInputStream.class); + + sslContextFactory.setSslAlgorithm("sslAlgorithm"); + sslContextFactory.setKeyManagerAlgortihm("keyManagerAlgorithm"); + sslContextFactory.setKeyStoreType("keyStoreType"); + sslContextFactory.setClientCertFileInputStream(mockInputStream); + sslContextFactory.setServerCertificationChainValidationEnabled(true); + sslContextFactory.setTrustStoreFileName("truststoreFileName"); + sslContextFactory.setClientCertPassword("password"); + + assertEquals("sslAlgorithm", sslContextFactory.getSslAlgorithm()); + assertEquals("keyManagerAlgorithm", sslContextFactory.getKeyManagerAlgortihm()); + assertEquals("keyStoreType", sslContextFactory.getKeyStoreType()); + assertEquals(mockInputStream, sslContextFactory.getClientCertFileInputStream()); + assertEquals(true, sslContextFactory.isServerCertificationChainValidationEnabled()); + assertEquals("truststoreFileName", sslContextFactory.getTrustStoreFileName()); + assertEquals("password", sslContextFactory.getClientCertPassword()); + + } + +} diff --git a/src/test/java/org/openecomp/sparky/security/portal/TestPortalRestAPIServiceImpl.java b/src/test/java/org/openecomp/sparky/security/portal/TestPortalRestAPIServiceImpl.java new file mode 100644 index 0000000..a39c19d --- /dev/null +++ b/src/test/java/org/openecomp/sparky/security/portal/TestPortalRestAPIServiceImpl.java @@ -0,0 +1,269 @@ +/* +* ============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.openecomp.sparky.security.portal; + +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.is; +import static org.hamcrest.Matchers.nullValue; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.when; + +import java.io.File; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.LinkedHashSet; +import java.util.List; +import java.util.Set; + +import javax.servlet.http.HttpServletRequest; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.openecomp.portalsdk.core.onboarding.exception.PortalAPIException; +import org.openecomp.portalsdk.core.restful.domain.EcompRole; +import org.openecomp.portalsdk.core.restful.domain.EcompUser; +import org.openecomp.sparky.security.portal.config.PortalAuthenticationConfig; +import org.openecomp.sparky.security.portal.config.RolesConfig; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.junit4.PowerMockRunner; +import org.powermock.reflect.Whitebox; + +@PowerMockIgnore({ "javax.crypto.*" }) +@RunWith(PowerMockRunner.class) +@PrepareForTest({ PortalAuthenticationConfig.class, RolesConfig.class }) +public class TestPortalRestAPIServiceImpl { + + private static File testUsersFile; + private static final String LOGINID_1 = "200"; + private static final String LOGINID_2 = "201"; + private static final String VIEW_ROLE = "View"; + + 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"); + + private String filename; + TestData(String filename) {this.filename = filename;} + public String getFilename() {return this.filename;} + // @formatter:on + } + + @Mock + private UserManager userManager = new UserManager(testUsersFile); + + @InjectMocks + private PortalRestAPIServiceImpl portalApi = new PortalRestAPIServiceImpl(); + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + testUsersFile = Paths.get(TestData.TEST_USERS.getFilename()).toFile(); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + Files.deleteIfExists(testUsersFile.toPath()); + } + + @Before + public void setUp() throws Exception { + Whitebox.setInternalState(RolesConfig.class, "ROLES_CONFIG_FILE", + TestData.ROLES_CONFIG_FILE.getFilename()); + } + + @After + public void tearDown() throws Exception { + Files.deleteIfExists(testUsersFile.toPath()); + } + + @Test + public void testPushAndGetUser() throws Exception { + EcompUser user = new EcompUser(); + user.setLoginId(LOGINID_1); + + portalApi.pushUser(user); + EcompUser storedUser = portalApi.getUser(user.getLoginId()); + + assertThat(storedUser.getLoginId(), is(user.getLoginId())); + } + + @Test(expected = PortalAPIException.class) + public void testCannotPushUserTwice() throws Exception { + EcompUser user = new EcompUser(); + user.setLoginId(LOGINID_1); + + portalApi.pushUser(user); + portalApi.pushUser(user); + } + + @Test(expected = PortalAPIException.class) + public void testGetUnknownUser() throws Exception { + EcompUser user = new EcompUser(); + user.setLoginId(LOGINID_1); + portalApi.pushUser(user); + + portalApi.getUser("does-not-exist"); + } + + @Test + public void testGetUsers() throws Exception { + EcompUser user = new EcompUser(); + user.setLoginId(LOGINID_1); + + EcompUser user2 = new EcompUser(); + user2.setLoginId(LOGINID_2); + + portalApi.pushUser(user); + portalApi.pushUser(user2); + + List<EcompUser> users = portalApi.getUsers(); + + assertThat(users.size(), is(2)); + assertThat(users.get(0).getLoginId(), is(LOGINID_1)); + assertThat(users.get(1).getLoginId(), is(LOGINID_2)); + } + + @Test + public void testEditUser() throws Exception { + EcompUser user = new EcompUser(); + user.setLoginId(LOGINID_1); + user.setFirstName("Bob"); + + portalApi.pushUser(user); + + user.setFirstName("Jen"); + portalApi.editUser(LOGINID_1, user); + + assertThat(portalApi.getUser(LOGINID_1).getFirstName(), is("Jen")); + } + + @Test(expected = PortalAPIException.class) + public void testEditUnknowUser() throws Exception { + EcompUser user = new EcompUser(); + user.setLoginId(LOGINID_1); + portalApi.pushUser(user); + + portalApi.editUser("does-no-exist", new EcompUser()); + } + + @Test + public void testGetRoles() throws Exception { + EcompUser user = new EcompUser(); + user.setLoginId(LOGINID_1); + user.setRoles(new HashSet<>(portalApi.getAvailableRoles())); + + portalApi.pushUser(user); + + List<EcompRole> userRoles = portalApi.getUserRoles(LOGINID_1); + + assertThat(userRoles.size(), is(1)); + assertThat(userRoles.get(0).getId(), is(1L)); + assertThat(userRoles.get(0).getName(), is(VIEW_ROLE)); + } + + @Test + public void testPushUserRoles() throws Exception { + EcompUser user = new EcompUser(); + user.setLoginId(LOGINID_1); + portalApi.pushUser(user); + + EcompUser storedUser = portalApi.getUser(LOGINID_1); + assertThat(storedUser.getRoles(), nullValue()); + + portalApi.pushUserRole(LOGINID_1, UserManager.getRoles()); + + Set<EcompRole> storedUserRoles = portalApi.getUser(LOGINID_1).getRoles(); + ArrayList<EcompRole> rolesList = new ArrayList<>(storedUserRoles); + + assertThat(rolesList.size(), is(1)); + assertThat(rolesList.get(0).getId(), is(1L)); + assertThat(rolesList.get(0).getName(), is(VIEW_ROLE)); + } + + @Test + public void testCannotPushRoleTwice() throws Exception { + EcompUser user = new EcompUser(); + user.setLoginId(LOGINID_1); + portalApi.pushUser(user); + + EcompUser storedUser = portalApi.getUser(LOGINID_1); + assertThat(storedUser.getRoles(), nullValue()); + + portalApi.pushUserRole(LOGINID_1, UserManager.getRoles()); + portalApi.pushUserRole(LOGINID_1, UserManager.getRoles()); + + Set<EcompRole> storedUserRoles = portalApi.getUser(LOGINID_1).getRoles(); + ArrayList<EcompRole> rolesList = new ArrayList<>(storedUserRoles); + + assertThat(rolesList.size(), is(1)); + assertThat(rolesList.get(0).getId(), is(1L)); + assertThat(rolesList.get(0).getName(), is(VIEW_ROLE)); + } + + @Test + public void testDeleteUserRoles() throws Exception { + EcompUser user = new EcompUser(); + user.setLoginId(LOGINID_1); + user.setFirstName("Bob"); + List<EcompRole> availableRoles = portalApi.getAvailableRoles(); + user.setRoles(new LinkedHashSet<EcompRole>(availableRoles)); + + portalApi.pushUser(user); + + portalApi.pushUserRole(LOGINID_1, new ArrayList<EcompRole>()); + + EcompUser userWithNoRoles = portalApi.getUser(LOGINID_1); + + assertThat(userWithNoRoles.getRoles(), empty()); + } + + @Test + public void testPushNullRoles() throws Exception { + EcompUser user = new EcompUser(); + user.setLoginId(LOGINID_1); + user.setFirstName("Bob"); + List<EcompRole> availableRoles = portalApi.getAvailableRoles(); + user.setRoles(new LinkedHashSet<EcompRole>(availableRoles)); + + portalApi.pushUser(user); + portalApi.pushUserRole(LOGINID_1, null); + + EcompUser userWithNoRoles = portalApi.getUser(LOGINID_1); + + assertThat(userWithNoRoles.getRoles(), empty()); + } +}
\ No newline at end of file diff --git a/src/test/java/org/openecomp/sparky/security/portal/TestUserManager.java b/src/test/java/org/openecomp/sparky/security/portal/TestUserManager.java new file mode 100644 index 0000000..1a8a9e9 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/security/portal/TestUserManager.java @@ -0,0 +1,205 @@ +/* +* ============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.openecomp.sparky.security.portal; + +import static org.hamcrest.Matchers.empty; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertThat; + +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.Arrays; +import java.util.List; +import java.util.concurrent.Callable; +import java.util.concurrent.ExecutorService; +import java.util.concurrent.Executors; +import java.util.stream.Collectors; + +import org.junit.After; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.portalsdk.core.restful.domain.EcompUser; +import org.openecomp.sparky.util.NodeUtils; +import org.powermock.modules.junit4.PowerMockRunner; + +import com.google.gson.Gson; + +@RunWith(PowerMockRunner.class) +//@PrepareForTest(RolesConfig.class) +public class TestUserManager { + + private static final String LOGINID_3 = "3"; + private static File noFile; + private static File concurrentUsers; + private static File concurrentEditUsers; + + private static final Gson GSON = new Gson(); + private static final String LOGINID_1 = "1"; + private static final String LOGINID_2 = "2"; + + 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"); + + private String filename; + TestData(String filename) {this.filename = filename;} + public String getFilename() {return this.filename;} + // @formatter:on + } + + @BeforeClass + public static void setUpBeforeClass() throws Exception { + noFile = Paths.get(TestData.NO_FILE.getFilename()).toFile(); + concurrentUsers = Paths.get(TestData.CONCURRENT_USERS.getFilename()).toFile(); + concurrentEditUsers = Paths.get(TestData.CONCURRENT_EDIT_USERS.getFilename()).toFile(); + } + + @AfterClass + public static void tearDownAfterClass() throws Exception { + Files.deleteIfExists(concurrentUsers.toPath()); + Files.deleteIfExists(concurrentEditUsers.toPath()); + } + + @Before + public void setUp() throws Exception { + EcompUser user1 = new EcompUser(); + user1.setLoginId(LOGINID_1); + + EcompUser user2 = new EcompUser(); + user2.setLoginId(LOGINID_2); + + List<EcompUser> users = Arrays.asList(user1, user2); + Files.write(concurrentEditUsers.toPath(), GSON.toJson(users).getBytes()); + +// Whitebox.setInternalState(RolesConfig.class, "ROLES_CONFIG_FILE", +// TestData.ROLES_CONFIG_FILE.getFilename()); + } + + @After + public void tearDown() throws Exception { + Files.deleteIfExists(concurrentUsers.toPath()); + Files.deleteIfExists(concurrentEditUsers.toPath()); + } + + @Test + public void testGetUsersNoFile() throws Exception { + UserManager userManager = new UserManager(noFile); + List<EcompUser> users = userManager.getUsers(); + + assertThat(users, empty()); + } + + @Test + public void testConcurrentPush() throws Exception { + Callable<EcompUser> pushTask = () -> { + return pushTask(concurrentUsers, String.valueOf(NodeUtils.getRandomTxnId())); + }; + + List<Callable<EcompUser>> callables = Arrays.asList(pushTask, pushTask, pushTask, pushTask, + pushTask); + + ExecutorService executor = Executors.newWorkStealingPool(); + executor.invokeAll(callables).stream().map(future -> { + try { + return future.get(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }); + + UserManager userManager = new UserManager(concurrentUsers); + assertThat(userManager.getUsers().size(), is(5)); + } + + @Test + public void testConcurrentPushAndEdit() throws Exception { + Callable<EcompUser> pushTaskRandomId = () -> { + return pushTask(concurrentEditUsers, String.valueOf(NodeUtils.getRandomTxnId())); + }; + + Callable<EcompUser> pushTaskId3 = () -> { + return pushTask(concurrentEditUsers, LOGINID_3); + }; + + Callable<EcompUser> editTaskId1 = () -> { + return editTask(LOGINID_1, "Bob"); + }; + + Callable<EcompUser> editTaskId2 = () -> { + return editTask(LOGINID_2, "Jen"); + }; + + Callable<EcompUser> editTaskId3 = () -> { + return editTask(LOGINID_3, "Amy"); + }; + + 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 -> { + try { + return future.get(); + } catch (Exception e) { + throw new IllegalStateException(e); + } + }).collect(Collectors.toList()); + + assertThat(userTasks.size(), is(9)); + + UserManager userManager = new UserManager(concurrentEditUsers); + assertThat(userManager.getUsers().size(), is(8)); + assertThat(userManager.getUser(LOGINID_1).get().getFirstName(), is("Bob")); + assertThat(userManager.getUser(LOGINID_2).get().getFirstName(), is("Jen")); + assertThat(userManager.getUser(LOGINID_3).get().getFirstName(), is("Amy")); + } + + private EcompUser pushTask(File fileStore, String loginId) throws IOException { + UserManager userManager = new UserManager(fileStore); + EcompUser user = new EcompUser(); + user.setLoginId(loginId); + userManager.pushUser(user); + return user; + } + + private EcompUser editTask(String loginId, String firstName) throws IOException { + UserManager userManager = new UserManager(concurrentEditUsers); + EcompUser user = new EcompUser(); + user.setLoginId(loginId); + user.setFirstName(firstName); + userManager.editUser(loginId, user); + return user; + } +}
\ No newline at end of file diff --git a/src/test/java/org/openecomp/sparky/synchronizer/AsyncRateControlTester.java b/src/test/java/org/openecomp/sparky/synchronizer/AsyncRateControlTester.java new file mode 100644 index 0000000..e52995d --- /dev/null +++ b/src/test/java/org/openecomp/sparky/synchronizer/AsyncRateControlTester.java @@ -0,0 +1,245 @@ +/* +* ============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.openecomp.sparky.synchronizer; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.openecomp.sparky.synchronizer.config.TaskProcessorConfig; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * The Class AsyncRateControlTester. + */ +public class AsyncRateControlTester { + + private static Logger logger = LoggerFactory.getLogger(AsyncRateControlTester.class); + + private long startTimeInMs; + + private AtomicInteger counter; + + protected boolean syncInProgress; + + /** + * Instantiates a new async rate control tester. + * + * @throws Exception the exception + */ + public AsyncRateControlTester() throws Exception { + + TaskProcessorConfig tpc = new TaskProcessorConfig(); + + tpc.setMaxConcurrentWorkers(1); + tpc.setTransactionRateControllerEnabled(false); + tpc.setNumSamplesPerThreadForRunningAverage(100); + tpc.setTargetTps(0.25); + + tpc.setBytesHistogramLabel("bytesHistoLabel"); + tpc.setBytesHistogramMaxYAxis(1000000); + tpc.setBytesHistogramNumBins(20); + tpc.setBytesHistogramNumDecimalPoints(2); + + tpc.setQueueLengthHistogramLabel("queueHistoLabel"); + tpc.setQueueLengthHistogramMaxYAxis(1000000); + tpc.setQueueLengthHistogramNumBins(20); + tpc.setQueueLengthHistogramNumDecimalPoints(2); + + // ZeroDelayProcessor zdp = new ZeroDelayProcessor(LinkProcessorType.AAI, tpc); + // zdp.setStatCollector(this.aaiStatCollector); + /* + * zdp.setTaskProcessorConfig(tpc); + * + * this.resolver.registerProcessor(zdp); this.resolver.registerEventListener(this); this.counter + * = new AtomicInteger(0); this.syncInProgress = false; } + * + * @Override public void handleEvent(AsyncEvent event) { + * + * if(event.getEventType() == AsyncEventType.RESOLVER_IDLE) { + * + * if(syncInProgress) { long duration = System.currentTimeMillis() - startTimeInMs; + * System.out.println(getStatReport(duration)); syncInProgress = false; } + * + * // shutdown(); } else if(event.getEventType() == AsyncEventType.TRANSACTION_PROCESSED) { + * + * this.syncInProgress = true; + * + * ExternalResource resource = (ExternalResource)event.getPayload(); + * + * //aaiStatCollector.updateCounters(resource); + * + * counter.incrementAndGet(); + * + * } + * + * }; + * + * public void shutdown() { resolver.shutdown(); } + * + * private int getCounterValue(AtomicInteger counter) { + * + * if(counter == null) { return 0; } + * + * return counter.get(); } + * + * private void addActiveInventoryStatReport(StringBuilder sb) { + * + * if(sb == null) { return; } + * + * sb.append("\n\n ").append(LinkProcessorType.AAI.name()); + * + * sb.append("\n\n ").append("REST Operational Stats:"); + * + * /* Map<String, AtomicInteger> procOperationalCounters = + * aaiStatCollector.getActiveInventoryOperationalCounters(); + * + * if(procOperationalCounters != null) { + * + * int _1XX = + * getCounterValue(procOperationalCounters.get(ActiveInventoryStatCollector.GET_1XX)); int _2XX + * = getCounterValue(procOperationalCounters.get(ActiveInventoryStatCollector.GET_2XX)); int + * _3XX = getCounterValue(procOperationalCounters.get(ActiveInventoryStatCollector.GET_3XX)); + * int _4XX = + * getCounterValue(procOperationalCounters.get(ActiveInventoryStatCollector.GET_4XX)); int _5XX + * = getCounterValue(procOperationalCounters.get(ActiveInventoryStatCollector.GET_5XX)); int + * _6XX = getCounterValue(procOperationalCounters.get(ActiveInventoryStatCollector.GET_6XX)); + * + * sb.append("\n ").append(String.format( + * "%-12s 1XX: %-12d 2XX: %-12d 3XX: %-12d 4XX: %-12d 5XX: %-12d 6XX: %-12d ", HttpMethod.GET, + * _1XX, _2XX, _3XX, _4XX, _5XX, _6XX)); } + */ + + // sb.append("\n\n ").append("Entity Stats:"); + + /* + * sort entities, then sort nested op codes + */ + + /* + * TreeMap<String, HashMap<String, AtomicInteger>> activeInventoryEntitySortedTreeMap = new + * TreeMap<String, HashMap<String, AtomicInteger>>( new Comparator<String>() { + * + * public int compare(String o1, String o2) { return + * o1.toLowerCase().compareTo(o2.toLowerCase()); } }); + */ + + /* + * activeInventoryEntitySortedTreeMap.putAll(aaiStatCollector.getActiveInventoryEntityCounters() + * ); + * + * for(String counterEntityKey : activeInventoryEntitySortedTreeMap.keySet()) { + * + * HashMap<String, AtomicInteger> entityCounters = + * activeInventoryEntitySortedTreeMap.get(counterEntityKey); + * + * AtomicInteger total = entityCounters.get(ActiveInventoryStatCollector.TOTAL); AtomicInteger + * found = entityCounters.get(ActiveInventoryStatCollector.FOUND); AtomicInteger notFound = + * entityCounters.get(ActiveInventoryStatCollector.NOT_FOUND); AtomicInteger error = + * entityCounters.get(ActiveInventoryStatCollector.ERROR); + * + * int totalValue = (total == null) ? 0 : total.get(); int foundValue = (found == null) ? 0 : + * found.get(); int notFoundValue = (found == null) ? 0 : notFound.get(); int errorValue = + * (error == null) ? 0 : error.get(); + * + * sb.append("\n ").append(String.format( + * "%-30s TOTAL: %-12d FOUND: %-12d NOT_FOUND: %-12d ERROR: %-12d", counterEntityKey, + * totalValue, foundValue, notFoundValue, errorValue)); + * + * } + */ + + // sb.append("\n\n ").append("Task Processor Stats:"); + + // int totalRetries = + // getCounterValue(procOperationalCounters.get(ActiveInventoryStatCollector.NUM_RETRIES)); + // int currentQueueLength = resolver.getCurrentQueueLength(LinkProcessorType.AAI.name()); + + /* + * sb.append("\n " + * ).append(resolver.getProcessorTaskAgeStats(LinkProcessorType.AAI.name(), false, " " + * )); sb.append("\n " + * ).append(resolver.getProcessorResponseStats(LinkProcessorType.AAI.name(), false, " " + * )); sb.append("\n") + * .append(resolver.getQueueItemLengthHistogram(LinkProcessorType.AAI.name(), false, + * " ")); sb.append("\n") + * .append(resolver.getResponseByteSizeHistogram(LinkProcessorType.AAI.name(), false, + * " ")); sb.append("\n " + * ).append("TPS=").append(resolver.getTPS(LinkProcessorType.AAI.name())).append(", NumRetries=" + * ).append(totalRetries) .append(", CurrentQueueLength=").append(currentQueueLength); + */ + /* + * } + * + * private String getStatReport(long syncOpTimeInMs) { + * + * StringBuilder sb = new StringBuilder(128); + * + * sb.append("\n").append("Async Resolver Statistics: ( Sync Operation Duration = " + + * NodeUtils.getDurationBreakdown(syncOpTimeInMs) + " )"); + * + * addActiveInventoryStatReport(sb); + * + * return sb.toString(); + * + * } + * + * public void loadResolver(int numItems) { + * + * if(numItems <= 0) { return; } + * + * startTimeInMs = System.currentTimeMillis(); + * + * DummyPerformanceTask dpt = null; + * + * for(int i = 0; i < numItems; i++) { + * + * dpt = new DummyPerformanceTask(); dpt.setLinkProcessorType(LinkProcessorType.AAI); + * dpt.setResourceEntityType("DummyPerformanceEntity"); dpt.setOperationType(HttpMethod.GET); + * + * resolver.resolve(dpt); + * + * } + * + * } + * + * public static void main(String[] args) throws Exception { + * + * System.getProperties().setProperty("AJSC_HOME", "x:\\aaiui\\"); + * + * System.out.println("Available processors = " + Runtime.getRuntime().availableProcessors()); + * + * AsyncRateControlTester arcTester = new AsyncRateControlTester(); + * + * // give us time to instrument the jvm with jvisualvm // Thread.sleep(30000); + * Thread.sleep(5000); + * + * arcTester.loadResolver(1000); + * + * + * } + */ + } +} diff --git a/src/test/java/org/openecomp/sparky/synchronizer/IndexDocumentTest.java b/src/test/java/org/openecomp/sparky/synchronizer/IndexDocumentTest.java new file mode 100644 index 0000000..0f03f81 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/synchronizer/IndexDocumentTest.java @@ -0,0 +1,107 @@ +/* +* ============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.openecomp.sparky.synchronizer; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.Mockito; +import org.openecomp.sparky.config.oxm.OxmModelLoader; +import org.openecomp.sparky.util.LogValidator; +import org.powermock.modules.junit4.PowerMockRunner; + +import ch.qos.logback.classic.Level; + + +/** + * The Class IndexDocumentTest. + */ +@RunWith(PowerMockRunner.class) +public class IndexDocumentTest { + + private LogValidator logValidator; + private OxmModelLoader oxmModelLoader; + + /** + * Inits the. + * + * @throws Exception the exception + */ + @Before + public void init() throws Exception { + logValidator = new LogValidator(); + logValidator.initializeLogger(Level.WARN); + oxmModelLoader = Mockito.mock(OxmModelLoader.class); + } + + /** + * Validate basic construction. + * + * @throws NoSuchAlgorithmException the no such algorithm exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void validateBasicConstruction() throws NoSuchAlgorithmException, IOException { + + /* + * String testDate = "2016-12-21 00:00:00.00"; OxmEntityDescriptor d = new + * OxmEntityDescriptor(); d.setEntityName("service-instance"); + * d.setPrimaryKeyAttributeName(Arrays.asList("service-instance-id")); + * d.setSearchableAttributes(Arrays.asList("service-instance-id")); + * + * Mockito.when(oxmModelLoader.getEntityDescriptor(anyString())).thenReturn(d); + * + * SearchableEntity id1 = new SearchableEntity(oxmModelLoader); + * + * id1.setEntityType("service-instance"); id1.setEntityPrimaryKeyValue("DUP2"); + * id1.addSearchTagWithIdx("DUP2", String.valueOf(1)); + * + * id1.deriveFields(); id1.setEntityTimeStamp(testDate); ObjectMapper mapper = new + * ObjectMapper(); + * + * String objStr = id1.getIndexDocumentJson(); + * + * JsonNode indexDocNode = mapper.readTree(objStr); + * + * /// + * + * ObjectNode expectedNode = mapper.createObjectNode(); expectedNode.put("entityType", + * "service-instance"); expectedNode.put("entityPrimaryKeyValue", "DUP2"); + * expectedNode.put("searchTagIDs", "1"); expectedNode.put("searchTags", "DUP2"); + * expectedNode.put("crossEntityReferenceValues", ""); expectedNode.put("lastmodTimestamp", + * testDate); + * + * assertTrue(NodeUtils.isEqual(expectedNode, indexDocNode)); // Test if the timestamp is + * calculated when the node is being created + * assertTrue(NodeUtils.getNodeFieldAsText(indexDocNode, "lastmodTimestamp") != null); + */ + + } + +} diff --git a/src/test/java/org/openecomp/sparky/synchronizer/SyncControllerBuilder.java b/src/test/java/org/openecomp/sparky/synchronizer/SyncControllerBuilder.java new file mode 100644 index 0000000..45c272b --- /dev/null +++ b/src/test/java/org/openecomp/sparky/synchronizer/SyncControllerBuilder.java @@ -0,0 +1,581 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.synchronizer; + +import org.openecomp.sparky.dal.aai.ActiveInventoryAdapter; +import org.openecomp.sparky.dal.aai.config.ActiveInventoryConfig; +import org.openecomp.sparky.dal.cache.InMemoryEntityCache; +import org.openecomp.sparky.dal.cache.PersistentEntityCache; +import org.openecomp.sparky.dal.elasticsearch.ElasticSearchAdapter; +import org.openecomp.sparky.dal.elasticsearch.ElasticSearchDataProvider; +import org.openecomp.sparky.dal.elasticsearch.config.ElasticSearchConfig; +import org.openecomp.sparky.dal.rest.OperationResult; +import org.openecomp.sparky.dal.rest.RestClientBuilder; +import org.openecomp.sparky.dal.rest.RestfulDataAccessor; +import org.openecomp.sparky.synchronizer.SyncController.SyncActions; +import org.openecomp.sparky.synchronizer.enumeration.SynchronizerState; +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.Level; + +/** + * The Class SyncControllerBuilder. + */ +public class SyncControllerBuilder { + + /** + * Do master entity sync. + */ + public void doMasterEntitySync() { + + } + + /** + * 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); + */ + + + + } 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 SyncController("historicalEntityTestController"); + + ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new RestClientBuilder()); + aaiAdapter.setCacheEnabled(false); + + 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); + */ + + //// + + /* + * 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 RestClientBuilder()); + + aaiAdapter.setCacheEnabled(true); + + InMemoryEntityCache aaiInMemoryCache = new InMemoryEntityCache(); + aaiAdapter.setEntityCache(aaiInMemoryCache); + + /* + * PersistentEntityCache aaiDiskCache = new PersistentEntityCache(); + * aaiAdapter.setEntityCache(aaiDiskCache); + */ + + 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 SyncController("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 RestClientBuilder()); + + aaiAdapter.setCacheEnabled(true); + + /* + * InMemoryEntityCache aaiInMemoryCache = new InMemoryEntityCache(); + * aaiAdapter.setEntityCache(aaiInMemoryCache); + */ + + PersistentEntityCache aaiDiskCache = new PersistentEntityCache(); + aaiAdapter.setEntityCache(aaiDiskCache); + + 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 SyncController("searchtableEntityTestController"); + + SearchableEntitySynchronizer ses = + new SearchableEntitySynchronizer("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 RestClientBuilder()); + + aaiAdapter.setCacheEnabled(true); + + /* + * InMemoryEntityCache aaiInMemoryCache = new InMemoryEntityCache(); + * aaiAdapter.setEntityCache(aaiInMemoryCache); + */ + + PersistentEntityCache aaiDiskCache = new PersistentEntityCache(); + aaiAdapter.setEntityCache(aaiDiskCache); + + 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 SyncController("crossEntityRefSyncController"); + + CrossEntityReferenceSynchronizer cers = + new CrossEntityReferenceSynchronizer("entitysearchindex-localhost", ActiveInventoryConfig.getConfig()); + cers.setAaiDataProvider(aaiAdapter); + cers.setEsDataProvider(esAdapter); + syncController.registerEntitySynchronizer(cers); + + SearchableEntitySynchronizer ses = + new SearchableEntitySynchronizer("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 RestClientBuilder()); + + aaiAdapter.setCacheEnabled(true); + + /* + * InMemoryEntityCache aaiInMemoryCache = new InMemoryEntityCache(); + * aaiAdapter.setEntityCache(aaiInMemoryCache); + */ + + PersistentEntityCache aaiDiskCache = new PersistentEntityCache(); + aaiAdapter.setEntityCache(aaiDiskCache); + + 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 SyncController("suggestionEntityTestController"); + + AutosuggestionSynchronizer ses = + new AutosuggestionSynchronizer("suggestionentityindex-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()); + } + } + + /* + * Do no op sync. + */ + public void doNoOpSync() { + try { + SyncController syncController = new SyncController("noopSyncTestController"); + + /* + * ActiveInventoryAdapter aaiAdapter = new ActiveInventoryAdapter(new RestClientBuilder()); + * + * aaiAdapter.setCacheEnabled(true); + * + * /*InMemoryEntityCache aaiInMemoryCache = new InMemoryEntityCache(); + * aaiAdapter.setEntityCache(aaiInMemoryCache); + */ + + /* + * 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. + * + * @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("AJSC_HOME", "d:\\AAI\\tier_support_ui\\tier-support-ui\\target\\swm\\package\\nix\\dist_files\\appl\\inventory-ui-service\\1.0-SNAPSHOT"); + + ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory + .getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); + // root.detachAndStopAllAppenders(); + // logger = new CaptureLoggerAppender(); + root.setLevel(Level.INFO); + // root.addAppender(logger); + + + SyncControllerBuilder syncBuilder = new SyncControllerBuilder(); + + /* + * if (runSearchableEntitySync) syncBuilder.doSearchableEntitysync(); + */ + + //syncBuilder.doSearchableEntitysync(); + // syncBuilder.doCrossEntityReferenceSync(); + // syncBuilder.doHistoricalEntitySync(); + // syncBuilder.doGeoEntitySync(); + syncBuilder.doSuggestionEntitySync(); + + // syncBuilder.testElasticSearchUpdateAPI(); + + /* + * if (runGeoEntitySync) { syncBuilder.doGeoEntitySync(); } + */ + + + + } +} diff --git a/src/test/java/org/openecomp/sparky/util/CaptureLoggerAppender.java b/src/test/java/org/openecomp/sparky/util/CaptureLoggerAppender.java new file mode 100644 index 0000000..ec23544 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/util/CaptureLoggerAppender.java @@ -0,0 +1,247 @@ +/* +* ============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.openecomp.sparky.util; + +import java.util.ArrayList; +import java.util.Deque; +import java.util.List; +import java.util.concurrent.ConcurrentLinkedDeque; + +import ch.qos.logback.classic.spi.LoggingEvent; +import ch.qos.logback.core.Appender; +import ch.qos.logback.core.Context; +import ch.qos.logback.core.LogbackException; +import ch.qos.logback.core.filter.Filter; +import ch.qos.logback.core.spi.FilterReply; +import ch.qos.logback.core.status.Status; + +/** + * A test class used to provide a concrete log stub of the Log4j API interface. The goal is to + * transparently capture logging paths so we can add log validation during the junit validation + * without post-analyzing on-disk logs. + * + * @author DAVEA + * + */ +@SuppressWarnings("rawtypes") +public class CaptureLoggerAppender implements Appender { + + private Deque<LoggingEvent> capturedLogs; + + /** + * Instantiates a new capture logger appender. + */ + public CaptureLoggerAppender() { + capturedLogs = new ConcurrentLinkedDeque<LoggingEvent>(); + } + + /** + * Drain all logs. + * + * @return the list + */ + public List<LoggingEvent> drainAllLogs() { + List<LoggingEvent> loggingEvents = new ArrayList<LoggingEvent>(); + + LoggingEvent event = null; + + while (capturedLogs.peek() != null) { + event = capturedLogs.pop(); + loggingEvents.add(event); + } + + return loggingEvents; + } + + /** + * Clears the capture logs double-ended queue and returns the size of the queue before it was + * cleared. + * + * @return int numCapturedLogs + */ + public int clearAllLogs() { + int numCapturedLogs = capturedLogs.size(); + capturedLogs.clear(); + return numCapturedLogs; + } + + + + /* (non-Javadoc) + * @see ch.qos.logback.core.spi.LifeCycle#start() + */ + @Override + public void start() {} + + /* (non-Javadoc) + * @see ch.qos.logback.core.spi.LifeCycle#stop() + */ + @Override + public void stop() {} + + @Override + public boolean isStarted() { + // TODO Auto-generated method stub + System.out.println("isStarted"); + return false; + } + + @Override + public void setContext(Context context) { + // TODO Auto-generated method stub + System.out.println("setContext"); + + } + + @Override + public Context getContext() { + // TODO Auto-generated method stub + System.out.println("getContext"); + return null; + } + + /* (non-Javadoc) + * @see ch.qos.logback.core.spi.ContextAware#addStatus(ch.qos.logback.core.status.Status) + */ + @Override + public void addStatus(Status status) { + // TODO Auto-generated method stub + System.out.println("addStatus"); + } + + /* (non-Javadoc) + * @see ch.qos.logback.core.spi.ContextAware#addInfo(java.lang.String) + */ + @Override + public void addInfo(String msg) { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see ch.qos.logback.core.spi.ContextAware#addInfo(java.lang.String, java.lang.Throwable) + */ + @Override + public void addInfo(String msg, Throwable ex) { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see ch.qos.logback.core.spi.ContextAware#addWarn(java.lang.String) + */ + @Override + public void addWarn(String msg) { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see ch.qos.logback.core.spi.ContextAware#addWarn(java.lang.String, java.lang.Throwable) + */ + @Override + public void addWarn(String msg, Throwable ex) { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see ch.qos.logback.core.spi.ContextAware#addError(java.lang.String) + */ + @Override + public void addError(String msg) { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see ch.qos.logback.core.spi.ContextAware#addError(java.lang.String, java.lang.Throwable) + */ + @Override + public void addError(String msg, Throwable ex) { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see ch.qos.logback.core.spi.FilterAttachable#addFilter(ch.qos.logback.core.filter.Filter) + */ + @Override + public void addFilter(Filter newFilter) { + // TODO Auto-generated method stub + + } + + /* (non-Javadoc) + * @see ch.qos.logback.core.spi.FilterAttachable#clearAllFilters() + */ + @Override + public void clearAllFilters() { + // TODO Auto-generated method stub + + } + + @Override + public List getCopyOfAttachedFiltersList() { + // TODO Auto-generated method stub + return null; + } + + /* (non-Javadoc) + * @see ch.qos.logback.core.spi.FilterAttachable#getFilterChainDecision(java.lang.Object) + */ + @Override + public FilterReply getFilterChainDecision(Object event) { + // TODO Auto-generated method stub + return null; + } + + @Override + public String getName() { + // TODO Auto-generated method stub + System.out.println("getName"); + return "MOCK"; + } + + /* (non-Javadoc) + * @see ch.qos.logback.core.Appender#doAppend(java.lang.Object) + */ + @Override + public void doAppend(Object event) throws LogbackException { + // TODO Auto-generated method stub + // System.out.println("doAppend(), event = " + event); + // System.out.println("event class = " + event.getClass().getSimpleName()); + capturedLogs.add((LoggingEvent) event); + } + + @Override + public void setName(String name) { + // TODO Auto-generated method stub + System.out.println("setName() name = " + name); + + } + +} diff --git a/src/test/java/org/openecomp/sparky/util/ElasticEntitySummarizer.java b/src/test/java/org/openecomp/sparky/util/ElasticEntitySummarizer.java new file mode 100644 index 0000000..9709bb8 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/util/ElasticEntitySummarizer.java @@ -0,0 +1,173 @@ +/* +* ============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.openecomp.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.openecomp.sparky.config.oxm.OxmModelLoader; +import org.openecomp.sparky.dal.elasticsearch.config.ElasticSearchConfig; +import org.openecomp.sparky.dal.exception.ElasticSearchOperationException; +import org.openecomp.sparky.dal.rest.RestDataProvider; +import org.openecomp.sparky.synchronizer.config.TaskProcessorConfig; + +/** + * 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(OxmModelLoader loader) throws Exception { + + + elasticConfig = new ElasticSearchConfig(); + TaskProcessorConfig tpc = new TaskProcessorConfig(); + elasticConfig.setProcessorConfig(tpc); + + 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/openecomp/sparky/util/ElasticGarbageInjector.java b/src/test/java/org/openecomp/sparky/util/ElasticGarbageInjector.java new file mode 100644 index 0000000..dc47713 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/util/ElasticGarbageInjector.java @@ -0,0 +1,170 @@ +/* +* ============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.openecomp.sparky.util; + +import java.util.concurrent.atomic.AtomicInteger; + +import org.openecomp.sparky.dal.elasticsearch.config.ElasticSearchConfig; +import org.openecomp.sparky.dal.rest.RestDataProvider; +import org.openecomp.sparky.synchronizer.config.TaskProcessorConfig; + +/** + * The Class ElasticGarbageInjector. + */ +public class ElasticGarbageInjector { + + + private AtomicInteger counter; + private long startTimeInMs; + private int progressStep; + + /** + * The Enum ActiveInventoryEntities. + */ + private enum ActiveInventoryEntities { + + COMPLEX("complex"), CUSTOMER("customer"), GENERIC_VNF("generic-vnf"), NEWVCE("newvce"), PSERVER( + "pserver"), SERVICE_INSTANCE("service-instance"), VCE("vce"), VPE("vpe"), VSERVER( + "vserver"); + + private final String entityName; + + /** + * Instantiates a new active inventory entities. + * + * @param name the name + */ + private ActiveInventoryEntities(String name) { + this.entityName = name; + } + + public String getEntityName() { + return entityName; + } + + } + + /** + * Instantiates a new elastic garbage injector. + * + * @throws Exception the exception + */ + public ElasticGarbageInjector() throws Exception { + + this.counter = new AtomicInteger(0); + + ElasticSearchConfig elasticConfig = new ElasticSearchConfig(); + + TaskProcessorConfig tpc = new TaskProcessorConfig(); + + tpc.setMaxConcurrentWorkers(5); + tpc.setTransactionRateControllerEnabled(false); + tpc.setNumSamplesPerThreadForRunningAverage(100); + tpc.setTargetTps(100.0); + + tpc.setBytesHistogramLabel("bytesHistoLabel"); + tpc.setBytesHistogramMaxYAxis(1000000); + tpc.setBytesHistogramNumBins(20); + tpc.setBytesHistogramNumDecimalPoints(2); + + tpc.setQueueLengthHistogramLabel("queueHistoLabel"); + tpc.setQueueLengthHistogramMaxYAxis(1000000); + tpc.setQueueLengthHistogramNumBins(20); + tpc.setQueueLengthHistogramNumDecimalPoints(2); + + RestDataProvider syncAdapter = null; + // syncAdapter.setTaskProcessorConfig(tpc); + + } + + // @Override + /* + * public void handleEvent(AsyncEvent event) { + * + * if(event.getEventType() == AsyncEventType.RESOLVER_IDLE) { System.out.println("All Done!"); + * resolver.shutdown(); } + * + * + * + * if(event.getEventType() == AsyncEventType.TRANSACTION_PROCESSED) { + * + * + * if ( event.getPayload() instanceof SyncTask) { + * + * counter.incrementAndGet(); + * + * SyncTask ers = (SyncTask)event.getPayload(); + * + * OperationResult or = ers.getResult(); + * + * if ( or.wasSuccessful() ) { //System.out.println("Garbaged injected successfully"); }else { + * System.out.println(ers.getResult().toString()); } + * + * if ( counter.get() % progressStep == 0) { + * + * long duration = System.currentTimeMillis() - startTimeInMs; double tps = ( duration / + * counter.get() ); System.out.println("Currently inserting doc at index = " + counter.get() + + * ", current TPS = " + tps ); } + * + * } + * + * } } + * + * public void injectGarbage(int numGarbageDocs, String baseUrl) { + * + * IndexDocument d = null; SyncTask syncTask = null; Random r = new Random(); + * + * startTimeInMs = System.currentTimeMillis(); this.progressStep = (numGarbageDocs/5); if ( + * this.progressStep == 0 ) { this.progressStep = 1; } int numEntities = + * ActiveInventoryEntities.values().length; + * + * for(int i = 0; i < numGarbageDocs; i++) { d = new IndexDocument(OXMModelLoader.getInstance()); + * d.setId(UUID.randomUUID().toString()); + * d.setEntityType(ActiveInventoryEntities.values()[r.nextInt(numEntities)].getEntityName()); + * + * String link = baseUrl + d.getId(); syncTask = new SyncTask(d, link); + * syncTask.setResourceEntityType(d.getEntityType()); + * syncTask.setPayload(d.getIndexDocumentJson()); + * + * resolver.resolve(syncTask); } + * + * } + * + * public static void main(String[] args) throws Exception { + * + * //System.getProperties().setProperty("AJSC_HOME", "X:\\aaiui\\"); + * + * ElasticGarbageInjector sync = new ElasticGarbageInjector(); + * + * //int numEntries = Integer.parseInt(args[0]); //String baseUrl = args[1]; + * + * //sync.injectGarbage(numEntries,baseUrl); + * sync.injectGarbage(10000,"http://localhost:9200/entitysearchindex-localhost/default/"); + * + * } + */ + +} diff --git a/src/test/java/org/openecomp/sparky/util/ExceptionHelper.java b/src/test/java/org/openecomp/sparky/util/ExceptionHelper.java new file mode 100644 index 0000000..6f647c7 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/util/ExceptionHelper.java @@ -0,0 +1,62 @@ +/* +* ============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.openecomp.sparky.util; + +/** + * The Class ExceptionHelper. + */ +public class ExceptionHelper { + + /** + * Extract stack trace elements. + * + * @param maxNumberOfElementsToCapture the max number of elements to capture + * @param exc the exc + * @return the string + */ + public static String extractStackTraceElements(int maxNumberOfElementsToCapture, Exception exc) { + StringBuilder sb = new StringBuilder(128); + + StackTraceElement[] stackTraceElements = exc.getStackTrace(); + + if (stackTraceElements != null) { + + /* + * We want to avoid an index out-of-bounds error, so we will make sure to only extract the + * number of frames from the stack trace that actually exist. + */ + + int numFramesToExtract = Math.min(maxNumberOfElementsToCapture, stackTraceElements.length); + + for (int x = 0; x < numFramesToExtract; x++) { + sb.append(stackTraceElements[x]).append("\n"); + } + + } + + return sb.toString(); + } +} diff --git a/src/test/java/org/openecomp/sparky/util/HttpServletHelper.java b/src/test/java/org/openecomp/sparky/util/HttpServletHelper.java new file mode 100644 index 0000000..cf3933a --- /dev/null +++ b/src/test/java/org/openecomp/sparky/util/HttpServletHelper.java @@ -0,0 +1,161 @@ +/* +* ============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.openecomp.sparky.util; + +import static org.junit.Assert.fail; + +import java.io.BufferedReader; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringReader; +import java.nio.charset.StandardCharsets; +import java.util.Collections; +import java.util.Map; + +import javax.servlet.ReadListener; +import javax.servlet.ServletInputStream; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.mockito.Mockito; + +/** + * The Class HttpServletHelper. + */ +public class HttpServletHelper { + + public static HttpServletRequest getMockHttpServletRequest() { + return Mockito.mock(HttpServletRequest.class); + } + + /** + * Sets the request payload. + * + * @param request the request + * @param mimeType the mime type + * @param payloadContent the payload content + */ + public static void setRequestPayload(HttpServletRequest request, String mimeType, + String payloadContent) { + + try { + Mockito.when(request.getContentType()).thenReturn(mimeType); + + + final ByteArrayInputStream bais = + new ByteArrayInputStream(payloadContent.getBytes(StandardCharsets.UTF_8)); + + ServletInputStream servletInputStream = new ServletInputStream() { + + @Override + public int read() throws IOException { + return bais.read(); + } + + @Override + public boolean isFinished() { + return true; + } + + @Override + public boolean isReady() { + return true; + } + + @Override + public void setReadListener(ReadListener readListener) { + // TODO Auto-generated method stub + + } + }; + + Mockito.when(request.getInputStream()).thenReturn(servletInputStream); + Mockito.when(request.getReader()).thenReturn(new BufferedReader(new StringReader(payloadContent))); + + } catch (IOException ioe) { + fail(ExceptionHelper.extractStackTraceElements(5, ioe)); + } + + } + + /** + * Gets the mock http servlet response. + * + * @param printWriter the print writer + * @return the mock http servlet response + */ + public static HttpServletResponse getMockHttpServletResponse(PrintWriter printWriter) { + HttpServletResponse commonResponse = Mockito.mock(HttpServletResponse.class); + + /* + * Use the StringWriter wrapped in a PrintWriter to redirect output stream to an in-memory + * buffer instead of an on-disk file. + */ + + try { + Mockito.when(commonResponse.getWriter()).thenReturn(printWriter); + } catch (IOException ioe) { + fail(ExceptionHelper.extractStackTraceElements(5, ioe)); + } + + return commonResponse; + } + + /** + * Assign request uri. + * + * @param req the req + * @param requestUri the request uri + */ + public static void assignRequestUri(HttpServletRequest req, String requestUri) { + Mockito.when(req.getRequestURI()).thenReturn(requestUri); + } + + /** + * Assign request parameter name map. + * + * @param req the req + * @param paramNameValueMap the param name value map + */ + public static void assignRequestParameterNameMap(HttpServletRequest req, + Map<String, String> paramNameValueMap) { + if (paramNameValueMap != null) { + Mockito.when(req.getParameterNames()) + .thenReturn(Collections.enumeration(paramNameValueMap.keySet())); + + for (String key : paramNameValueMap.keySet()) { + Mockito.when(req.getParameter(key)).thenReturn(paramNameValueMap.get(key)); + } + + } + } + + public static void assignRequestHeader(HttpServletRequest req, String headerName, String headerValue) { + Mockito.when(req.getHeader(headerName)).thenReturn(headerValue); + } + +} diff --git a/src/test/java/org/openecomp/sparky/util/LogValidator.java b/src/test/java/org/openecomp/sparky/util/LogValidator.java new file mode 100644 index 0000000..0771ff1 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/util/LogValidator.java @@ -0,0 +1,85 @@ +/* +* ============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.openecomp.sparky.util; + +import java.util.List; + +import org.slf4j.LoggerFactory; + +import ch.qos.logback.classic.Level; +import ch.qos.logback.classic.spi.LoggingEvent; + +/** + * The Class LogValidator. + */ +public class LogValidator { + + protected CaptureLoggerAppender logger = null; + + /** + * Initialize logger. + * + * @param level the level + */ + @SuppressWarnings("unchecked") + public void initializeLogger(Level level) { + ch.qos.logback.classic.Logger root = (ch.qos.logback.classic.Logger) LoggerFactory + .getLogger(ch.qos.logback.classic.Logger.ROOT_LOGGER_NAME); + root.detachAndStopAllAppenders(); + logger = new CaptureLoggerAppender(); + root.setLevel(level); + root.addAppender(logger); + } + + public CaptureLoggerAppender getLogger() { + return logger; + } + + /** + * Dump and count logs. + * + * @param logToConsole the log to console + * @return the int + */ + public int dumpAndCountLogs(boolean logToConsole) { + + List<LoggingEvent> logs = logger.drainAllLogs(); + + if (logs == null) { + return 0; + } + + if (logToConsole) { + for (LoggingEvent e : logs) { + System.out.println(e); + } + } + + return logs.size(); + + } + +} diff --git a/src/test/java/org/openecomp/sparky/util/ModelLoaderTester.java b/src/test/java/org/openecomp/sparky/util/ModelLoaderTester.java new file mode 100644 index 0000000..6e2406c --- /dev/null +++ b/src/test/java/org/openecomp/sparky/util/ModelLoaderTester.java @@ -0,0 +1,46 @@ +/* +* ============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.openecomp.sparky.util; + +import org.openecomp.sparky.config.oxm.OxmModelLoader; + +/** + * The Class ModelLoaderTester. + */ +public class ModelLoaderTester { + + /** + * The main method. + * + * @param args the arguments + */ + public static void main(String[] args) { + System.getProperties().put("AJSC_HOME", "d:\\oxm\\"); + + OxmModelLoader loader = OxmModelLoader.getInstance(); + } + +} diff --git a/src/test/java/org/openecomp/sparky/util/NodeUtilsTest.java b/src/test/java/org/openecomp/sparky/util/NodeUtilsTest.java new file mode 100644 index 0000000..23d9df3 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/util/NodeUtilsTest.java @@ -0,0 +1,489 @@ +/* +* ============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.openecomp.sparky.util; + +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 static org.junit.Assert.fail; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; + +import javax.xml.stream.XMLStreamConstants; + +import org.json.JSONException; +import org.junit.Before; +import org.junit.Test; +import org.openecomp.sparky.dal.rest.OperationResult; + +import com.fasterxml.jackson.core.JsonProcessingException; + +/** + * The Class NodeUtilsTest. + */ +public class NodeUtilsTest { + + + private static final String TEST_LINK1 = + "https://aai-ext1.test.att.com:9292/aai/v7/network/generic-vnfs/generic-vnf/cafaeb02-b54d-4918-bd06-85406dad19e7/l-interfaces/l-interface/WAN1_1123_GAMMA2016.04_PWT/l3-interface-ipv4-address-list/155.196.36.1/"; + private static final String TEST_LINK2 = + "https://aai-ext1.test.att.com:9292/aai/v7/network/generic-vnfs/generic-vnf/cafaeb02-b54d-4918-bd06-85406dad19e7/l-interfaces/l-interface/WAN1_1123_GAMMA2016.04_PWT/l3-interface-ipv4-address-list/155.196.36.1"; + private static final String TEST_LINK3 = + "https://aai-ext1.test.att.com:9292/aai/v7/network/generic-vnfs/generic-vnf/cafaeb02-b54d-4918-bd06-85406dad19e7/l-interfaces/l-interface/WAN1_1123_GAMMA2016.04_PWT/l3-interface-ipv4-address-list/ge-0%2f1%2f0"; + private static final String TEST_LINK4 = + "https://aai-ext1.test.att.com:9292/aai/v7/network/generic-vnfs/generic-vnf/cafaeb02-b54d-4918-bd06-85406dad19e7/l-interfaces/l-interface/WAN1_1123_GAMMA2016.04_PWT/l3-interface-ipv4-address-list/ge-%bad%wolf%timelord"; + private static final String TEST_LINK5_NO_RESOURCE_ID = + "https://aai-ext1.test.att.com:9292/aai/v7/network/generic-vnfs/generic-vnf/cafaeb02-b54d-4918-bd06-85406dad19e7/l-interfaces/l-interface/WAN1_1123_GAMMA2016.04_PWT/l3-interface-ipv4-address-list//"; + private static final int NODE_UTILS_TAB_WIDTH = 3; + + /** + * Inits the. + * + * @throws Exception the exception + */ + @Before + public void init() throws Exception {} + + /* + * String buildDepthPadding(int depth) + */ + + /** + * Builds the depth padding with negative depth. + */ + @Test + public void buildDepthPaddingWithNegativeDepth() { + String paddingString = NodeUtils.buildDepthPadding(-1); + assertEquals(paddingString.length(), 0); + } + + /** + * Builds the depth padding with zero depth. + */ + @Test + public void buildDepthPaddingWithZeroDepth() { + String paddingString = NodeUtils.buildDepthPadding(0); + assertEquals(paddingString.length(), 0); + } + + /** + * Builds the depth padding with small depth. + */ + @Test + public void buildDepthPaddingWithSmallDepth() { + String paddingString = NodeUtils.buildDepthPadding(1); + assertEquals(paddingString.length(), NODE_UTILS_TAB_WIDTH * 1); + } + + /** + * Builds the depth padding with large depth. + */ + @Test + public void buildDepthPaddingWithLargeDepth() { + String paddingString = NodeUtils.buildDepthPadding(100); + assertEquals(paddingString.length(), NODE_UTILS_TAB_WIDTH * 100); + } + + /* + * String buildEntityResourceKey(String entityType, String resourceId) + */ + + /* + * TODO: we should probably throw an IllegalArgumentExecption or just return null if a required + * parameter is passed to us with a null. + */ + + /** + * Builds the entity resource key with null entity type. + */ + @Test + public void buildEntityResourceKeyWithNullEntityType() { + String resourceId = NodeUtils.buildEntityResourceKey(null, "generic-vnf-123"); + assertEquals(resourceId, "null.generic-vnf-123"); + } + + /** + * Builds the entity resource key with null resource id. + */ + @Test + public void buildEntityResourceKeyWithNullResourceId() { + String resourceId = NodeUtils.buildEntityResourceKey("generic-vnf", null); + assertEquals(resourceId, "generic-vnf.null"); + } + + /** + * Builds the entity resource key success path. + */ + @Test + public void buildEntityResourceKeySuccessPath() { + String resourceId = NodeUtils.buildEntityResourceKey("generic-vnf", "generic-vnf-123"); + assertEquals(resourceId, "generic-vnf.generic-vnf-123"); + } + + /* + * String extractResourceIdFromLink(String link) + */ + + /** + * Id extraction when url has trailing forward slash. + */ + @Test + public void idExtractionWhenUrlHasTrailingForwardSlash() { + + String resourceId = NodeUtils.extractResourceIdFromLink(TEST_LINK1); + + if (!"155.196.36.1".equals(resourceId)) { + fail("Failed to extract expected resourceId"); + } + } + + /** + * Id extraction when url does not have trailing forward slash. + */ + @Test + public void idExtractionWhenUrlDoesNotHaveTrailingForwardSlash() { + + String resourceId = NodeUtils.extractResourceIdFromLink(TEST_LINK2); + + if (!"155.196.36.1".equals(resourceId)) { + fail("Failed to extract expected resourceId"); + } + } + + /** + * Id extraction when url contains url encoded hex characters. + */ + @Test + public void idExtractionWhenUrlContainsUrlEncodedHexCharacters() { + + String resourceId = NodeUtils.extractResourceIdFromLink(TEST_LINK3); + + if (!"ge-0/1/0".equals(resourceId)) { + fail("Failed to extract expected resourceId"); + } + + } + + /** + * Id extraction when url contains non standard hex characters. + */ + @Test + public void idExtractionWhenUrlContainsNonStandardHexCharacters() { + + String resourceId = NodeUtils.extractResourceIdFromLink(TEST_LINK4); + + /* + * This is not an expected hex encoding, so the decode will fail and the original parameter will + * be returned instead. + */ + + if (!"ge-%bad%wolf%timelord".equals(resourceId)) { + fail("Failed to extract expected resourceId"); + } + + } + + /** + * Id extraction when url is null. + */ + @Test + public void idExtractionWhenUrlIsNull() { + String resourceId = NodeUtils.extractResourceIdFromLink(null); + assertEquals(null, resourceId); + } + + /** + * Id extraction when url is empty string. + */ + @Test + public void idExtractionWhenUrlIsEmptyString() { + String resourceId = NodeUtils.extractResourceIdFromLink(""); + assertEquals(null, resourceId); + } + + /* + * String getXMLStreamConstantAsStr(int c) + */ + + /** + * Test string conversion of xml stream constants. + */ + @Test + public void testStringConversionOfXmlStreamConstants() { + + /* + * Range of enum is 0 - 256 + */ + + for (int id = 0; id <= 256; id++) { + + switch (id) { + case XMLStreamConstants.ATTRIBUTE: { + assertEquals("ATTRIBUTE", NodeUtils.getXmlStreamConstantAsStr(id)); + break; + } + + case XMLStreamConstants.CDATA: { + assertEquals("CDATA", NodeUtils.getXmlStreamConstantAsStr(id)); + break; + } + + case XMLStreamConstants.CHARACTERS: { + assertEquals("CHARACTERS", NodeUtils.getXmlStreamConstantAsStr(id)); + break; + } + + case XMLStreamConstants.COMMENT: { + assertEquals("COMMENT", NodeUtils.getXmlStreamConstantAsStr(id)); + break; + } + + case XMLStreamConstants.DTD: { + assertEquals("DTD", NodeUtils.getXmlStreamConstantAsStr(id)); + break; + } + + case XMLStreamConstants.END_DOCUMENT: { + assertEquals("END_DOCUMENT", NodeUtils.getXmlStreamConstantAsStr(id)); + break; + } + + case XMLStreamConstants.END_ELEMENT: { + assertEquals("END_ELEMENT", NodeUtils.getXmlStreamConstantAsStr(id)); + break; + } + + case XMLStreamConstants.ENTITY_DECLARATION: { + assertEquals("ENTITY_DECLARATION", NodeUtils.getXmlStreamConstantAsStr(id)); + break; + } + + case XMLStreamConstants.ENTITY_REFERENCE: { + assertEquals("ENTITY_REFERENCE", NodeUtils.getXmlStreamConstantAsStr(id)); + break; + } + + case XMLStreamConstants.NAMESPACE: { + assertEquals("NAMESPACE", NodeUtils.getXmlStreamConstantAsStr(id)); + break; + } + + case XMLStreamConstants.NOTATION_DECLARATION: { + assertEquals("NOTATION_DECLARATION", NodeUtils.getXmlStreamConstantAsStr(id)); + break; + } + + case XMLStreamConstants.PROCESSING_INSTRUCTION: { + assertEquals("PROCESSING_INSTRUCTION", NodeUtils.getXmlStreamConstantAsStr(id)); + break; + } + + case XMLStreamConstants.SPACE: { + assertEquals("SPACE", NodeUtils.getXmlStreamConstantAsStr(id)); + break; + } + + case XMLStreamConstants.START_DOCUMENT: { + assertEquals("START_DOCUMENT", NodeUtils.getXmlStreamConstantAsStr(id)); + break; + } + + case XMLStreamConstants.START_ELEMENT: { + assertEquals("START_ELEMENT", NodeUtils.getXmlStreamConstantAsStr(id)); + break; + } + + default: + String result = NodeUtils.getXmlStreamConstantAsStr(id); + assertNotNull(result); + if (!result.startsWith("Unknown")) { + fail("Unexecpted XML Stream Constant definition for id = " + id); + } + + } + + } + } + + /** + * Convert object to json successful. + * + * @throws JsonProcessingException the json processing exception + */ + @Test + public void convertObjectToJsonSuccessful() throws JsonProcessingException { + + OperationResult opResult = new OperationResult(200, "op result"); + String asJson = NodeUtils.convertObjectToJson(opResult, false); + + assertTrue("Doesn't contain result field", asJson.contains("result")); + assertTrue("Doesn't contain resultCode field", asJson.contains("resultCode")); + assertTrue("Doesn't contain resolvedLinkFailure field", asJson.contains("resolvedLinkFailure")); + + } + + /** + * Convert object to json successful pretty. + * + * @throws JsonProcessingException the json processing exception + */ + @Test + public void convertObjectToJsonSuccessful_pretty() throws JsonProcessingException { + + OperationResult opResult = new OperationResult(200, "op result"); + String asJson = NodeUtils.convertObjectToJson(opResult, true); + + assertTrue("Doesn't contain result field", asJson.contains("result")); + assertTrue("Doesn't contain resultCode field", asJson.contains("resultCode")); + assertTrue("Doesn't contain resolvedLinkFailure field", asJson.contains("resolvedLinkFailure")); + + } + + /** + * Convert object to json failure caused by null. + * + * @throws JsonProcessingException the json processing exception + */ + @Test() + public void convertObjectToJsonFailure_causedBy_null() throws JsonProcessingException { + + String asJson = NodeUtils.convertObjectToJson(null, true); + + assertTrue("Doesn't contain result field", !asJson.contains("result")); + assertTrue("Doesn't contain resultCode field", !asJson.contains("resultCode")); + assertTrue("Doesn't contain resolvedLinkFailure field", + !asJson.contains("resolvedLinkFailure")); + + } + + /** + * Convert object to xml successful. + * + * @throws JsonProcessingException the json processing exception + */ + @Test + public void convertObjectToXmlSuccessful() throws JsonProcessingException { + + OperationResult opResult = new OperationResult(200, "op result"); + String asXml = NodeUtils.convertObjectToXml(opResult); + + assertTrue("Doesn't contain result field", asXml.contains("result")); + assertTrue("Doesn't contain resultCode field", asXml.contains("resultCode")); + assertTrue("Doesn't contain resolvedLinkFailure field", asXml.contains("resolvedLinkFailure")); + + } + + /** + * Convert object to xml failure caused by null. + * + * @throws JsonProcessingException the json processing exception + */ + @Test(expected = JSONException.class) + public void convertObjectToXmlFailure_causedBy_null() throws JsonProcessingException { + + String asXml = NodeUtils.convertObjectToXml(null); + assertNull("Output should be null", asXml); + + } + + /** + * Validate concatonate list empty list. + * + * @throws JsonProcessingException the json processing exception + */ + @Test + public void validateConcatonateList_EmptyList() throws JsonProcessingException { + + String[] array = null; + String result = NodeUtils.concatArray(array); + assertEquals("", result); + + List<String> emptyList = Collections.emptyList(); + result = NodeUtils.concatArray(emptyList); + assertEquals("", result); + } + + /** + * Validate concatonate list multiple values. + * + * @throws JsonProcessingException the json processing exception + */ + @Test + public void validateConcatonateList_MultipleValues() throws JsonProcessingException { + + List<String> numberList = new ArrayList<String>(); + + numberList.add("1"); + numberList.add("2"); + numberList.add("3"); + + String result = NodeUtils.concatArray(numberList); + assertEquals("1 2 3", result); + } + + /** + * Test format timestamp expect valid result. + */ + @Test + public void test_formatTimestamp_expectValidResult() { + String validTimeStamp = "20170111T123116Z"; + String result = NodeUtils.formatTimestamp(validTimeStamp); + + assertEquals("2017-01-11T12:31:16Z", result); + } + + /** + * Test format timestamp expect invalid result. + */ + @Test + public void test_formatTimestamp_expectInvalidResult() { + String validTimeStamp = "#20170011T123116Z"; + String result = NodeUtils.formatTimestamp(validTimeStamp); + + assertEquals(validTimeStamp, result); + } + + /** + * test calculate edit attributes urls + */ + @Test + public void validateCalculateEditAttributeLogic() { + + assertEquals(NodeUtils.calculateEditAttributeUri("https://localhost:9000/aai/v7/pservers/pserver/12345"),"pservers/pserver/12345"); + assertEquals(NodeUtils.calculateEditAttributeUri("https://localhost:9000/aai/v1/pservers/pserver/12345"),"pservers/pserver/12345"); + assertEquals(NodeUtils.calculateEditAttributeUri("https://localhost:9000/aai/v21/pservers/pserver/12345"),"pservers/pserver/12345"); + assertEquals(NodeUtils.calculateEditAttributeUri("https://localhost:9000/aai/v211/pservers/pserver/12345"),"pservers/pserver/12345"); + assertEquals(NodeUtils.calculateEditAttributeUri("https://localhost:9000/aai/v5252/pservers/pserver/12345"),"pservers/pserver/12345"); + assertNull(NodeUtils.calculateEditAttributeUri(null)); + assertNull(NodeUtils.calculateEditAttributeUri("https://localhost:9000/aai/noVersionTag/pservers/pserver/12345")); + + } + + +} diff --git a/src/test/java/org/openecomp/sparky/util/OxmModelLoaderTest.java b/src/test/java/org/openecomp/sparky/util/OxmModelLoaderTest.java new file mode 100644 index 0000000..a830175 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/util/OxmModelLoaderTest.java @@ -0,0 +1,166 @@ +/* +* ============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.openecomp.sparky.util; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; + +import java.io.File; +import java.io.IOException; + +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.TemporaryFolder; +import org.mockito.Mockito; +import org.openecomp.sparky.config.oxm.OxmModelLoader; + +/** + * The Class OxmModelLoaderTest. + */ +public class OxmModelLoaderTest { + + @Rule + public TemporaryFolder folder = new TemporaryFolder(); + + OxmModelLoader loader; + + /** + * Inits the. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Before + public void init() throws IOException { + + + } + + /** + * Test find latest oxm version expectv 9. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void test_findLatestOxmVersion_expectv9() throws IOException { + System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/')); + + folder.newFile("aai_oxm_v7.xml"); + folder.newFile("aai_oxm_v8.xml"); + folder.newFile("aai_oxm_v9.xml"); + folder.newFile("randomTest.xml"); + + loader = Mockito.spy(new OxmModelLoader()); + Mockito.when(loader.loadOxmFolder()).thenReturn(folder.getRoot()); + + String version = loader.findLatestOxmVersion(); + + assertEquals("v9", version); + } + + /** + * Test find latest oxm version expect null when folder is empty. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void test_findLatestOxmVersion_expectNullWhenFolderIsEmpty() throws IOException { + System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/')); + + loader = Mockito.spy(new OxmModelLoader()); + Mockito.when(loader.loadOxmFolder()).thenReturn(folder.getRoot()); + + String version = loader.findLatestOxmVersion(); + + assertEquals(null, version); + } + + /** + * Test find latest oxm version expect null when files does not match expected pattern. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void test_findLatestOxmVersion_expectNullWhenFilesDoesNotMatchExpectedPattern() + throws IOException { + System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/')); + + folder.newFile("file1.xml"); + folder.newFile("file2.xml"); + + loader = Mockito.spy(new OxmModelLoader()); + Mockito.when(loader.loadOxmFolder()).thenReturn(folder.getRoot()); + + String version = loader.findLatestOxmVersion(); + + assertEquals(null, version); + } + + /** + * Test load model expect success. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void test_loadModel_expectSuccess() throws IOException { + String version = "v9"; + System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/')); + + loader = Mockito.spy(new OxmModelLoader()); + Mockito.when(loader.loadOxmFileName(version)).thenReturn( + System.getProperty("AJSC_HOME") + "/bundleconfig-local/oxm/aai_oxm_" + version + ".xml"); + + loader.loadModel(version); + + assertNotEquals(null, loader.getOxmModel()); + } + + /** + * Test load model expect oxm data as empty. + * + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void test_loadModel_expectOxmDataAsEmpty() throws IOException { + String version = "v8"; + System.setProperty("AJSC_HOME", new File(".").getCanonicalPath().replace('\\', '/')); + + loader = Mockito.spy(new OxmModelLoader()); + Mockito.when(loader.loadOxmFileName(version)).thenReturn( + System.getProperty("AJSC_HOME") + "/bundleconfig-local/oxm/aai_oxm_" + version + ".xml"); + + loader.loadModel(version); + + assertEquals(0, loader.getOxmModel().size()); + assertEquals(true, loader.getSearchableEntityDescriptors().isEmpty()); + assertEquals(0, loader.getSearchableOxmModel().size()); + + + + assertNotEquals(null, loader.getOxmModel()); + } + +} diff --git a/src/test/java/org/openecomp/sparky/util/SuggestionsPermutationsTest.java b/src/test/java/org/openecomp/sparky/util/SuggestionsPermutationsTest.java new file mode 100644 index 0000000..dd5d7ca --- /dev/null +++ b/src/test/java/org/openecomp/sparky/util/SuggestionsPermutationsTest.java @@ -0,0 +1,35 @@ +package org.openecomp.sparky.util; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; + +import org.junit.Test; + +public class SuggestionsPermutationsTest { + + @Test + public void isValidSuggestionPermutation_successPath() { + + List<String> x = new ArrayList<>(Arrays.asList("A", "B", "C", "D")); + SuggestionsPermutation suggPermutation = new SuggestionsPermutation(); + + ArrayList<ArrayList<String>> uniqueLists = suggPermutation.getSuggestionsPermutation(x); + + assertTrue(uniqueLists.get(0).toString().equals("[A]")); + assertTrue(uniqueLists.get(1).toString().equals("[A, B, C, D]")); + assertTrue(uniqueLists.get(2).toString().equals("[A, C, D]")); + assertTrue(uniqueLists.get(3).toString().equals("[A, D]")); + assertTrue(uniqueLists.get(4).toString().equals("[B]")); + assertTrue(uniqueLists.get(5).toString().equals("[B, C, D]")); + assertTrue(uniqueLists.get(6).toString().equals("[B, D]")); + assertTrue(uniqueLists.get(7).toString().equals("[C]")); + assertTrue(uniqueLists.get(8).toString().equals("[C, D]")); + assertTrue(uniqueLists.get(9).toString().equals("[D]")); + assertTrue(uniqueLists.size() == 10); + + } +} diff --git a/src/test/java/org/openecomp/sparky/util/TreeWalkerTest.java b/src/test/java/org/openecomp/sparky/util/TreeWalkerTest.java new file mode 100644 index 0000000..27eb0c0 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/util/TreeWalkerTest.java @@ -0,0 +1,563 @@ +/* +* ============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.openecomp.sparky.util; + +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 java.io.IOException; +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; + +import ch.qos.logback.classic.Level; + +/** + * The Class TreeWalkerTest. + */ +public class TreeWalkerTest { + + + /** + * Inits the. + * + * @throws Exception the exception + */ + @Before + public void init() throws Exception { + } + + /** + * Validate json node conversion null input. + */ + @Test + public void validateJsonNodeConversionNullInput() { + + TreeWalker walker = new TreeWalker(); + + try { + JsonNode convertedNode = walker.convertJsonToNode(null); + assertNull("Converted node should have be null", convertedNode); + + } catch (JsonProcessingException exc) { + // expected + } catch (IOException exc) { + // expeted + } + + } + + /** + * Validate json node conversion empty non json input. + */ + @Test + public void validateJsonNodeConversionEmptyNonJsonInput() { + + TreeWalker walker = new TreeWalker(); + + try { + JsonNode convertedNode = walker.convertJsonToNode(""); + assertNull("Converted node should have be null", convertedNode); + + } catch (JsonProcessingException exc) { + // expected + } catch (IOException exc) { + // expeted + } + + } + + /** + * Validate json node conversion empty json input. + */ + @Test + public void validateJsonNodeConversionEmptyJsonInput() { + + TreeWalker walker = new TreeWalker(); + + try { + JsonNode convertedNode = walker.convertJsonToNode("{}"); + assertNotNull("Converted node should not be null", convertedNode); + + ObjectMapper objectMapper = new ObjectMapper(); + String convertedNodeAsStr = objectMapper.writeValueAsString(convertedNode); + + assertEquals("{}", convertedNodeAsStr); + + } catch (JsonProcessingException exc) { + // expected + } catch (IOException exc) { + // expeted + } + + } + + /** + * Validate walk tree null input. + */ + @Test + public void validateWalkTreeNullInput() { + + TreeWalker walker = new TreeWalker(); + + List<String> paths = new ArrayList<String>(); + walker.walkTree(paths, null); + assertEquals(0, paths.size()); + + } + + /** + * Validate walk tree empty node. + */ + @Test + public void validateWalkTreeEmptyNode() { + + try { + TreeWalker walker = new TreeWalker(); + List<String> paths = new ArrayList<String>(); + walker.walkTree(paths, walker.convertJsonToNode("{}")); + assertEquals(0, paths.size()); + } catch (JsonProcessingException exc) { + // expected + } catch (IOException exc) { + // expected + } + + } + + /** + * Validate walk tree one parent node. + */ + @Test + public void validateWalkTreeOneParentNode() { + + try { + TreeWalker walker = new TreeWalker(); + List<String> paths = new ArrayList<String>(); + walker.walkTree(paths, walker.convertJsonToNode("{ \"root\" : { } }")); + assertEquals(1, paths.size()); + } catch (JsonProcessingException exc) { + // expected + } catch (IOException exc) { + // expected + } + + } + + /** + * Validate walk tree one parent node with object array. + */ + @Test + public void validateWalkTreeOneParentNodeWithObjectArray() { + + try { + 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(); + List<String> paths = new ArrayList<String>(); + walker.walkTree(paths, walker.convertJsonToNode(jsonStr)); + assertEquals(9, paths.size()); + } catch (JsonProcessingException exc) { + // expected + } catch (IOException exc) { + // expected + } + + } + + /** + * Validate walk tree one parent node with value array. + */ + @Test + public void validateWalkTreeOneParentNodeWithValueArray() { + + try { + String jsonStr = "{ \"colors\" : [ \"yellow\", \"blue\", \"red\" ] }"; + TreeWalker walker = new TreeWalker(); + List<String> paths = new ArrayList<String>(); + walker.walkTree(paths, walker.convertJsonToNode(jsonStr)); + + assertEquals(3, paths.size()); + } catch (JsonProcessingException exc) { + // expected + } catch (IOException exc) { + // expected + } + + } + + /** + * Test walk for complex entity type aai entity node descriptors. + */ + @Test + public void testWalkForComplexEntityType_AaiEntityNodeDescriptors() { + + 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\" } } } ] }}"; + TreeWalker walker = new TreeWalker(); + List<String> paths = new ArrayList<String>(); + walker.walkTree(paths, walker.convertJsonToNode(jsonStr)); + + assertEquals(68, paths.size()); + + /* + * Example of expected value + * + * generalNodeClass.class=aai-entity-node general-node + * generalNodeClass.visualElements.type=circle generalNodeClass.visualElements.class=outer + * generalNodeClass.visualElements.svgAttributes.r=20 + * generalNodeClass.visualElements.type=circle generalNodeClass.visualElements.class=inner + * generalNodeClass.visualElements.svgAttributes.r=10 + * generalNodeClass.visualElements.type=text + * generalNodeClass.visualElements.class=id-type-label + * generalNodeClass.visualElements.displayKey=itemType + * generalNodeClass.visualElements.shapeAttributes.offset.x=0 + * generalNodeClass.visualElements.shapeAttributes.offset.y=30 + * generalNodeClass.visualElements.type=text + * generalNodeClass.visualElements.class=id-value-label + * generalNodeClass.visualElements.displayKey=itemNameValue + * generalNodeClass.visualElements.shapeAttributes.offset.x=0 + * generalNodeClass.visualElements.shapeAttributes.offset.y=40 + * searchedNodeClass.class=aai-entity-node search-node + * searchedNodeClass.visualElements.type=circle searchedNodeClass.visualElements.class=outer + * searchedNodeClass.visualElements.svgAttributes.r=20 + * searchedNodeClass.visualElements.type=circle searchedNodeClass.visualElements.class=inner + * searchedNodeClass.visualElements.svgAttributes.r=10 + * searchedNodeClass.visualElements.type=text + * searchedNodeClass.visualElements.class=id-type-label + * searchedNodeClass.visualElements.displayKey=itemType + * searchedNodeClass.visualElements.shapeAttributes.offset.x=0 + * searchedNodeClass.visualElements.shapeAttributes.offset.y=30 + * searchedNodeClass.visualElements.type=text + * searchedNodeClass.visualElements.class=id-value-label + * searchedNodeClass.visualElements.displayKey=itemNameValue + * searchedNodeClass.visualElements.shapeAttributes.offset.x=0 + * searchedNodeClass.visualElements.shapeAttributes.offset.y=40 + * selectedSearchedNodeClass.class=aai-entity-node selected-search-node + * selectedSearchedNodeClass.visualElements.type=circle + * selectedSearchedNodeClass.visualElements.class=outer + * selectedSearchedNodeClass.visualElements.svgAttributes.r=20 + * selectedSearchedNodeClass.visualElements.type=circle + * selectedSearchedNodeClass.visualElements.class=inner + * selectedSearchedNodeClass.visualElements.svgAttributes.r=10 + * selectedSearchedNodeClass.visualElements.type=text + * selectedSearchedNodeClass.visualElements.class=id-type-label + * selectedSearchedNodeClass.visualElements.displayKey=itemType + * selectedSearchedNodeClass.visualElements.shapeAttributes.offset.x=0 + * selectedSearchedNodeClass.visualElements.shapeAttributes.offset.y=30 + * selectedSearchedNodeClass.visualElements.type=text + * selectedSearchedNodeClass.visualElements.class=id-value-label + * selectedSearchedNodeClass.visualElements.displayKey=itemNameValue + * selectedSearchedNodeClass.visualElements.shapeAttributes.offset.x=0 + * selectedSearchedNodeClass.visualElements.shapeAttributes.offset.y=40 + * selectedNodeClass.class=aai-entity-node selected-node + * selectedNodeClass.visualElements.type=circle selectedNodeClass.visualElements.class=outer + * selectedNodeClass.visualElements.svgAttributes.r=20 + * selectedNodeClass.visualElements.type=circle selectedNodeClass.visualElements.class=inner + * selectedNodeClass.visualElements.svgAttributes.r=10 + * selectedNodeClass.visualElements.type=text + * selectedNodeClass.visualElements.class=id-type-label + * selectedNodeClass.visualElements.displayKey=itemType + * selectedNodeClass.visualElements.shapeAttributes.offset.x=0 + * selectedNodeClass.visualElements.shapeAttributes.offset.y=30 + * selectedNodeClass.visualElements.type=text + * selectedNodeClass.visualElements.class=id-value-label + * selectedNodeClass.visualElements.displayKey=itemNameValue + * selectedNodeClass.visualElements.shapeAttributes.offset.x=0 + * selectedNodeClass.visualElements.shapeAttributes.offset.y=40 + */ + + } catch (JsonProcessingException exc) { + // expected + } catch (IOException exc) { + // expected + } + + } + + /** + * Test complex object inversion equality. + */ + @Test + public void testComplexObjectInversionEquality() { + + /** + * Dave Adams (1-Nov-2016): + * + * Ok.. I agree...weird title of the test-case. This test is focused on the isEqual equality + * test within the NodeUtils helper class which compares the sorted structural paths of two Json + * Object representations. I attempted to normalize unordered structures to produce an equality + * result, as there doesn't seem to be any natural equality test between two JsonNode objects + * that I could find to date. + * + * Basically, this test is confirming that if the same object values are present in different + * orders, they are effectively the same Json Object representation, and pass, at least my + * structural value equality test. + * + * I reordered the aaiEntityNodeDescriptors top level class types, and change the order of the + * x,y coordinates to be y,x. Same values different order. Once again, the expectation is that + * both representations are objectively equal, they just have different json representations. + */ + + 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\" } }" + + " } ] }}"; + 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\" }" + + " } } ] }}"; + + TreeWalker walker = new TreeWalker(); + List<String> n1Paths = new ArrayList<String>(); + List<String> n2Paths = new ArrayList<String>(); + + JsonNode n1 = walker.convertJsonToNode(n1Str); + JsonNode n2 = walker.convertJsonToNode(n2Str); + walker.walkTree(n1Paths, n1); + walker.walkTree(n2Paths, n2); + + assertEquals(68, n1Paths.size()); + assertEquals(68, n2Paths.size()); + + assertTrue(NodeUtils.isEqual(n1, n2)); + + } catch (JsonProcessingException exc) { + // expected + } catch (IOException exc) { + // expected + } + + } + + + +} diff --git a/src/test/java/org/openecomp/sparky/viewandinspect/ActiveInventoryNodeTester.java b/src/test/java/org/openecomp/sparky/viewandinspect/ActiveInventoryNodeTester.java new file mode 100644 index 0000000..bdacfe9 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/viewandinspect/ActiveInventoryNodeTester.java @@ -0,0 +1,379 @@ +/* +* ============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.openecomp.sparky.viewandinspect; + +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.PropertyNamingStrategy; + +import java.io.IOException; +import java.util.Iterator; + +import org.openecomp.sparky.viewandinspect.config.VisualizationConfig; +import org.openecomp.sparky.viewandinspect.entity.ActiveInventoryNode; + +/** + * The Class ActiveInventoryNodeTester. + */ +public class ActiveInventoryNodeTester { + + /** + * Builds the tree 1. + * + * @return the active inventory node + */ + public ActiveInventoryNode buildTree1() { + + ActiveInventoryNode nodeA = new ActiveInventoryNode("A"); + nodeA.setSelfLink(String.format(selfLinkFormat, "A", "A")); + nodeA.addProperty("a1", "a1"); + nodeA.addProperty("a2", "a2"); + nodeA.addProperty("a3", "a3"); + + createChildNode("C", nodeA, "c1", "c2", "c3"); + createChildNode("D", nodeA, "d1", "d2", "d3"); + createChildNode("E", nodeA, "e1", "e2", "e3"); + + /* + * Assume key uniqueness within a single tree. Safe?? Can we say that every nodeId is unique? + */ + + + return nodeA; + + } + + /** + * Builds the tree 2. + * + * @return the active inventory node + */ + public ActiveInventoryNode buildTree2() { + + ActiveInventoryNode nodeA = new ActiveInventoryNode("A"); + nodeA.setSelfLink(String.format(selfLinkFormat, "A", "A")); + nodeA.addProperty("a4", "a4"); + + ActiveInventoryNode nodeD = createChildNode("D", nodeA, "d7", "d8"); + ActiveInventoryNode nodeW = createChildNode("W", nodeD, "w1", "w2", "w3"); + + createChildNode("H", nodeA, "h2", "h4", "h6"); + + return nodeA; + } + + private String selfLinkFormat = + "https://aai-ext1.test.att.com:9292/aai/v7/network/generic-vnfs/%s/%s"; + + + /** + * Creates the child node. + * + * @param key the key + * @param parent the parent + * @param propertyNames the property names + * @return the active inventory node + */ + private ActiveInventoryNode createChildNode(String key, ActiveInventoryNode parent, + String... propertyNames) { + // ActiveInventoryNode ain = parent.addNode(new ActiveInventoryNode(key)); + // ain.setSelfLink(String.format(SELF_LINK_FORMAT, key, key)); + /* + * if (propertyNames != null) { for (String p : propertyNames) { ain.addProperty(p, p); } } + */ + + ActiveInventoryNode ain = new ActiveInventoryNode(); + + return ain; + + } + + /** + * Builds the tree 3. + * + * @return the active inventory node + */ + public ActiveInventoryNode buildTree3() { + + ActiveInventoryNode nodeA = new ActiveInventoryNode("A"); + nodeA.setSelfLink(String.format(selfLinkFormat, "A", "A")); + nodeA.addProperty("a1", "a1"); + + createChildNode("B", nodeA, "b1"); + createChildNode("C", nodeA, "c1"); + createChildNode("D", nodeA, "d1"); + createChildNode("E", nodeA, "e1"); + createChildNode("F", nodeA, "f1"); + createChildNode("G", nodeA, "g1"); + + return nodeA; + } + + /** + * Builds the tree 4. + * + * @return the active inventory node + */ + public ActiveInventoryNode buildTree4() { + + ActiveInventoryNode nodeA = new ActiveInventoryNode("A"); + nodeA.setSelfLink(String.format(selfLinkFormat, "A", "A")); + nodeA.addProperty("a2", "a2"); + + ActiveInventoryNode nodeB = createChildNode("B", nodeA, "b2"); + ActiveInventoryNode nodeC = createChildNode("C", nodeB, "c2"); + ActiveInventoryNode nodeD = createChildNode("D", nodeC, "d2"); + ActiveInventoryNode nodeE = createChildNode("E", nodeD, "e2"); + ActiveInventoryNode nodeF = createChildNode("F", nodeE, "f2"); + ActiveInventoryNode nodeG = createChildNode("G", nodeF, "g2"); + + return nodeA; + } + + /** + * Do test 1. + */ + public void doTest1() { + + ActiveInventoryNode one = buildTree1(); + ActiveInventoryNode two = buildTree2(); + + one.dumpNodeTree(true); + System.out.println("---"); + two.dumpNodeTree(true); + + System.out.println("---"); + // one.merge(two); + one.dumpNodeTree(true); + + } + + /** + * Do test 2. + * + * @param showProps the show props + */ + public void doTest2(boolean showProps) { + + VisualizationConfig.getConfig().setVisualizationDebugEnabled(false); + + ActiveInventoryNode one = buildTree3(); + ActiveInventoryNode two = buildTree4(); + + System.out.println(one.dumpNodeTree(showProps)); + System.out.println("---"); + System.out.println(two.dumpNodeTree(showProps)); + + System.out.println("---"); + // MergeResult mr = one.merge(two); + // System.out.println("merge result = " + mr.name()); + System.out.println(one.dumpNodeTree(showProps)); + + } + + public static String DIRECT_COMPLEX_SELF_LINK_JSON_RESPONSE = + "{\"complex\":{\"physical-location-id\":\"MJ-1604-COMPLEX\",\"data-center-code\":\"DAYTONNJ\",\"complex-name\":\"complex-name-MDTWNJ23A4\",\"resource-version\":\"1470195143\",\"physical-location-type\":\"SBC/VHO and Mega Pop\",\"street1\":\"451 Western Ave\",\"street2\":\"CU-212\",\"city\":\"dayton\",\"state\":\"NJ\",\"postal-code\":\"08852\",\"country\":\"USA\",\"region\":\"Northeast\",\"latitude\":\"40.3896\",\"longitude\":\"-74.5463\",\"relationship-list\":{\"relationship\":[{\"related-to\":\"pserver\",\"related-link\":\"https://aai-int1.test.att.com:8443/aai/v8/cloud-infrastructure/pservers/pserver/MJ-1604-PSERVER/\",\"relationship-data\":[{\"relationship-key\":\"pserver.hostname\",\"relationship-value\":\"MJ-1604-PSERVER\"}],\"related-to-property\":[{\"property-key\":\"pserver.pserver-name2\",\"property-value\":\"MJ-1604-PSERVER\"}]}]}}}"; + public static String DIRECT_PSERVER_SELF_LINK_JSON_RESPONSE = + "{\"pserver\":{\"hostname\":\"MJ-1604-PSERVER\",\"equip-type\":\"JUNIPER UCPE\",\"equip-vendor\":\"JUNIPER\",\"equip-model\":\"QFX5100-24P-AA\",\"ipv4-oam-address\":\"10.402.143.1\",\"serial-number\":\"VX371521MAHI\",\"pserver-id\":\"1C2B8D47-AVAE-4721-0110-E2C41A07MAHI\",\"in-maint\":false,\"resource-version\":\"1456765026\",\"pserver-name2\":\"MJ-1604-PSERVER\",\"relationship-list\":{\"relationship\":[{\"related-to\":\"complex\",\"related-link\":\"https://aai-int1.test.att.com:8443/aai/v8/cloud-infrastructure/complexes/complex/MJ-1604-COMPLEX/\",\"relationship-data\":[{\"relationship-key\":\"complex.physical-location-id\",\"relationship-value\":\"MJ-1604-COMPLEX\"}]}]},\"p-interfaces\":{\"p-interface\":[{\"interface-name\":\"ge-0/2/0\",\"speed-value\":\"1\",\"speed-units\":\"GBPS\",\"resource-version\":\"1456723241\",\"relationship-list\":{\"relationship\":[{\"related-to\":\"physical-link\",\"related-link\":\"https://aai-int1.test.att.com:8443/aai/v8/network/physical-links/physical-link/BBEC.112430..ATI/\",\"relationship-data\":[{\"relationship-key\":\"physical-link.link-name\",\"relationship-value\":\"BBEC.112430..ATI\"}]}]}},{\"interface-name\":\"ge-0/2/1\",\"speed-value\":\"1\",\"speed-units\":\"GBPS\",\"resource-version\":\"1456723241\",\"relationship-list\":{\"relationship\":[{\"related-to\":\"physical-link\",\"related-link\":\"https://aai-int1.test.att.com:8443/aai/v8/network/physical-links/physical-link/BBEC.112431..ATI/\",\"relationship-data\":[{\"relationship-key\":\"physical-link.link-name\",\"relationship-value\":\"BBEC.112431..ATI\"}]}]}}]}}}"; + + /** + * Parses the direct self link json response. + * + * @param selfLinkJsonResponse the self link json response + * @throws JsonProcessingException the json processing exception + * @throws IOException Signals that an I/O exception has occurred. + */ + public void parseDirectSelfLinkJsonResponse(String selfLinkJsonResponse) + throws JsonProcessingException, IOException { + + ObjectMapper mapper = new ObjectMapper(); + mapper.setSerializationInclusion(Include.NON_EMPTY); + mapper.setPropertyNamingStrategy(new PropertyNamingStrategy.KebabCaseStrategy()); + + + // try { + JsonNode jsonNodeArray = mapper.readTree(selfLinkJsonResponse); + + Iterator<String> iterator = jsonNodeArray.fieldNames(); + JsonNode entityNode = null; + String entityTypeStr = null; + String entityNodeFieldName = null; + + while (iterator.hasNext()) { + entityTypeStr = iterator.next(); + entityNode = jsonNodeArray.get(entityTypeStr); + + Iterator<String> entityNodeFields = entityNode.fieldNames(); + + while (entityNodeFields.hasNext()) { + entityNodeFieldName = entityNodeFields.next(); + System.out.println(String.format("%s.%s", entityTypeStr, entityNodeFieldName)); + } + } + + /* + * Iterator<Entry<String, JsonNode>> fieldNames = jsonNode.fields(); Entry<String,JsonNode> + * field = null; List<String> entitiesToFilter = null; + */ + + /* + * try { entitiesToFilter = + * ActiveInventoryConfig.getConfig().getAaiRestConfig().getFilteredEntities(); } catch ( + * Exception e ) { LOG.error( + * "Caught an exception while retrieving filtered entities. Error Cause = " + + * e.getLocalizedMessage());; return; } + */ + + /* + * JsonNode entityNode = jsonNode. + * + * /*String entityType = entityNode.textValue(); fieldNames = entityNode.fields(); + * + * while ( fieldNames.hasNext() ) { + * + * field = fieldNames.next(); + * + * /* Is there a way to tell if the field is an aggregate or an atomic value? This is where our + * flattening code needs to live + */ + + /* + * String fieldName = field.getKey(); + * + * System.out.println( + * "processDirectSelfLinkResponse(), fieldName for current node with entityType = " + entityType + * + " and field name " + fieldName); + * + * + * /*if ( "relationship-list".equals( fieldName ) ) { + * + * /* Parse the relationship list like we were doing before, or at least navigate it so we can + * extract the relationship data + */ + + /* + * cloud-region is the only exception to this rule where we don't want to collect the + * relationship data from the self-link (for now). + */ + + /* + * if ( !entitiesToFilter.contains(entityType) ) { + * + * // if the current depth >= maxTraversal depth, stop analyzing relationships RelationshipList + * relationships = null; + * + * /* At each level we traverse, we want the properties + relationship-list, until we reach the + * max traversal depth, then we only the properties, and we want to ignore the relationship-list + * to avoid excessive traversal. + */ + + /* + * if ( linkDepth < VisualizationConfig.getConfig().getMaxSelfLinkTraversalDepth()) { + * relationships = analyzeSelfLinkRelationshipList(field.getValue().toString()); + * addSelfLinkRelationshipChildren( relationships, linkDepth ); } else { LOG.warn( + * "Ignoring relationship-list for entity = " + entityType + " at traversal depth = " + + * linkDepth); } + * + * } else { LOG.warn(String.format( + * "Ignoring relationship-list attribute for '%s' based on configuration", entityType)); } + * + * } else { + * + * JsonNode nodeValue = field.getValue(); + * + * if ( nodeValue.isValueNode() ) { + * + * // current behavior, but we need to discover how to translate groups into flattened text by + * using the Jackson JsonNode API addProperty(fieldName, nodeValue.asText()); } else { // need + * special handling for collections + * + * if ( LOG.isDebugEnabled()) { LOG.debug("Complex field discovered = " + fieldName); } + * + * Iterator<String> childFields = nodeValue.fieldNames(); StringBuilder sb = new + * StringBuilder(128); + * + * while ( childFields.hasNext() ) { String f= childFields.next(); + * + * if ( LOG.isDebugEnabled()) { LOG.debug("found field = " + f + " for parent field = " + + * fieldName); } sb.append(fieldName + "=" + nodeValue.get(f).asText()); } + * + * addProperty(fieldName, sb.toString()); + * + * } + * + * } + */ + + /* + * Conscious choice to not log the filtered out resources because it would dump on every node. + * We can always re-visit that choice and put a debug log here if need to / want to. + */ + + /* + * } + * + * + * } catch (IOException exc) { + * + * System.out.println("Argh an io exception occurred with message = " + + * e.getLocalizedMessage()); + * + * /*LOG.error("An error occurred while converting JSON into POJO = " + + * e.getLocalizedMessage()); + * + * this.setProcessingErrorOccurred(true); this.addErrorCause( + * "An error occurred while converting JSON into POJO = " + e.getLocalizedMessage()); + */ + // } + + } + + + + /** + * The main method. + * + * @param args the arguments + * @throws JsonProcessingException the json processing exception + * @throws IOException Signals that an I/O exception has occurred. + */ + public static void main(String[] args) throws JsonProcessingException, IOException { + + System.getProperties().setProperty("AJSC_HOME", "d:\\3\\"); + ActiveInventoryNodeTester tester = new ActiveInventoryNodeTester(); + // tester.doTest2(true); + + tester.parseDirectSelfLinkJsonResponse(DIRECT_COMPLEX_SELF_LINK_JSON_RESPONSE); + System.out.println("---"); + tester.parseDirectSelfLinkJsonResponse(DIRECT_PSERVER_SELF_LINK_JSON_RESPONSE); + + + + } + +} diff --git a/src/test/java/org/openecomp/sparky/viewandinspect/SearchAdapterTest.java b/src/test/java/org/openecomp/sparky/viewandinspect/SearchAdapterTest.java new file mode 100644 index 0000000..f9605e8 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/viewandinspect/SearchAdapterTest.java @@ -0,0 +1,90 @@ +/* +* ============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.openecomp.sparky.viewandinspect; + +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.openecomp.sparky.dal.elasticsearch.SearchAdapter; +import org.openecomp.sparky.dal.rest.OperationResult; +import org.openecomp.sparky.dal.rest.RestClientBuilder; + +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 SearchAdapterTest. + */ +public class SearchAdapterTest { + + 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)); + } + +} diff --git a/src/test/java/org/openecomp/sparky/viewandinspect/SearchResponseTest.java b/src/test/java/org/openecomp/sparky/viewandinspect/SearchResponseTest.java new file mode 100644 index 0000000..41db58c --- /dev/null +++ b/src/test/java/org/openecomp/sparky/viewandinspect/SearchResponseTest.java @@ -0,0 +1,92 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.viewandinspect; + +import java.util.ArrayList; +import java.util.List; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sparky.viewandinspect.entity.EntityEntry; +import org.openecomp.sparky.viewandinspect.entity.SearchResponse; +import org.powermock.modules.junit4.PowerMockRunner; + +/** + * The Class SearchResponseTest. + */ +@RunWith(PowerMockRunner.class) +public class SearchResponseTest { + + /** + * Inits the. + * + * @throws Exception the exception + */ + @Before + public void init() throws Exception {} + + /** + * Validate basic construction. + */ + @Test + public void validateBasicConstruction() { + + SearchResponse response = new SearchResponse(); + + //response.setNumReturned(1); + response.setProcessingTimeInMs(512); + //response.setTotalFound(50); + + List<EntityEntry> entities = new ArrayList<EntityEntry>(); + //response.setEntities(entities); + + EntityEntry e1 = new EntityEntry(); + e1.setEntityPrimaryKeyValue("e1"); + e1.setEntityType("e1"); + e1.setSearchTags("e1"); + + //response.addEntityEntry(e1); + + EntityEntry e2 = new EntityEntry(); + + e2.setEntityPrimaryKeyValue("e2"); + e2.setEntityType("e2"); + e2.setSearchTags("e2"); + + //response.addEntityEntry(e2); + + //assertEquals(1, response.getNumReturned()); + //assertEquals(512, response.getProcessingTimeInMs()); + //assertEquals(50, response.getTotalFound()); + + //List<EntityEntry> responseEntities = response.getEntities(); + + //assertEquals(2, responseEntities.size()); + + } + +} diff --git a/src/test/java/org/openecomp/sparky/viewandinspect/SearchServletTest.java b/src/test/java/org/openecomp/sparky/viewandinspect/SearchServletTest.java new file mode 100644 index 0000000..9e14735 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/viewandinspect/SearchServletTest.java @@ -0,0 +1,786 @@ +/* +* ============LICENSE_START======================================================= +* SPARKY (inventory 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.openecomp.sparky.viewandinspect; + +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 static org.junit.Assert.fail; +import static org.mockito.Matchers.anyString; + +import java.io.IOException; +import java.io.PrintWriter; +import java.io.StringWriter; +import java.security.SecureRandom; +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +import javax.servlet.ServletException; +import javax.servlet.http.HttpServletRequest; +import javax.servlet.http.HttpServletResponse; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.Mockito; +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.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.openecomp.sparky.viewandinspect.services.SearchServiceWrapper; +import org.openecomp.sparky.viewandinspect.servlet.SearchServlet; +import org.slf4j.MDC; + +import org.openecomp.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. + */ + +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; + + /** + * 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 + */ + + 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("vnf","1234", "VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf","1111", "Created VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf","1122", "ACTIVE VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf","2233", "ACTIVE and Error VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf","3344", "ACTIVE and NOT ORCHESTRATED VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf","4455", "ACTIVE and Running VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf","5566", "Activated VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf","6677", "CAPPED VNFs")); + autoSuggestions.add(new SuggestionEntity("vnf","7788", "CAPPED and Created VNFs")); + + 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 + 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 + 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 + */ + + 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()); + } + + } + + + + /** + * 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>" } + */ + + ObjectNode rootNode = mapper.createObjectNode(); + + if (maxResults != null) { + rootNode.put("maxResults", maxResults); + } + + if (queryStr != null) { + rootNode.put("queryStr", queryStr); + } + + return NodeUtils.convertObjectToJson(rootNode, true); + + } + + + /** + * 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/openecomp/sparky/viewandinspect/SearchableGroupsTest.java b/src/test/java/org/openecomp/sparky/viewandinspect/SearchableGroupsTest.java new file mode 100644 index 0000000..13088ba --- /dev/null +++ b/src/test/java/org/openecomp/sparky/viewandinspect/SearchableGroupsTest.java @@ -0,0 +1,73 @@ +/* +* ============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.openecomp.sparky.viewandinspect; + +/** + * The Class SearchableGroupsTest. + */ +public class SearchableGroupsTest { + + static final String TEST_RESOURCE_PATH = "/src/test/resources"; + + static final String GOOD_TEST_CONFIG = "{\"groups\": [" + "{" + "\"group-name\" : \"inventory\"," + + "\"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")); } + */ +} diff --git a/src/test/java/org/openecomp/sparky/viewandinspect/SelfLinkNodeCollectorTester.java b/src/test/java/org/openecomp/sparky/viewandinspect/SelfLinkNodeCollectorTester.java new file mode 100644 index 0000000..fe3a8f8 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/viewandinspect/SelfLinkNodeCollectorTester.java @@ -0,0 +1,69 @@ +/* +* ============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.openecomp.sparky.viewandinspect; + +import org.openecomp.sparky.config.oxm.OxmModelLoader; +import org.openecomp.sparky.viewandinspect.entity.ActiveInventoryNode; +import org.openecomp.sparky.viewandinspect.services.VisualizationContext; + +/** + * The Class SelfLinkNodeCollectorTester. + */ +public class SelfLinkNodeCollectorTester { + + /** + * The main method. + * + * @param args the arguments + * @throws Exception the exception + */ + public static void main(String[] args) throws Exception { + // TODO Auto-generated method stub + + System.getProperties().setProperty("AJSC_HOME", "d:\\3\\"); + //VisualizationContext collector = new VisualizationContext(OxmModelLoader.getInstance()); + + /* + * This is a good test of the LinkResolverServer when we are ready + */ + + ActiveInventoryNode ain = new ActiveInventoryNode(); + ain.setSelfLink( + "https://localhost:9292/aai/v7/network/generic-vnfs/generic-vnf/d2f661e7-d6a0-43b5-979f-720803396a70/"); + ain.setEntityType("generic-vnf"); + + /* + * collector.collectSelfLinks(ain, 1, "generic-vnf", + * "generic-vnf.d2f661e7-d6a0-43b5-979f-720803396a70"); + */ + + // collector.shutdown(); + + ain.dumpNodeTree(true); + + } + +} diff --git a/src/test/java/org/openecomp/sparky/viewandinspect/ViewAndInspectSearchRequestTest.java b/src/test/java/org/openecomp/sparky/viewandinspect/ViewAndInspectSearchRequestTest.java new file mode 100644 index 0000000..41ad2c6 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/viewandinspect/ViewAndInspectSearchRequestTest.java @@ -0,0 +1,81 @@ +/* +* ============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.openecomp.sparky.viewandinspect; + + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNull; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.openecomp.sparky.viewandinspect.entity.QuerySearchEntity; +import org.powermock.modules.junit4.PowerMockRunner; + +/** + * The Class ViewAndInspectSearchRequestTest. + */ +@RunWith(PowerMockRunner.class) +public class ViewAndInspectSearchRequestTest { + + /** + * Inits the. + * + * @throws Exception the exception + */ + @Before + public void init() throws Exception {} + + /** + * Validate basic construction. + */ + @Test + public void validateBasicConstruction() { + + QuerySearchEntity request = new QuerySearchEntity(); + + // test constructor defaults + assertNull(request.getQueryStr()); + assertEquals("10", request.getMaxResults()); + + request.setMaxResults("500"); + assertEquals("500", request.getMaxResults()); + + assertNull(request.getSearchTerms()); + + request.setQueryStr(""); + assertEquals(1, request.getSearchTerms().length); + + request.setQueryStr("t1"); + assertEquals(1, request.getSearchTerms().length); + + request.setQueryStr("t1 t2 t3"); + assertEquals(3, request.getSearchTerms().length); + + } + +} + diff --git a/src/test/java/org/openecomp/sparky/viewandinspect/entity/EntityEntryTest.java b/src/test/java/org/openecomp/sparky/viewandinspect/entity/EntityEntryTest.java new file mode 100644 index 0000000..6dfa448 --- /dev/null +++ b/src/test/java/org/openecomp/sparky/viewandinspect/entity/EntityEntryTest.java @@ -0,0 +1,74 @@ +/* +* ============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.openecomp.sparky.viewandinspect.entity; + + +import static org.junit.Assert.assertEquals; + +import java.io.IOException; +import java.security.NoSuchAlgorithmException; + +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.powermock.modules.junit4.PowerMockRunner; + +/** + * The Class EntityEntryTest. + */ +@RunWith(PowerMockRunner.class) +public class EntityEntryTest { + + /** + * Inits the. + * + * @throws Exception the exception + */ + @Before + public void init() throws Exception {} + + /** + * Validate basic construction. + * + * @throws NoSuchAlgorithmException the no such algorithm exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void validateBasicConstruction() throws NoSuchAlgorithmException, IOException { + + EntityEntry entityEntry = new EntityEntry(); + + entityEntry.setEntityType("ShinyEntityType"); + entityEntry.setEntityPrimaryKeyValue("primary_key_value"); + entityEntry.setSearchTags("t1 t2 t3"); + + assertEquals("ShinyEntityType", entityEntry.getEntityType()); + assertEquals("primary_key_value", entityEntry.getEntityPrimaryKeyValue()); + assertEquals("t1 t2 t3", entityEntry.getSearchTags()); + + } + +} |