summaryrefslogtreecommitdiffstats
path: root/src/test/java/org/openecomp/sparky/util
diff options
context:
space:
mode:
Diffstat (limited to 'src/test/java/org/openecomp/sparky/util')
-rw-r--r--src/test/java/org/openecomp/sparky/util/CaptureLoggerAppender.java247
-rw-r--r--src/test/java/org/openecomp/sparky/util/ElasticEntitySummarizer.java173
-rw-r--r--src/test/java/org/openecomp/sparky/util/ElasticGarbageInjector.java170
-rw-r--r--src/test/java/org/openecomp/sparky/util/ExceptionHelper.java62
-rw-r--r--src/test/java/org/openecomp/sparky/util/HttpServletHelper.java161
-rw-r--r--src/test/java/org/openecomp/sparky/util/LogValidator.java85
-rw-r--r--src/test/java/org/openecomp/sparky/util/ModelLoaderTester.java46
-rw-r--r--src/test/java/org/openecomp/sparky/util/NodeUtilsTest.java489
-rw-r--r--src/test/java/org/openecomp/sparky/util/OxmModelLoaderTest.java166
-rw-r--r--src/test/java/org/openecomp/sparky/util/SuggestionsPermutationsTest.java35
-rw-r--r--src/test/java/org/openecomp/sparky/util/TreeWalkerTest.java563
11 files changed, 2197 insertions, 0 deletions
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
+ }
+
+ }
+
+
+
+}