aboutsummaryrefslogtreecommitdiffstats
path: root/ajsc-aai/src/test/java/org/openecomp/aai/util
diff options
context:
space:
mode:
Diffstat (limited to 'ajsc-aai/src/test/java/org/openecomp/aai/util')
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/AAIApiServerURLBaseTest.java88
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/AAIApiVersionTest.java93
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/AAIAppServletContextListenerTest.java179
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/AAIConfigPasswordDecodingTest.java56
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/AAIPrimaryHostTest.java203
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/AAIRSyncUtilityTest.java216
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/AAITxnLogTest.java362
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/AAIUtilsTest.java113
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/CNNameTest.java141
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/CustomLogPatternLayoutTest.java50
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/DataConversionHelperTest.java89
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestConfig.java303
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestFileWatcher.java64
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestGetFileTime.java55
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestProcessBuilder.java218
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/DeleteResourceTest.java107
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/HbaseSaltPrefixerTest.java40
-rw-r--r--ajsc-aai/src/test/java/org/openecomp/aai/util/JettyObfuscationConversionCommandLineUtilTest.java72
18 files changed, 2449 insertions, 0 deletions
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIApiServerURLBaseTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIApiServerURLBaseTest.java
new file mode 100644
index 0000000..b016c7a
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIApiServerURLBaseTest.java
@@ -0,0 +1,88 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import static org.junit.Assert.*;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
+import org.apache.cxf.message.Message;
+import org.apache.cxf.message.MessageImpl;
+import org.apache.cxf.phase.PhaseInterceptorChain;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.openecomp.aai.util.AAIApiServerURLBase;
+import org.openecomp.aai.util.AAIConfig;
+import org.openecomp.aai.util.AAIConstants;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import static org.mockito.Mockito.*;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.modules.agent.PowerMockAgent;
+import org.powermock.modules.junit4.PowerMockRunner;
+import org.powermock.modules.junit4.rule.PowerMockRule;
+
+@PrepareForTest({PhaseInterceptorChain.class, AAIConfig.class})
+
+public class AAIApiServerURLBaseTest {
+ @Rule
+ public PowerMockRule rule = new PowerMockRule();
+
+ static {
+ PowerMockAgent.initializeIfNeeded();
+ }
+
+ /**
+ * Test get hostname.
+ *
+ * @throws Exception the exception
+ */
+ @Test
+ public void testGetHostname() throws Exception {
+ PowerMockito.mockStatic(PhaseInterceptorChain.class);
+ Map <String, List<String>> hm = new HashMap<String, List<String>>();
+ List<String> host = new ArrayList<String>();
+ host.add("my-localhost");
+ hm.put("host", host);
+
+ Message outMessage = new MessageImpl();
+ outMessage.put(Message.PROTOCOL_HEADERS, hm);
+
+ when(PhaseInterceptorChain.getCurrentMessage()).thenReturn(outMessage);
+ assertEquals("https://my-localhost/aai/", AAIApiServerURLBase.get());
+ }
+
+ /**
+ * Test get with null hostname.
+ *
+ * @throws Exception the exception
+ */
+ @Test
+ public void testGetWithNullHostname() throws Exception {
+ PowerMockito.mockStatic(AAIConfig.class);
+ String defaultHostname = "default-name";
+ when(AAIConfig.get(AAIConstants.AAI_SERVER_URL_BASE)).thenReturn(defaultHostname);
+ assertEquals(defaultHostname, AAIApiServerURLBase.get());
+ }
+}
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIApiVersionTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIApiVersionTest.java
new file mode 100644
index 0000000..89f56de
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIApiVersionTest.java
@@ -0,0 +1,93 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import static org.junit.Assert.*;
+
+import org.apache.cxf.message.Message;
+import org.apache.cxf.message.MessageImpl;
+import org.apache.cxf.phase.PhaseInterceptorChain;
+import org.junit.Rule;
+import org.junit.Test;
+import org.openecomp.aai.util.AAIApiVersion;
+import org.openecomp.aai.util.AAIConfig;
+import org.openecomp.aai.util.AAIConstants;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import static org.mockito.Mockito.*;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.modules.agent.PowerMockAgent;
+import org.powermock.modules.junit4.rule.PowerMockRule;
+
+@PrepareForTest({PhaseInterceptorChain.class, AAIConfig.class})
+
+public class AAIApiVersionTest {
+ @Rule
+ public PowerMockRule rule = new PowerMockRule();
+
+ static { PowerMockAgent.initializeIfNeeded();}
+
+ /**
+ * Test get version.
+ *
+ * @throws Exception the exception
+ */
+ @Test
+ public void testGetVersion() throws Exception {
+ PowerMockito.mockStatic(PhaseInterceptorChain.class);
+ Message outMessage = new MessageImpl();
+ String msg = "/v2/";
+ outMessage.put(Message.REQUEST_URI, msg);
+ when(PhaseInterceptorChain.getCurrentMessage()).thenReturn(outMessage);
+ assertEquals("v2", AAIApiVersion.get());
+ }
+
+ /**
+ * Test get with null version.
+ *
+ * @throws Exception the exception
+ */
+ @Test
+ public void testGetWithNullVersion() throws Exception {
+ PowerMockito.mockStatic(AAIConfig.class);
+ String defaultURI = "default-v2";
+ when(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP, AAIConstants.AAI_DEFAULT_API_VERSION)).thenReturn(defaultURI);
+ assertEquals(defaultURI, AAIApiVersion.get());
+ }
+
+ /**
+ * Test incorrect version pattern.
+ *
+ * @throws Exception the exception
+ */
+ @Test
+ public void testIncorrectVersionPattern() throws Exception {
+ PowerMockito.mockStatic(PhaseInterceptorChain.class);
+ PowerMockito.mockStatic(AAIConfig.class);
+ Message outMessage = new MessageImpl();
+ String msg = "2.0.1";
+ String defaultURI = "default-v2";
+ outMessage.put(Message.REQUEST_URI, msg);
+ when(PhaseInterceptorChain.getCurrentMessage()).thenReturn(outMessage);
+ when(AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP, AAIConstants.AAI_DEFAULT_API_VERSION)).thenReturn(defaultURI);
+ assertEquals(defaultURI, AAIApiVersion.get());
+ }
+
+}
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIAppServletContextListenerTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIAppServletContextListenerTest.java
new file mode 100644
index 0000000..05bb288
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIAppServletContextListenerTest.java
@@ -0,0 +1,179 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import static org.junit.Assert.assertTrue;
+
+import java.util.ArrayList;
+import java.util.List;
+
+import javax.servlet.ServletContextEvent;
+
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Rule;
+import org.junit.Test;
+import org.openecomp.aai.dbmap.AAIGraph;
+import org.openecomp.aai.logging.ErrorLogHelper;
+import org.openecomp.aai.util.AAIAppServletContextListener;
+import org.openecomp.aai.util.AAIConfig;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.agent.PowerMockAgent;
+import org.powermock.modules.junit4.rule.PowerMockRule;
+import org.slf4j.LoggerFactory;
+
+import ch.qos.logback.classic.Level;
+import ch.qos.logback.classic.Logger;
+import ch.qos.logback.classic.PatternLayout;
+import ch.qos.logback.classic.spi.ILoggingEvent;
+import ch.qos.logback.core.AppenderBase;
+
+@PrepareForTest({AAIGraph.class, AAIConfig.class, ErrorLogHelper.class})
+public class AAIAppServletContextListenerTest {
+
+ @Rule
+ public PowerMockRule rule = new PowerMockRule();
+
+ static {
+ PowerMockAgent.initializeIfNeeded();
+ }
+
+ private ServletContextEvent arg;
+ private AAIAppServletContextListener listener;
+
+ /**
+ * Initialize.
+ */
+ @Before
+ @PrepareForTest({AAIGraph.class, AAIConfig.class, ErrorLogHelper.class})
+ public void initialize(){
+ arg = PowerMockito.mock(ServletContextEvent.class);
+ PowerMockito.mockStatic(AAIGraph.class);
+ PowerMockito.mockStatic(AAIConfig.class);
+ PowerMockito.mockStatic(ErrorLogHelper.class);
+
+ listener = new AAIAppServletContextListener();
+ configureLog();
+ }
+
+ /**
+ * Test contextDestroyed.
+ */
+ @Test
+ @Ignore
+ public void testContextDestroyed(){
+ listener.contextDestroyed(arg);
+ assertTrue(logContains(Level.DEBUG, "AAI Server shutdown"));
+ assertTrue(logContains(Level.INFO, "AAI graph shutdown"));
+ }
+
+ /**
+ * Test contextInitialized.
+ */
+ @Test
+ @Ignore
+ public void testContextInitialized(){
+ listener.contextInitialized(arg);
+ assertTrue(logContains(Level.DEBUG, "Loading aaiconfig.properties"));
+ assertTrue(logContains(Level.DEBUG, "Loading error.properties"));
+ assertTrue(logContains(Level.DEBUG, "Loading graph database"));
+ assertTrue(logContains(Level.INFO, "AAI Server initialization"));
+ }
+
+
+ /**
+ * Helper method to check if a String appears in the desired log level.
+ *
+ * @param level Log level to use
+ * @param expected String to search for
+ * @return True if search String is found, false otherwise
+ */
+ private boolean logContains(Level level, String expected) {
+ String actual[] = RecordingAppender.messages();
+ for (String log : actual) {
+ if (log.contains(level.toString()) && log.contains(expected))
+ return true;
+ }
+ return false;
+ }
+
+ /**
+ * Set logging level, and initialize log-appender.
+ */
+ private void configureLog() {
+ Logger rootLogger = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
+ rootLogger.setLevel(Level.DEBUG);
+ rootLogger.detachAndStopAllAppenders();
+ rootLogger.addAppender(RecordingAppender.appender(new PatternLayout()));
+ }
+
+}
+
+
+/**
+ * Appender class that appends log messages to a String List when some logging event occurs
+ */
+class RecordingAppender extends AppenderBase<ILoggingEvent> {
+ private static List<String> messages = new ArrayList<String>();
+ private static RecordingAppender appender = new RecordingAppender();
+ private PatternLayout patternLayout;
+
+ private RecordingAppender() {
+ super();
+ }
+
+ /**
+ * @param patternLayout Pattern to format log message
+ * @return Current appender
+ */
+ public static RecordingAppender appender(PatternLayout patternLayout) {
+ appender.patternLayout = patternLayout;
+ appender.clear();
+ return appender;
+ }
+
+ @Override
+ protected void append(ILoggingEvent event) {
+ messages.add(patternLayout.doLayout(event));
+ }
+
+ public void close() {}
+
+ public boolean requiresLayout() {
+ return false;
+ }
+
+ /**
+ * @return Return logs as a String array
+ */
+ public static String[] messages() {
+ return (String[]) messages.toArray(new String[messages.size()]);
+ }
+
+ /**
+ * Clear the message container
+ */
+ private void clear() {
+ messages.clear();
+ }
+
+}
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIConfigPasswordDecodingTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIConfigPasswordDecodingTest.java
new file mode 100644
index 0000000..d5e5923
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIConfigPasswordDecodingTest.java
@@ -0,0 +1,56 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.BeforeClass;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.openecomp.aai.exceptions.AAIException;
+import org.openecomp.aai.util.AAIConfig;
+
+public class AAIConfigPasswordDecodingTest {
+
+ /**
+ * Configure.
+ *
+ * @throws AAIException the AAI exception
+ */
+ @BeforeClass
+ public static void configure() throws AAIException {
+ System.setProperty("AJSC_HOME", ".");
+ System.setProperty("BUNDLECONFIG_DIR", "src/test/java/bundleconfig-local"); //fake prop file for testing
+ AAIConfig.init();
+ }
+
+ /**
+ * Password check.
+ *
+ * @throws AAIException the AAI exception
+ */
+ @Ignore
+ @Test
+ public void passwordCheck() throws AAIException {
+ assertEquals("password", "aaiuser123", AAIConfig.get("ecm.auth.password"));
+ }
+
+}
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIPrimaryHostTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIPrimaryHostTest.java
new file mode 100644
index 0000000..5454aac
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIPrimaryHostTest.java
@@ -0,0 +1,203 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.openecomp.aai.util.AAIConfig;
+import org.openecomp.aai.util.AAIPrimaryHost;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.agent.PowerMockAgent;
+import org.powermock.modules.junit4.rule.PowerMockRule;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import static org.junit.Assert.*;
+
+import java.io.File;
+import java.io.FileOutputStream;
+
+@PrepareForTest({InetAddress.class, AAIPrimaryHost.class})
+public class AAIPrimaryHostTest {
+
+
+ @Rule
+ public PowerMockRule rule = new PowerMockRule();
+
+ static {
+ PowerMockAgent.initializeIfNeeded();
+ }
+
+
+ AAIPrimaryHost obj = null;
+ private static final String transId = UUID.randomUUID().toString();
+ private static final String fromAppId = "AAIPrimaryHostTest";
+
+ /**
+ * Initialize.
+ */
+ @Before
+ public void initialize(){
+ partialSetupForAAIConfig();
+ obj = new AAIPrimaryHost(transId, fromAppId);
+
+ }
+
+ /**
+ * Test do commandwith failure.
+ *
+ * @throws Exception the exception
+ */
+ @Test
+ public void testDoCommandwithFailure() throws Exception {
+ List<String> myCommands = new ArrayList<String>();
+ String command = "some-command";
+ myCommands.add(command);
+ try {
+ obj.doCommand(myCommands);
+ }
+ catch (Exception e){
+ assertTrue(e.getMessage().contains("Cannot run program \"some-command\""));
+ }
+ }
+
+ /**
+ * Test am I primary with random key name.
+ */
+ @Test
+ public void testAmIPrimary_withRandomKeyName(){
+ assertTrue("If key isn't found in the config file, log exception and return true.", obj.amIPrimary("randomName"));
+ }
+
+ /**
+ * Test am I primary with DEFAUL T CHEC K for localhost.
+ */
+ @Test
+ public void testAmIPrimary_with_DEFAULT_CHECK_for_localhost(){
+ assertTrue("localhost name should not be in the server list", obj.amIPrimary(new String("aai.primary.filetransfer.")));
+ }
+
+
+ /**
+ * Test am I primary with DEFAUL T CHEC K for valid host echo success.
+ */
+ @Test
+ public void testAmIPrimary_with_DEFAULT_CHECK_for_valid_host_echo_success(){
+ mockIP();
+ obj = getTestObject(true, "");
+ assertTrue("host name should exist in the server list in echo success", obj.amIPrimary(new String("aai.primary.filetransfer.")));
+ }
+
+ /**
+ * Test which is primary when missingconfig properties.
+ *
+ * @throws Exception the exception
+ */
+ @Test
+ public void testWhichIsPrimaryWhenMissingconfigProperties() throws Exception {
+ assertEquals(null, obj.whichIsPrimary("checkName"));
+ }
+
+ /**
+ * Test which is primary.
+ *
+ * @throws Exception the exception
+ */
+ @Test
+ public void testWhichIsPrimary() throws Exception {
+ AAIPrimaryHost primaryHost = getTestObject(true, "primaryHost");
+ assertEquals("primaryHost", primaryHost.whichIsPrimary("aai.primary.filetransfer."));
+ }
+
+
+
+ /**
+ * Mock IP.
+ */
+ public void mockIP(){
+
+ PowerMockito.mockStatic(InetAddress.class);
+ InetAddress dummyInetAddress = null;
+ try {
+ Mockito.when(InetAddress.getLocalHost()).thenReturn(dummyInetAddress);
+ Mockito.when(dummyInetAddress.getHostAddress()).thenReturn("localhost");
+ } catch (UnknownHostException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
+
+ /**
+ * Gets the test object.
+ *
+ * @param echoStatus the echo status
+ * @param host the host
+ * @return the test object
+ */
+ public AAIPrimaryHost getTestObject(final boolean echoStatus, final String host){
+ return new AAIPrimaryHost(transId, fromAppId){
+ @Override
+ public boolean amIPrimaryUsingEcho( String hostname, String aaiPrimaryCheck, String aaiServerList) {
+ return echoStatus;
+ }
+
+ @Override
+ public String whichIsPrimaryUsingEcho( String aaiPrimaryCheck, String aaiServerList) {
+ return "primaryHost";
+ }
+
+ };
+ }
+
+
+ static void setFinalStatic(Field field, Object newValue) throws Exception {
+ field.setAccessible(true);
+ Field modifiersField = Field.class.getDeclaredField("modifiers");
+ modifiersField.setAccessible(true);
+ modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
+ field.set(null, newValue);
+ }
+
+ /**
+ * Partial setup for AAI config.
+ */
+ public void partialSetupForAAIConfig(){
+ try {
+ setFinalStatic(AAIConfig.class.getDeclaredField("GlobalPropFileName"), "src/test/resources/test_aaiconfig.properties");
+ }
+ catch (Exception e) {fail();}
+
+ AAIConfig.reloadConfig();
+ }
+
+
+}
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIRSyncUtilityTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIRSyncUtilityTest.java
new file mode 100644
index 0000000..71ab75f
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIRSyncUtilityTest.java
@@ -0,0 +1,216 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.File;
+import java.lang.reflect.Field;
+import java.lang.reflect.InvocationTargetException;
+import java.lang.reflect.Method;
+import java.lang.reflect.Modifier;
+import java.net.InetAddress;
+import java.net.UnknownHostException;
+import java.nio.file.Files;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.StringTokenizer;
+import java.util.UUID;
+
+import org.junit.Before;
+import org.junit.Ignore;
+import org.junit.Test;
+import org.openecomp.aai.util.AAIConfig;
+import org.openecomp.aai.util.AAIRSyncUtility;
+
+
+public class AAIRSyncUtilityTest {
+
+ AAIRSyncUtility syncUtil;
+ AAIRSyncUtility syncUtilOmitDoCommand;
+ AAIConfig aaiConfig;
+ String hostName;
+ String transId = UUID.randomUUID().toString();
+
+ /**
+ * Initialize.
+ */
+ @Before
+ public void initialize(){
+ syncUtil = new AAIRSyncUtility();
+
+ syncUtilOmitDoCommand = new AAIRSyncUtility(){
+ /**
+ * {@inheritDoc}
+ */
+ @Override
+ public int doCommand(List<String> command) throws Exception
+ {
+ return 1;
+ }
+ };
+
+ partialSetupForAAIConfig();
+
+ InetAddress ip = null;
+ try {
+ ip = InetAddress.getLocalHost();
+ } catch (UnknownHostException e2) {
+ e2.printStackTrace();
+ }
+ hostName = ip.getHostName();
+ }
+
+
+ /**
+ * Test sendRsync.
+ */
+ @Ignore
+ @Test
+ public void testSendRsyncCommand(){
+ syncUtilOmitDoCommand.sendRsyncCommand(transId, "RandomFileName");
+ //TODO write codes to check what is being logged
+ }
+
+ /**
+ * Test getHost.
+ */
+ @Test
+ public void testGetHost(){
+
+ String returnedHost = null;
+ Method getHostMethod = makePublic("getHost");
+ try {
+ returnedHost = (String)getHostMethod.invoke(syncUtil, null);
+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
+ e.printStackTrace();
+ }
+
+ assertEquals("Host name didn't match", returnedHost, hostName);
+ }
+
+ /**
+ * Test getRemoteHostList.
+ */
+ @Test
+ public void testGetRemoteHostList(){
+ String localHost = "host_local";
+ String remoteHost1 = "hostR1";
+ String remoteHost2 = "hostR2";
+ ArrayList<String> remotes = new ArrayList<String>();
+ remotes.add(remoteHost1);
+ remotes.add(remoteHost2);
+
+ StringTokenizer stTokenizer = new StringTokenizer(remoteHost1+"\r"+remoteHost2+"\r"+localHost);
+
+ Method m = makePublic("getRemoteHostList");
+ try {
+ assertEquals("Remote host missing", remotes, m.invoke(syncUtil, stTokenizer, localHost));
+ } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Test doCommand.
+ */
+ @Test
+ public void testDoCommand(){
+
+ assertTrue("Don't have execute permissions", Files.isExecutable(new File(".").toPath()));
+
+ List<String> commands = new ArrayList<String>();
+ commands.add("ping");
+ commands.add("google.com");
+ try {
+ assertEquals("Failed to execute commands", 1, syncUtilOmitDoCommand.doCommand(commands));
+ } catch (Exception e) {
+ fail("Failed to execute a command");
+ e.printStackTrace();
+ }
+
+ }
+
+ /**
+ * Test doCommand with null.
+ */
+ @Test
+ public void testDoCommand_withNull(){
+ assertTrue("Don't have execute permissions", Files.isExecutable(new File(".").toPath()));
+ try {
+ assertEquals("This should be unreachable", 1, syncUtil.doCommand(null));
+ } catch (Exception e) {
+ assertTrue("Expecting an NPE from ProcessBuilder", e instanceof NullPointerException);
+ }
+
+ }
+
+
+ /**
+ * Helper method to covert access type of a method from private to public .
+ *
+ * @param privateMethodName Method which is private originally
+ * @return method object with 'access type = 'public'
+ */
+ public Method makePublic(String privateMethodName){
+ Method targetMethod = null;
+ try {
+ if (privateMethodName.equals("getHost"))
+ targetMethod = AAIRSyncUtility.class.getDeclaredMethod(privateMethodName, null);
+ else if (privateMethodName.equals("getRemoteHostList"))
+ targetMethod = AAIRSyncUtility.class.getDeclaredMethod(privateMethodName, StringTokenizer.class, String.class);
+ } catch (NoSuchMethodException | SecurityException e) {
+ e.printStackTrace();
+ }
+ targetMethod.setAccessible(true);
+ return targetMethod;
+ }
+
+ /**
+ * Helper method to load aai config from test configuration file
+ * This requires that the 'test_aaiconfig.properties' file is available
+ */
+ static void setFinalStatic(Field field, Object newValue) throws Exception {
+ field.setAccessible(true);
+ Field modifiersField = Field.class.getDeclaredField("modifiers");
+ modifiersField.setAccessible(true);
+ modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
+ field.set(null, newValue);
+ }
+
+ /**
+ * Helper method to setup AAIConfig for test.
+ */
+ public void partialSetupForAAIConfig(){
+ try {
+ setFinalStatic(AAIConfig.class.getDeclaredField("GlobalPropFileName"), "src/test/resources/test_aaiconfig.properties");
+ }
+ catch (SecurityException e) {fail();}
+ catch (NoSuchFieldException e) {fail();}
+ catch (Exception e) {fail();}
+
+ AAIConfig.reloadConfig();
+ }
+
+}
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAITxnLogTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAITxnLogTest.java
new file mode 100644
index 0000000..8929e33
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAITxnLogTest.java
@@ -0,0 +1,362 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.io.IOException;
+import java.lang.reflect.Field;
+import java.lang.reflect.Modifier;
+import java.util.List;
+
+import org.apache.hadoop.conf.Configuration;
+import org.apache.hadoop.hbase.HBaseConfiguration;
+import org.apache.hadoop.hbase.client.Get;
+import org.apache.hadoop.hbase.client.HTable;
+import org.apache.hadoop.hbase.client.Result;
+import org.apache.hadoop.hbase.client.ResultScanner;
+import org.apache.hadoop.hbase.client.Scan;
+import org.apache.hadoop.hbase.util.Bytes;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.openecomp.aai.domain.notificationEvent.NotificationEvent;
+import org.openecomp.aai.domain.translog.TransactionLogEntries;
+import org.openecomp.aai.domain.translog.TransactionLogEntry;
+import org.openecomp.aai.exceptions.AAIException;
+import org.openecomp.aai.util.AAIConfig;
+import org.openecomp.aai.util.AAITxnLog;
+import org.openecomp.aai.util.PojoUtils;
+import org.powermock.api.mockito.PowerMockito;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.agent.PowerMockAgent;
+import org.powermock.modules.junit4.rule.PowerMockRule;
+
+import com.fasterxml.jackson.core.JsonGenerationException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+
+
+@PrepareForTest({HBaseConfiguration.class, Configuration.class,
+ HTable.class, Result.class, ResultScanner.class, Scan.class,
+ Get.class, NotificationEvent.class,
+ NotificationEvent.EventHeader.class, PojoUtils.class, AAITxnLog.class})
+
+public class AAITxnLogTest {
+
+ @Rule
+ public PowerMockRule rule = new PowerMockRule();
+
+ static {
+ PowerMockAgent.initializeIfNeeded();
+ }
+
+ AAITxnLog aaiTnxLog;
+ Configuration config;
+ HTable htable;
+ Result result;
+ ResultScanner resScanner;
+ Scan scan;
+ Get g;
+ NotificationEvent notif;
+ NotificationEvent.EventHeader ehNotif;
+ PojoUtils pu;
+
+ boolean hasNotifEvent = true;
+ final String notifPayload = "A random payload";
+ final String notifID = "1";
+ final String notifEntityLink = "nLink";
+ final String notifAction = "nAction";
+ final String notifStatus = "nStatus";
+ final String notifTopic = "nTopic";
+
+ final String tid = "tidVal";
+ final String status = "statusVal";
+ final String rqstTm = "rqstTmVal";
+ final String respTm = "respTmVal";
+ final String srcId = "srcIdVal";
+ final String rsrcId = "rsrcIdVal";
+ final String rsrcType = "rsrcTypeVal";
+ final String rqstBuf = "rqstBufVal";
+ final String respBuf = "respBufVal";
+
+
+ /**
+ * Initialize.
+ */
+ @Before
+ public void initialize(){
+ partialSetupForAAIConfig();
+ PowerMockito.mockStatic(HBaseConfiguration.class);
+ config = PowerMockito.mock(Configuration.class);
+ htable = PowerMockito.mock(HTable.class);
+ result = PowerMockito.mock(Result.class);
+ resScanner = PowerMockito.mock(ResultScanner.class);
+ scan = PowerMockito.mock(Scan.class);
+ g = PowerMockito.mock(Get.class);
+ notif = PowerMockito.mock(NotificationEvent.class);
+ ehNotif = PowerMockito.mock(NotificationEvent.EventHeader.class);
+ pu = PowerMockito.mock(PojoUtils.class);
+
+
+ mockNotificationEvent();
+
+ Mockito.when(HBaseConfiguration.create()).thenReturn(config);
+ aaiTnxLog = new AAITxnLog(tid, srcId);
+
+ try {
+ PowerMockito.whenNew(HTable.class).withAnyArguments().thenReturn(htable);
+ PowerMockito.whenNew(Get.class).withAnyArguments().thenReturn(g);
+ PowerMockito.whenNew(PojoUtils.class).withAnyArguments().thenReturn(pu);
+ PowerMockito.whenNew(Scan.class).withAnyArguments().thenReturn(scan);
+ } catch (Exception e) {
+ e.printStackTrace();
+ }
+
+ mockResult();
+
+ try {
+ PowerMockito.when(htable.get(g)).thenReturn(result);
+ PowerMockito.when(htable.getScanner(scan)).thenReturn(resScanner);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Method to test 'put' operation without a notification event.
+ */
+ @Test
+ public void testPut_withoutNotifEvent(){
+ String htid = aaiTnxLog.put(tid, status, rqstTm, respTm, srcId, rsrcId, rsrcType, rqstBuf, respBuf);
+ try {
+ TransactionLogEntry tle = aaiTnxLog.get(htid);
+ hasNotifEvent = false;
+ validateTransactionLogEntry(tle);
+ } catch (AAIException e) {
+ fail("Cant read back data from htable");
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Method to test 'put' operation with a notification event.
+ */
+ @Test
+ public void testPut_withNotifEvent(){
+ hasNotifEvent = true;
+ String htid = aaiTnxLog.put(tid, status, rqstTm, respTm, srcId, rsrcId, rsrcType, rqstBuf, respBuf, hasNotifEvent, notif);
+ try {
+ TransactionLogEntry tle = aaiTnxLog.get(htid);
+ validateTransactionLogEntry(tle);
+ } catch (AAIException e) {
+ fail("Cant read back data from htable");
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * Method to test 'scan' over an empty htable.
+ */
+ @Test
+ public void testScan_withEmptyHTable(){
+ String key = tid;
+ List<String> res = aaiTnxLog.scan(key);
+ assertTrue("Scan output should be empty", res.size() == 0 );
+ }
+
+ /**
+ * Method to test 'scan' operation.
+ */
+ @Test
+ public void testScan(){
+ try {
+ PowerMockito.when(resScanner.next()).thenReturn(result).thenReturn(null);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ List<String> res = aaiTnxLog.scan(tid);
+ assertTrue("Scan output should not be empty", res.size()==1);
+ assertTrue("Did not find entry in 'scan'", res.get(0).equals(result.toString()));
+ }
+
+ /**
+ * Method to test 'scanFiltered' with an empty htable.
+ */
+ @Test
+ public void testScanFiltered_withEmptyHTable(){
+ aaiTnxLog.put(tid, status, rqstTm, respTm, srcId, rsrcId, rsrcType, rqstBuf, respBuf, true, new NotificationEvent());
+ TransactionLogEntries tles = aaiTnxLog.scanFiltered(0, 100, null, null, null, null, null);
+ assertTrue ("scanFilstered output should be empty", tles.getTransactionLogEntries().size() == 0);
+ }
+
+ /**
+ * Method to test 'scanFiltered' operation.
+ */
+ @Test
+ public void testScanFiltered(){
+ try {
+ PowerMockito.when(resScanner.next()).thenReturn(result).thenReturn(null);
+ } catch (IOException e) {
+ e.printStackTrace();
+ }
+ aaiTnxLog.put(tid, status, rqstTm, respTm, srcId, rsrcId, rsrcType, rqstBuf, respBuf, true, new NotificationEvent());
+ TransactionLogEntries tles = aaiTnxLog.scanFiltered(0, 100, null, null, null, null, null);
+ assertFalse ("scanFilstered output should not be empty", tles.getTransactionLogEntries().size() == 0);
+ validateTransactionLogEntry(tles.getTransactionLogEntries().get(0));
+ }
+
+ /**
+ * Helper method to validate the contents of a TransactionalLogEntry.
+ *
+ * @param tle TransactionalLogEntry to compare against
+ */
+ public void validateTransactionLogEntry(TransactionLogEntry tle){
+ String pre = "validateTransactionLogEntry: ";
+ String post = " didn't match";
+ assertEquals(pre + "tid" + post, tle.getTransactionLogEntryId(), tid);
+ assertEquals(pre + "status" + post, tle.getStatus(), status);
+ assertEquals(pre + "rqstDate" + post, tle.getRqstDate(), rqstTm);
+ assertEquals(pre + "respDate" + post, tle.getRespDate(), respTm);
+ assertEquals(pre + "srcId" + post, tle.getSourceId(), srcId);
+ assertEquals(pre + "rsrcId" + post, tle.getResourceId(), rsrcId);
+ assertEquals(pre + "rqstBuf" + post, tle.getRqstBuf(), rqstBuf);
+ assertEquals(pre + "respBuf" + post, tle.getrespBuf(), respBuf);
+ if ( hasNotifEvent){
+ assertEquals(pre + "notifPayload" + post, tle.getNotificationPayload(), notifPayload);
+ assertEquals(pre + "notifStatus" + post, tle.getNotificationStatus(), notifStatus);
+ assertEquals(pre + "notifID" + post, tle.getNotificationId(), notifID);
+ assertEquals(pre + "notifTopic" + post, tle.getNotificationTopic(), notifTopic);
+ assertEquals(pre + "notifEntityLink" + post, tle.getNotificationEntityLink(), notifEntityLink);
+ assertEquals(pre + "notifAction" + post, tle.getNotificationAction(), notifAction);
+ }
+ }
+
+
+
+ /**
+ * Helper method to mock PojoUtils.
+ */
+ public void mockPojoUtils(){
+
+ try {
+ PowerMockito.when(pu.getJsonFromObject(notif)).thenReturn(notifPayload);
+ } catch (JsonGenerationException e) {e.printStackTrace();}
+ catch (JsonMappingException e) {e.printStackTrace();}
+ catch (IOException e) {e.printStackTrace(); }
+ }
+
+
+
+ /**
+ * Helper method to mock a notification event handler.
+ */
+ public void mockNotifEventHandler(){
+ PowerMockito.when(ehNotif.getId()).thenReturn(notifID);
+ PowerMockito.when(ehNotif.getEntityLink()).thenReturn(notifEntityLink);
+ PowerMockito.when(ehNotif.getAction()).thenReturn(notifAction);
+ PowerMockito.when(ehNotif.getStatus()).thenReturn(notifStatus);
+ }
+
+ /**
+ * Helper method to mock a notification event.
+ */
+ public void mockNotificationEvent(){
+ mockPojoUtils();
+ mockNotifEventHandler();
+ PowerMockito.when(notif.getEventHeader()).thenReturn(ehNotif);
+ PowerMockito.when(notif.getEventHeader().getEventType()).thenReturn(null);
+ PowerMockito.when(notif.getEventHeader().getStatus()).thenReturn(null);
+ }
+
+
+ /**
+ * Helper method to build a mock-Result.
+ */
+ public void mockResult(){
+ PowerMockito.when(result.getValue(Bytes.toBytes("transaction"),Bytes.toBytes("tid"))).thenReturn(Bytes.toBytes(tid));
+ PowerMockito.when(result.getValue(Bytes.toBytes("transaction"),Bytes.toBytes("status"))).thenReturn(Bytes.toBytes(status));
+ PowerMockito.when(result.getValue(Bytes.toBytes("transaction"),Bytes.toBytes("rqstDate"))).thenReturn(Bytes.toBytes(rqstTm));
+ PowerMockito.when(result.getValue(Bytes.toBytes("transaction"),Bytes.toBytes("respDate"))).thenReturn(Bytes.toBytes(respTm));
+ PowerMockito.when(result.getValue(Bytes.toBytes("transaction"),Bytes.toBytes("sourceId"))).thenReturn(Bytes.toBytes(srcId));
+
+ PowerMockito.when(result.getValue(Bytes.toBytes("resource"),Bytes.toBytes("resourceId"))).thenReturn(Bytes.toBytes(rsrcId));
+ PowerMockito.when(result.getValue(Bytes.toBytes("resource"),Bytes.toBytes("resourceType"))).thenReturn(Bytes.toBytes(rsrcType));
+
+ PowerMockito.when(result.getValue(Bytes.toBytes("payload"),Bytes.toBytes("rqstBuf"))).thenReturn(Bytes.toBytes(rqstBuf));
+ PowerMockito.when(result.getValue(Bytes.toBytes("payload"),Bytes.toBytes("respBuf"))).thenReturn(Bytes.toBytes(respBuf));
+
+ PowerMockito.when(result.getValue(Bytes.toBytes("notification"),Bytes.toBytes("notificationPayload"))).thenReturn(Bytes.toBytes(notifPayload));
+ PowerMockito.when(result.getValue(Bytes.toBytes("notification"),Bytes.toBytes("notificationStatus"))).thenReturn(Bytes.toBytes(notifStatus));
+ PowerMockito.when(result.getValue(Bytes.toBytes("notification"),Bytes.toBytes("notificationId"))).thenReturn(Bytes.toBytes(notifID));
+ PowerMockito.when(result.getValue(Bytes.toBytes("notification"),Bytes.toBytes("notificationTopic"))).thenReturn(Bytes.toBytes(notifTopic));
+ PowerMockito.when(result.getValue(Bytes.toBytes("notification"),Bytes.toBytes("notificationEntityLink"))).thenReturn(Bytes.toBytes(notifEntityLink));
+ PowerMockito.when(result.getValue(Bytes.toBytes("notification"),Bytes.toBytes("notificationAction"))).thenReturn(Bytes.toBytes(notifAction));
+ }
+
+
+ /**
+ * Helper method to load aai config from test configuration file
+ * This requires that the 'test_aaiconfig.properties' file is available
+ */
+
+ static void setFinalStatic(Field field, Object newValue) throws Exception {
+ field.setAccessible(true);
+ Field modifiersField = Field.class.getDeclaredField("modifiers");
+ modifiersField.setAccessible(true);
+ modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
+ field.set(null, newValue);
+ }
+
+ /**
+ * Partial setup for AAI config.
+ */
+ public void partialSetupForAAIConfig(){
+
+ try {
+ setFinalStatic(AAIConfig.class.getDeclaredField("GlobalPropFileName"), "src/test/resources/test_aaiconfig.properties");
+ }
+ catch (SecurityException e) {fail();}
+ catch (NoSuchFieldException e) {fail();}
+ catch (Exception e) {fail();}
+
+ AAIConfig.reloadConfig();
+ }
+
+ /**
+ * Helper method to set the file name of aaiconfig.properties file
+ *
+ * @param field Private static filed for update
+ * @param newValue New value to be used
+ * @throws Exception the exception
+ */
+ public void modifyFinalStatic(Field field, Object newValue) throws Exception {
+ field.setAccessible(true);
+ Field modifiersField = Field.class.getDeclaredField("modifiers");
+ modifiersField.setAccessible(true);
+ modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
+ field.set(null, newValue);
+ }
+
+}
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIUtilsTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIUtilsTest.java
new file mode 100644
index 0000000..5b2d1c4
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/AAIUtilsTest.java
@@ -0,0 +1,113 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.junit.Assert.fail;
+
+import java.text.DateFormat;
+import java.text.ParseException;
+import java.text.SimpleDateFormat;
+import java.util.ArrayList;
+import java.util.Date;
+import java.util.List;
+import java.util.TimeZone;
+import java.util.concurrent.TimeUnit;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.openecomp.aai.util.AAIUtils;
+import org.powermock.modules.agent.PowerMockAgent;
+import org.powermock.modules.junit4.rule.PowerMockRule;
+
+public class AAIUtilsTest {
+
+ @Rule
+ public PowerMockRule rule = new PowerMockRule();
+
+ static {
+ PowerMockAgent.initializeIfNeeded();
+ }
+
+
+ AAIUtils testObj;
+
+ /**
+ * Initialize.
+ */
+ @Before
+ public void initialize(){
+ testObj = new AAIUtils();
+ }
+
+ /**
+ * Test nullCheck with null.
+ */
+ @Test
+ public void testNullCheck_withNull(){
+ List<String> newList = null;
+ assertNotNull("method nullCheck should not return null", AAIUtils.nullCheck(newList));
+ }
+
+ /**
+ * Test nullCheck with a List.
+ */
+ @Test
+ public void testNullCheck_withList(){
+ List<String> newList = new ArrayList<String>();
+ newList.add("testString");
+ assertNotNull("method nullCheck failed for a List", AAIUtils.nullCheck(newList));
+ }
+
+ /**
+ * Test genDate using a past and a future date.
+ */
+ @Test
+ public void testGenDate(){
+
+ Date d1 = new Date(0);
+
+ DateFormat formatter = new SimpleDateFormat("YYMMdd-HH:mm:ss:SSS");
+ formatter.setTimeZone(TimeZone.getTimeZone("GMT"));
+ formatter.setLenient(false);
+
+ Date d2 = null;
+
+ try {
+ d2 = formatter.parse(AAIUtils.genDate());
+ } catch (ParseException e) {
+ fail("Date parsing exception");
+ e.printStackTrace();
+ }
+
+ try {
+ TimeUnit.SECONDS.sleep(1);
+ } catch (InterruptedException e1) {}
+
+ Date d3 = new Date();
+
+ assertTrue("Generated date is not after a past date", d2.after(d1));
+ assertTrue("Generated date is not before a future date", d2.before(d3));
+ }
+
+}
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/CNNameTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/CNNameTest.java
new file mode 100644
index 0000000..5ba1701
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/CNNameTest.java
@@ -0,0 +1,141 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.when;
+
+import java.security.cert.X509Certificate;
+
+import javax.security.auth.x500.X500Principal;
+import javax.servlet.http.HttpServletRequest;
+
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.mockito.Mockito;
+import org.openecomp.aai.util.CNName;
+import org.powermock.core.classloader.annotations.PowerMockIgnore;
+import org.powermock.core.classloader.annotations.PrepareForTest;
+import org.powermock.modules.agent.PowerMockAgent;
+import org.powermock.modules.junit4.PowerMockRunner;
+import org.powermock.modules.junit4.rule.PowerMockRule;
+
+import ch.qos.logback.access.spi.IAccessEvent;
+
+@PowerMockIgnore("javax.security.auth.x500.X500Principal")
+@PrepareForTest({IAccessEvent.class, HttpServletRequest.class, X509Certificate.class})
+public class CNNameTest {
+
+ @Rule
+ public PowerMockRule rule = new PowerMockRule();
+
+ static {
+ PowerMockAgent.initializeIfNeeded();
+ }
+
+
+ IAccessEvent mockAccEvent;
+ HttpServletRequest mockHttpServletRequest;
+ CNName cnname;
+ X509Certificate cert;
+
+ /**
+ * Initialize.
+ */
+ @Before
+ public void initialize(){
+ mockAccEvent = Mockito.mock(IAccessEvent.class);
+ mockHttpServletRequest = Mockito.mock(HttpServletRequest.class);
+ cert = Mockito.mock(X509Certificate.class);
+ }
+
+
+ /**
+ * Test 'convert' when there is no AccessConverter.
+ */
+ @Test
+ public void testConvert_withoutAccessConverter(){
+ cnname = getTestObj(false);
+ assertTrue("Conversion failed with no AccessConverter", "INACTIVE_HEADER_CONV".equals(cnname.convert(mockAccEvent)));
+ }
+
+ /**
+ * Test 'convert' with no CipherSuite.
+ */
+ @Test
+ public void testConvert_withNullCipherSuite(){
+ setupForCipherSuite(null);
+ assertTrue("Conversion failed for a null CipherSuite", "-".equals(cnname.convert(mockAccEvent)));
+ }
+
+
+ /**
+ * Test 'convert' with a non-null CipherSuite.
+ */
+ @Test
+ public void testConvert_withNotNullCipherSuite(){
+
+ setupForCipherSuite("StrRepOfAValidSuite");
+
+ final X500Principal principal = new X500Principal("CN=AnAI, OU=DOX, O=BWS, C=CA");
+
+ Mockito.when(cert.getSubjectX500Principal()).thenReturn(principal);
+
+ final X509Certificate[] certChain = {cert};
+
+ when(mockHttpServletRequest.getAttribute("javax.servlet.request.X509Certificate")).thenReturn(certChain);
+
+ assertTrue("Conversion failed for a valid CipherSuite", principal.toString().equals(cnname.convert(mockAccEvent)));
+ }
+
+
+ /**
+ * Helper method to mock IAccessEvent and HttpServletRequest.
+ *
+ * @param suite CipherSuite to be used in current test
+ */
+ private void setupForCipherSuite(String suite){
+ cnname = getTestObj(true);
+ when(mockAccEvent.getRequest()).thenReturn(mockHttpServletRequest);
+ when(mockHttpServletRequest.getAttribute("javax.servlet.request.cipher_suite")).thenReturn(suite);
+ }
+
+
+ /**
+ * Helper method to create a CNName object with overridden 'start status' .
+ *
+ * @param instanceStarted Start status to be used
+ * @return CNName object to test
+ */
+ private CNName getTestObj(final boolean instanceStarted){
+ return new CNName(){
+ @Override
+ public boolean isStarted(){
+ return instanceStarted;
+ }
+ };
+ }
+}
+
+
+
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/CustomLogPatternLayoutTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/CustomLogPatternLayoutTest.java
new file mode 100644
index 0000000..aa946b0
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/CustomLogPatternLayoutTest.java
@@ -0,0 +1,50 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+import org.junit.Test;
+import org.openecomp.aai.util.CNName;
+import org.openecomp.aai.util.CustomLogPatternLayout;
+
+public class CustomLogPatternLayoutTest {
+
+ /**
+ * Test null when defaultConverterMap doesn't have corresponding entry.
+ */
+ @Test
+ public void testNull(){
+ String s = CustomLogPatternLayout.defaultConverterMap.get("z");
+ assertFalse("Entry not found for key 'z'", CNName.class.getName().equals(s));
+ }
+
+ /**
+ * Test defaultConverterMap when valid entry exists.
+ */
+ @Test
+ public void testEntryFor_Z(){
+ CustomLogPatternLayout layout = new CustomLogPatternLayout();
+ String s = CustomLogPatternLayout.defaultConverterMap.get("z");
+ assertTrue("Entry not found for key 'z'", CNName.class.getName().equals(s));
+ }
+
+}
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/DataConversionHelperTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/DataConversionHelperTest.java
new file mode 100644
index 0000000..9df8900
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/DataConversionHelperTest.java
@@ -0,0 +1,89 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import static org.junit.Assert.assertEquals;
+
+import org.junit.Rule;
+import org.junit.Test;
+import org.openecomp.aai.util.DataConversionHelper;
+import org.powermock.modules.agent.PowerMockAgent;
+import org.powermock.modules.junit4.rule.PowerMockRule;
+
+public class DataConversionHelperTest {
+
+ @Rule
+ public PowerMockRule rule = new PowerMockRule();
+
+ static {
+ PowerMockAgent.initializeIfNeeded();
+ }
+
+ /**
+ * Test convertIPVersionNumToString with value "4".
+ */
+ @Test
+ public void testConvertIPVersionNumToString_withNum4(){
+ assertEquals(DataConversionHelper.IPVERSION_IPV4, DataConversionHelper.convertIPVersionNumToString("4"));
+ }
+
+ /**
+ * Test convertIPVersionNumToString with value "6".
+ */
+ @Test
+ public void testConvertIPVersionNumToString_withNum6(){
+ assertEquals(DataConversionHelper.IPVERSION_IPV6, DataConversionHelper.convertIPVersionNumToString("6"));
+ }
+
+ /**
+ * Test convertIPVersionNumToString with a value other than "4" or "6".
+ */
+ @Test
+ public void testConvertIPVersionNumToString_withAThirdNumber(){
+ assertEquals(DataConversionHelper.IPVERSION_UNKNOWN, DataConversionHelper.convertIPVersionNumToString("-1"));
+ }
+
+ /**
+ * Test convertIPVersionStringToNum with "v4".
+ */
+ @Test
+ public void testConvertIPVersionStringToNum_withV4(){
+ assertEquals("4", DataConversionHelper.convertIPVersionStringToNum(DataConversionHelper.IPVERSION_IPV4));
+ }
+
+ /**
+ * Test convertIPVersionStringToNum with "v6".
+ */
+ @Test
+ public void testConvertIPVersionStringToNum_withV6(){
+ assertEquals("6", DataConversionHelper.convertIPVersionStringToNum(DataConversionHelper.IPVERSION_IPV6));
+ }
+
+ /**
+ * Test convertIPVersionStringToNum with an illegal version.
+ */
+ @Test
+ public void testConvertIPVersionStringToNum_withRandomString(){
+ assertEquals("0", DataConversionHelper.convertIPVersionStringToNum("test string"));
+ }
+
+
+}
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestConfig.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestConfig.java
new file mode 100644
index 0000000..4f84519
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestConfig.java
@@ -0,0 +1,303 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import java.util.Date;
+import java.util.Enumeration;
+import java.util.Properties;
+import java.util.TimerTask;
+import java.io.File;
+import java.io.FileNotFoundException;
+import java.io.InputStream;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.util.Timer;
+import java.net.InetAddress;
+
+public class DbTestConfig {
+
+ public static final String AUDIT_FILESEP = (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator");
+ public static final String AUDIT_HOME = (System.getProperty("audit.home") == null) ? AUDIT_FILESEP + "opt" + AUDIT_FILESEP + "audit" : System.getProperty("audit.home");
+ public static final String AuditPropFilename = "c:\\tmp\\auditConfig.prop";
+ public static final String AUDIT_CONFIG_CHECKINGTIME = "audit.config.checktime";
+ public static final String AUDIT_NODENAME = "localhost";
+ public static final String AUDIT_DEBUG = "audit.config.debug";
+
+ private static Properties serverProps;
+ private static boolean propsInitialized = false;
+ private static boolean timerSet = false;
+ private static Timer timer = null;
+
+ private static String propFile = null;
+
+ /**
+ * Inits the.
+ *
+ * @param propertyFile the property file
+ */
+ public synchronized static void init(String propertyFile) {
+ propFile = propertyFile;
+ init();
+ }
+
+ /**
+ * Inits the.
+ */
+ public synchronized static void init() {
+ System.out.println("Initializing Config");
+
+ DbTestConfig.getConfigFile();
+ DbTestConfig.reloadConfig();
+
+ if ( propFile == null)
+ propFile = AuditPropFilename;
+ TimerTask task = null;
+ task = new DbTestFileWatcher ( new File(propFile)) {
+ protected void onChange( File file ) {
+ // here we implement the onChange
+ DbTestConfig.reloadConfig();
+ }
+ };
+
+ if (!timerSet) {
+ timerSet = true;
+ // repeat the check every second
+ timer = new Timer();
+ String fwi = DbTestConfig.get(AUDIT_CONFIG_CHECKINGTIME);
+ timer.schedule( task , new Date(), Integer.parseInt(fwi) );
+ System.out.println("Config Watcher Interval=" + fwi);
+
+ System.out.println("File" + propFile+" Loaded!");
+ }
+
+ }
+
+ /**
+ * Cleanup.
+ */
+ public static void cleanup() {
+ timer.cancel();
+ }
+
+ /**
+ * Gets the config file.
+ *
+ * @return the config file
+ */
+ public static String getConfigFile() {
+ return propFile;
+ }
+
+ /**
+ * Reload config.
+ */
+ public synchronized static void reloadConfig() {
+
+ String propFileName = propFile;
+
+ Properties newServerProps = null;
+
+ System.out.println("Reloading config from "+propFileName);
+
+ try {
+ InputStream is = new FileInputStream(propFileName);
+ newServerProps = new Properties();
+ newServerProps.load(is);
+ propsInitialized = true;
+
+ serverProps = newServerProps;
+ if (get(AUDIT_DEBUG).equals("on")) {
+ serverProps.list(System.out);
+ }
+ newServerProps = null;
+
+ } catch (FileNotFoundException fnfe) {
+ System.out.println("AuditConfig: " + propFileName + ". FileNotFoundException: "+fnfe.getMessage());
+ } catch (IOException e) {
+ System.out.println("AuditConfig: " + propFileName + ". IOException: "+e.getMessage());
+ }
+ }
+
+ /**
+ * Gets the.
+ *
+ * @param key the key
+ * @param defaultValue the default value
+ * @return the string
+ */
+ public static String get(String key, String defaultValue) {
+ String result = defaultValue;
+ try {
+ result = get (key);
+ }
+ catch ( Exception a ) {
+ }
+ return result;
+ }
+
+ /**
+ * Gets the.
+ *
+ * @param key the key
+ * @return the string
+ */
+ public static String get(String key) {
+ String response = null;
+
+ if (key.equals(AUDIT_NODENAME)) {
+ // Get this from InetAddress rather than the properties file
+ String nodeName = getNodeName();
+ if (nodeName != null) {
+ return nodeName;
+ }
+ // else get from property file
+ }
+
+ if (!propsInitialized || (serverProps == null)) {
+ reloadConfig();
+ }
+ if (!serverProps.containsKey(key)) {
+ System.out.println( "Property key "+key+" cannot be found");
+ } else {
+ response = serverProps.getProperty(key);
+ if (response == null || response.isEmpty()) {
+ System.out.println("Property key "+key+" is null or empty");
+ }
+ }
+ return response;
+ }
+
+ /**
+ * Gets the int.
+ *
+ * @param key the key
+ * @return the int
+ */
+ public static int getInt(String key) {
+ return Integer.valueOf(DbTestConfig.get(key));
+ }
+
+ /**
+ * Gets the server props.
+ *
+ * @return the server props
+ */
+ public static Properties getServerProps() {
+ return serverProps;
+ }
+
+ /**
+ * Gets the node name.
+ *
+ * @return the node name
+ */
+ public static String getNodeName() {
+ try {
+ InetAddress ip = InetAddress.getLocalHost();
+ if (ip != null) {
+ String hostname = ip.getHostName();
+ if (hostname != null) {
+ return hostname;
+ }
+ }
+ } catch (Exception e) {
+ return null;
+ }
+ return null;
+ }
+
+ /**
+ * Extracts a specific property key subset from the known properties.
+ * The prefix may be removed from the keys in the resulting dictionary,
+ * or it may be kept. In the latter case, exact matches on the prefix
+ * will also be copied into the resulting dictionary.
+ *
+ * @param prefix is the key prefix to filter the properties by.
+ * @param keepPrefix if true, the key prefix is kept in the resulting
+ * dictionary. As side-effect, a key that matches the prefix exactly
+ * will also be copied. If false, the resulting dictionary's keys are
+ * shortened by the prefix. An exact prefix match will not be copied,
+ * as it would result in an empty string key.
+ * @return a property dictionary matching the filter key. May be
+ * an empty dictionary, if no prefix matches were found.
+ *
+ * @see #getProperty( String ) is used to assemble matches
+ */
+ public static Properties matchingSubset(String prefix, boolean keepPrefix) {
+ Properties result = new Properties();
+
+ // sanity check
+ if (prefix == null || prefix.length() == 0) {
+ return result;
+ }
+
+ String prefixMatch; // match prefix strings with this
+ String prefixSelf; // match self with this
+ if (prefix.charAt(prefix.length() - 1) != '.') {
+ // prefix does not end in a dot
+ prefixSelf = prefix;
+ prefixMatch = prefix + '.';
+ } else {
+ // prefix does end in one dot, remove for exact matches
+ prefixSelf = prefix.substring(0, prefix.length() - 1);
+ prefixMatch = prefix;
+ }
+ // POSTCONDITION: prefixMatch and prefixSelf are initialized!
+
+ // now add all matches into the resulting properties.
+ // Remark 1: #propertyNames() will contain the System properties!
+ // Remark 2: We need to give priority to System properties. This is done
+ // automatically by calling this class's getProperty method.
+ String key;
+ for (Enumeration e = serverProps.keys(); e.hasMoreElements(); ) {
+ key = (String) e.nextElement();
+
+ if (keepPrefix) {
+ // keep full prefix in result, also copy direct matches
+ if (key.startsWith(prefixMatch) || key.equals(prefixSelf)) {
+ result.setProperty(key, serverProps.getProperty(key));
+ }
+ } else {
+ // remove full prefix in result, dont copy direct matches
+ if (key.startsWith(prefixMatch)) {
+ result.setProperty(key.substring(prefixMatch.length()), serverProps.getProperty(key));
+ }
+ }
+ }
+
+ // done
+ return result;
+ }
+
+
+
+ /**
+ * The main method.
+ *
+ * @param args the arguments
+ */
+ public static void main(String[] args) {
+ // TODO Auto-generated method stub
+ DbTestConfig.init( );
+
+ }
+
+}
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestFileWatcher.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestFileWatcher.java
new file mode 100644
index 0000000..05a4cfe
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestFileWatcher.java
@@ -0,0 +1,64 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import java.util.*;
+import java.io.*;
+
+public abstract class DbTestFileWatcher extends TimerTask {
+ private long timeStamp;
+ private File file;
+
+ /**
+ * Instantiates a new db test file watcher.
+ *
+ * @param file the file
+ */
+ public DbTestFileWatcher( File file ) {
+ this.file = file;
+ this.timeStamp = file.lastModified();
+ }
+
+ /**
+ * {@inheritDoc}
+ */
+ public final void run() {
+ long timeStamp = file.lastModified();
+
+ if( (timeStamp - this.timeStamp) > 500 ) {
+ this.timeStamp = timeStamp;
+ onChange(file);
+ }
+ try {
+ Thread.sleep(1000);
+ } catch (InterruptedException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+ }
+
+ /**
+ * On change.
+ *
+ * @param file the file
+ */
+ protected abstract void onChange( File file );
+}
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestGetFileTime.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestGetFileTime.java
new file mode 100644
index 0000000..d56a4d2
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestGetFileTime.java
@@ -0,0 +1,55 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import java.io.File;
+import java.io.IOException;
+import java.nio.file.Files;
+import java.nio.file.Path;
+import java.nio.file.Paths;
+import java.nio.file.attribute.BasicFileAttributeView;
+import java.nio.file.attribute.BasicFileAttributes;
+import java.nio.file.attribute.FileTime;
+
+public class DbTestGetFileTime {
+
+
+ /**
+ * Creates the file return time.
+ *
+ * @param path the path
+ * @return the file time
+ * @throws IOException Signals that an I/O exception has occurred.
+ */
+ public FileTime createFileReturnTime( String path) throws IOException {
+ File file = new File(path);
+ if(!file.exists()) {
+ file.createNewFile();
+ }
+ Path p = Paths.get(file.getAbsolutePath());
+ BasicFileAttributes view
+ = Files.getFileAttributeView(p, BasicFileAttributeView.class)
+ .readAttributes();
+ FileTime fileTime=view.creationTime();
+ // also available view.lastAccessTine and view.lastModifiedTime
+ return fileTime;
+ }
+}
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestProcessBuilder.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestProcessBuilder.java
new file mode 100644
index 0000000..8d8ebe0
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/DbTestProcessBuilder.java
@@ -0,0 +1,218 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import java.io.BufferedReader;
+import java.io.File;
+import java.io.IOException;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.nio.file.attribute.FileTime;
+import java.text.SimpleDateFormat;
+import java.util.Arrays;
+import java.util.List;
+import java.util.concurrent.Executors;
+import java.util.concurrent.ScheduledExecutorService;
+import java.util.concurrent.ScheduledFuture;
+import java.util.concurrent.TimeUnit;
+
+public class DbTestProcessBuilder {
+ ///public static Logger clog = Logger.getLogger("auditConsole");
+ //public static Logger alog = Logger.getLogger("auditLog");
+
+ /**
+ * Start audit process non blocking.
+ *
+ * @param wait the wait
+ * @param cmds the cmds
+ * @param dir the dir
+ */
+ public void startAuditProcessNonBlocking(final long wait, final String cmds[], final String dir) {
+
+ final ProcessBuilder pb = new ProcessBuilder(cmds).redirectErrorStream(true).directory(new File(dir));
+
+ new Thread(new Runnable() {
+ public void run() {
+ try {
+ //System.out.println( "sleeping seconds " + wait + " cmds " + Arrays.toString(cmds));
+ Thread.sleep(wait*1000);
+ //System.out.println( "returned from sleep");
+ final Process p = pb.start();
+ //System.out.println( "returned from pb.start");
+ final InputStream is = p.getInputStream();
+ final BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
+ final InputStreamReader isr = new InputStreamReader(is);
+ final BufferedReader br = new BufferedReader(isr);
+//clog.debug("Output of running " + Arrays.toString(cmds) + " is:");
+ System.out.println("Output of running is:" );
+ String line;
+ while ((line = br.readLine()) != null ) {
+ System.out.println(line);
+ }
+ System.out.println("stderr of running is:" );
+
+ while ((line = stdError.readLine()) != null ) {
+ System.out.println(line);
+ }
+
+ } catch (IOException ie) {
+
+ } catch (InterruptedException itre) {
+ Thread.currentThread().interrupt();
+ }
+ }
+ }).start();
+
+ }
+
+
+ private final ScheduledExecutorService auditProcessScheduler =
+ Executors.newScheduledThreadPool(10);
+
+ /**
+ * Run W command every X seconds for Y minutes.
+ *
+ * @param w the w
+ * @param x the x
+ * @param y the y
+ * @param runningDir the running dir
+ */
+ public void runWCommandEveryXSecondsForYMinutes(String[] w, int x, int y, final String runningDir) {
+ final String[] c1 = w;
+ final Runnable audit = new Runnable() {
+ public void run() {
+//clog.debug("checkpoint "+(new Date()).toString());
+ DbTestProcessBuilder a1 = new DbTestProcessBuilder();
+ a1.startAuditProcessNonBlocking(1, c1, "/tmp");
+ }
+ };
+
+ final ScheduledFuture<?> auditHandle =
+ auditProcessScheduler.scheduleAtFixedRate(audit, 0, x, TimeUnit.SECONDS);
+ auditProcessScheduler.schedule(new Runnable() {
+ public void run() {
+ auditHandle.cancel(true);
+ }
+ }, y * 60, TimeUnit.SECONDS);
+ }
+
+
+ /**
+ * The main method.
+ *
+ * @param args the arguments
+ */
+ @SuppressWarnings({ "null", "static-access" })
+ public static void main(String args[]) {
+ String props = "NA";
+ if (args.length > 0) {
+ System.out.println( "DbTestProcessBuilder called with " + args.length + " arguments, " + args[0]);
+ props = args[0].trim();
+ } else {
+ System.out.print("usage: DbTestProcessBuilder <auditConfig.prop path\n");
+ return;
+ }
+ DbTestConfig.init(props);
+ String ail = DbTestConfig.get("audit.list");
+ String path = DbTestConfig.get("audit.path");
+ final String runningDir = DbTestConfig.get("audit.runningdir");
+ try {
+ DbTestGetFileTime getFileTime = new DbTestGetFileTime();
+ FileTime fileTime = getFileTime.createFileReturnTime( path );
+ System.out.println(path + " creation time :"
+ + new SimpleDateFormat("dd/MM/yyyy HH:mm:ss")
+ .format(fileTime.toMillis()) + " runningDir " + runningDir);
+ } catch ( IOException io ) {
+ System.out.println( "IOException getting creation time " + path + " message " + io.getMessage());
+ io.printStackTrace();
+ }
+
+ List<String> items = Arrays.asList(ail.split("\\s*,\\s*"));
+ for (String ai: items) {
+ if (!DbTestConfig.get("audit.task."+ai+".status").startsWith("a")) {
+ continue;
+ }
+//clog.debug("***audit item = " + ai + " Starting***");
+
+ String w1 = DbTestConfig.get("audit.task."+ai+".cmd");
+ String[] w2 = w1.split("\\s*,\\s*");
+ System.out.print( "task items are : " + Arrays.toString(w2));
+ // append the audit item name as the prefix of the audit directory name
+ /*final int N = w2.length;
+ w2 = Arrays.copyOf(w2, N+1);
+ w2[N-2] = "\"-Dp=" + DbTestConfig.get("audit.task.odl.output.dir")+ai + "\"";
+//clog.debug("***java -D:"+w2[N-2]);
+ //w2[N] = "\""+DbTestConfig.get("audit.task.odl.output.dir")+ai+"\"";
+ w2[N] = "\""+DbTestConfig.get("audit.task.odl.output.dir")+ai+"\"";
+ */
+ DbTestProcessBuilder apb = new DbTestProcessBuilder();
+
+ String ts1 = DbTestConfig.get("audit.task."+ai+".schedule");
+ String[] ts2 = ts1.split("\\s*,\\s*");
+ // note ts2[0] is the wait-before time, and it is not being used right now. We start with ts2[1]
+ apb.runWCommandEveryXSecondsForYMinutes(w2,Integer.parseInt(ts2[1]),Integer.parseInt(ts2[2]), runningDir);
+//clog.debug("***audit item = " + ai + " started***");
+ System.out.println( "started test " + ai);
+
+ /*
+ int ct = 0;
+
+ while (true) try {
+ if (DbTestConfig.get("jcl").startsWith("q")) {
+ System.out.println("***Audit Main Program exiting...");
+ System.exit(0);
+ }
+
+ Thread.currentThread().sleep(1000);
+ if (ct < 10) {
+ ct++;
+ } else {
+ //clog.debug(AuditConfig.get("jcl").charAt(0));
+ ct=0;
+ }
+
+ } catch (InterruptedException ie) {
+
+ } */
+ }
+ int ct = 0;
+
+ while (true) try {
+ if (DbTestConfig.get("jcl").startsWith("q")) {
+ System.out.println("***Audit Main Program exiting...");
+ System.exit(0);
+ }
+
+ Thread.currentThread().sleep(1000);
+ if (ct < 10) {
+ ct++;
+ } else {
+ //clog.debug(AuditConfig.get("jcl").charAt(0));
+ ct=0;
+ }
+
+ } catch (InterruptedException ie) {
+
+ }
+
+ }
+
+}
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/DeleteResourceTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/DeleteResourceTest.java
new file mode 100644
index 0000000..efe4a41
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/DeleteResourceTest.java
@@ -0,0 +1,107 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+
+
+import static org.junit.Assert.assertEquals;
+
+import static org.junit.Assert.assertFalse;
+
+import static org.junit.Assert.assertTrue;
+
+import static org.junit.Assert.fail;
+
+import org.junit.Ignore;
+import org.junit.Test;
+import org.openecomp.aai.util.DeleteResource;
+import org.openecomp.aai.domain.yang.PhysicalLink;
+
+
+
+public class DeleteResourceTest {
+
+
+
+ /**
+ * Test getInstance.
+ */
+
+ @Test
+
+ public void testGetInstance(){
+
+ Object obj = null;
+
+ try {
+
+ obj = DeleteResource.getInstance(DeleteResource.class);
+
+ } catch (IllegalAccessException | InstantiationException e) {
+
+ e.printStackTrace();
+
+ }
+
+ assertTrue("Didn't get right instance", obj instanceof DeleteResource);
+
+ }
+
+
+
+ /**
+ * Test GetResourceVersion.
+ */
+ @Ignore
+ @Test
+
+ public void testGetResourceVersion(){
+
+ String version = "aVersion";
+
+ PhysicalLink plink = new PhysicalLink();
+
+ plink.setResourceVersion(version);
+
+ assertEquals("Versions didn't match", version, DeleteResource.GetResourceVersion(plink));
+
+ }
+
+
+
+ /**
+ * Test null in GetResourceVersion.
+ */
+
+ @Test
+
+ public void testGetResourceVersion_withNull(){
+
+ PhysicalLink plink = new PhysicalLink();
+
+ assertEquals("Versions didn't match", null, DeleteResource.GetResourceVersion(plink));
+
+ }
+
+
+
+}
+
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/HbaseSaltPrefixerTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/HbaseSaltPrefixerTest.java
new file mode 100644
index 0000000..ff1b53b
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/HbaseSaltPrefixerTest.java
@@ -0,0 +1,40 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import static org.junit.Assert.*;
+
+import org.junit.Test;
+import org.openecomp.aai.util.HbaseSaltPrefixer;
+
+public class HbaseSaltPrefixerTest {
+
+ /**
+ * Test.
+ */
+ @Test
+ public void test() {
+ String key = "imakey";
+ String saltedKey = HbaseSaltPrefixer.getInstance().prependSalt(key);
+ assertTrue(saltedKey.equals("0-imakey"));
+ }
+
+}
diff --git a/ajsc-aai/src/test/java/org/openecomp/aai/util/JettyObfuscationConversionCommandLineUtilTest.java b/ajsc-aai/src/test/java/org/openecomp/aai/util/JettyObfuscationConversionCommandLineUtilTest.java
new file mode 100644
index 0000000..39fec9b
--- /dev/null
+++ b/ajsc-aai/src/test/java/org/openecomp/aai/util/JettyObfuscationConversionCommandLineUtilTest.java
@@ -0,0 +1,72 @@
+/*-
+ * ============LICENSE_START=======================================================
+ * org.openecomp.aai
+ * ================================================================================
+ * Copyright (C) 2017 AT&T Intellectual Property. 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=========================================================
+ */
+
+package org.openecomp.aai.util;
+
+import static org.junit.Assert.*;
+
+import java.io.ByteArrayOutputStream;
+import java.io.PrintStream;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import org.junit.Test;
+import org.openecomp.aai.util.JettyObfuscationConversionCommandLineUtil;
+
+
+public class JettyObfuscationConversionCommandLineUtilTest {
+ private final ByteArrayOutputStream testOut = new ByteArrayOutputStream();
+
+ /**
+ * Test.
+ */
+ @Test
+ public void test() {
+ //setup, this will catch main's print statements for evaluation
+ System.setOut(new PrintStream(testOut));
+
+ /* ------ TEST OBFUSCATION ----*/
+ JettyObfuscationConversionCommandLineUtil.main(new String[]{"-e", "hello world"});
+ /*
+ * testOut was also catching any logging statements which interfered with result checking.
+ * This regex business was the workaround - it tries to find the expected value in
+ * the results and asserts against that.
+ */
+ String obfResult = testOut.toString();
+ String obfExpected = "OBF:1thf1ugo1x151wfw1ylz11tr1ymf1wg21x1h1uh21th7";
+ Pattern obfExpectPat = Pattern.compile(obfExpected);
+ Matcher obfMatch = obfExpectPat.matcher(obfResult);
+ assertTrue(obfMatch.find());
+
+ testOut.reset(); //clear out previous result
+
+ /* ------ TEST DEOBFUSCATION ----- */
+ JettyObfuscationConversionCommandLineUtil.main(new String[]{"-d", obfExpected});
+ String deobfResult = testOut.toString();
+ String deobfExpected = "hello world";
+ Pattern deobfExpectPat = Pattern.compile(deobfExpected);
+ Matcher deobfMatch = deobfExpectPat.matcher(deobfResult);
+ assertTrue(deobfMatch.find());
+
+ //clean up, resets to stdout
+ System.setOut(null);
+ }
+
+}