diff options
Diffstat (limited to 'aai-resources/src/test/java/org/openecomp')
19 files changed, 2308 insertions, 0 deletions
diff --git a/aai-resources/src/test/java/org/openecomp/aai/query/builder/TraversalQueryTest.java b/aai-resources/src/test/java/org/openecomp/aai/query/builder/TraversalQueryTest.java new file mode 100644 index 0000000..694e99e --- /dev/null +++ b/aai-resources/src/test/java/org/openecomp/aai/query/builder/TraversalQueryTest.java @@ -0,0 +1,105 @@ +/*- + * ============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.query.builder; + +import static org.junit.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mock; + +import org.openecomp.aai.db.props.AAIProperties; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Introspector; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +//import org.openecomp.aai.serialization.queryformats.QueryFormatTestHelper; +import org.openecomp.aai.util.AAIConstants; + +public class TraversalQueryTest { + + public static Loader loader; + @Mock public GraphTraversalSource g; + @BeforeClass + public static void configure() throws NoSuchFieldException, SecurityException, Exception { + + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); +// QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/org/openecomp/aai/introspection/"); + loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); + } + + @Test + public void unionQuery() { + TraversalQuery tQ = new TraversalQuery(loader, g); + TraversalQuery tQ2 = new TraversalQuery(loader, g); + TraversalQuery tQ3 = new TraversalQuery(loader, g); + tQ.union( + tQ2.getVerticesByProperty("test1", "value1"), + tQ3.getVerticesByIndexedProperty("test2", "value2")); + + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .union(__.has("test1", "value1"),__.has("test2", "value2")); + + assertEquals("they are equal", expected, tQ.getQuery()); + + } + + @Test + @Ignore + public void traversalClones() throws UnsupportedEncodingException, AAIException, URISyntaxException { + TraversalQuery tQ = new TraversalQuery(loader, g); + Introspector test = loader.introspectorFromName("test-object"); + QueryBuilder builder = tQ.createQueryFromURI(new URI("network/test-objects/test-object/key1")).getQueryBuilder(); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("vnf-id", "key1").has("aai-node-type", "test-object"); + GraphTraversal<Vertex, Vertex> containerExpected = __.<Vertex>start().has("aai-node-type", "test-object"); + + assertEquals("query object", expected.toString(), builder.getQuery().toString()); + assertEquals("container query object", containerExpected.toString(), builder.getContainerQuery().getQuery().toString()); + + } + + @Test + public void nestedTraversalClones() throws UnsupportedEncodingException, AAIException, URISyntaxException { + + TraversalQuery tQ = new TraversalQuery(loader, g); + QueryBuilder builder = tQ.createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1/l-interfaces/l-interface/key2")).getQueryBuilder(); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("vnf-id", "key1").has("aai-node-type", "generic-vnf").out("hasLInterface").has(AAIProperties.NODE_TYPE, "l-interface").has("interface-name", "key2"); + GraphTraversal<Vertex, Vertex> containerExpected = __.<Vertex>start().has("vnf-id", "key1").has("aai-node-type", "generic-vnf").out("hasLInterface").has(AAIProperties.NODE_TYPE, "l-interface"); + + assertEquals("query object", expected.toString(), builder.getQuery().toString()); + assertEquals("container query object", containerExpected.toString(), builder.getContainerQuery().getQuery().toString()); + + } + + + +} diff --git a/aai-resources/src/test/java/org/openecomp/aai/rest/util/ValidateEncodingTest.java b/aai-resources/src/test/java/org/openecomp/aai/rest/util/ValidateEncodingTest.java new file mode 100644 index 0000000..8c6450d --- /dev/null +++ b/aai-resources/src/test/java/org/openecomp/aai/rest/util/ValidateEncodingTest.java @@ -0,0 +1,101 @@ +/*- + * ============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.rest.util; + +import static org.junit.Assert.*; + +import java.io.UnsupportedEncodingException; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriInfo; + +import org.junit.Test; +import org.mockito.Mockito; + +public class ValidateEncodingTest { + + + @Test + public void badPath() throws UnsupportedEncodingException { + String badPath = "/aai/v6/network/vces/vce/blahh::blach/others/other/jklfea{}"; + UriInfo mockUriInfo = getMockUriInfo(badPath, new MultivaluedHashMap<String, String>()); + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(false, validator.validate(mockUriInfo)); + } + + @Test + public void goodPath() throws UnsupportedEncodingException { + String goodPath = "/aai/v6/network/vces/vce/blahh%3A%3Ablach/others/other/jklfea%7B%7D"; + UriInfo mockUriInfo = getMockUriInfo(goodPath, new MultivaluedHashMap<String, String>()); + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(true, validator.validate(mockUriInfo)); + } + + @Test + public void badQueryParamsKey() throws UnsupportedEncodingException { + MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>(); + map.putSingle("blahblah", "test"); + map.putSingle("blahblah", "test2"); + map.putSingle("bad::bad", "test3"); + UriInfo mockUriInfo = getMockUriInfo("", map); + + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(false, validator.validate(mockUriInfo)); + + } + @Test + public void badQueryParamsValue() throws UnsupportedEncodingException { + MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>(); + map.putSingle("blahblah", "test"); + map.putSingle("blahblah", "test//:2"); + map.putSingle("badbad", "test3"); + UriInfo mockUriInfo = getMockUriInfo("", map); + + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(false, validator.validate(mockUriInfo)); + } + @Test + public void goodQueryParams() throws UnsupportedEncodingException { + MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>(); + map.putSingle("blahblah", "test"); + map.putSingle("blahblah", "test2"); + map.putSingle("badbad", "~test%2F%2F%3A3"); + UriInfo mockUriInfo = getMockUriInfo("", map); + + ValidateEncoding validator = ValidateEncoding.getInstance(); + + assertEquals(true, validator.validate(mockUriInfo)); + } + + private UriInfo getMockUriInfo(String path, MultivaluedMap<String, String> map) { + UriInfo mockUriInfo = Mockito.mock(UriInfo.class); + Mockito.when(mockUriInfo.getPath(false)).thenReturn(path); + Mockito.when(mockUriInfo.getQueryParameters(false)).thenReturn(map); + + return mockUriInfo; + } + +} diff --git a/aai-resources/src/test/java/org/openecomp/aai/schema/db/AuditOXMTest.java b/aai-resources/src/test/java/org/openecomp/aai/schema/db/AuditOXMTest.java new file mode 100644 index 0000000..8188bdd --- /dev/null +++ b/aai-resources/src/test/java/org/openecomp/aai/schema/db/AuditOXMTest.java @@ -0,0 +1,94 @@ +/*- + * ============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.schema.db; + +import java.io.IOException; + +import org.codehaus.jackson.JsonGenerationException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import org.openecomp.aai.db.schema.AuditDoc; +import org.openecomp.aai.db.schema.AuditOXM; +import org.openecomp.aai.db.schema.Auditor; +import org.openecomp.aai.db.schema.AuditorFactory; +import org.openecomp.aai.introspection.Version; +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; + +@Ignore("not ready for testing") +public class AuditOXMTest { + + /** + * Before. + */ + @BeforeClass + public static void before() { + System.setProperty("AJSC_HOME", "./src/test/resources/");; + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + + } + + + /** + * Gets the graph audit. + * + * @return the graph audit + * @throws JsonGenerationException the json generation exception + * @throws JsonMappingException the json mapping exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void getGraphAudit() throws JsonGenerationException, JsonMappingException, IOException { + TitanGraph graph = TitanFactory.open("bundleconfig-local/etc/appprops/aaiconfig.properties"); + Auditor a = AuditorFactory.getGraphAuditor(graph); + AuditDoc doc = a.getAuditDoc(); + + ObjectMapper mapper = new ObjectMapper(); + + String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(doc); + System.out.println(json); + + } + + /** + * Gets the audit. + * + * @return the audit + * @throws JsonGenerationException the json generation exception + * @throws JsonMappingException the json mapping exception + * @throws IOException Signals that an I/O exception has occurred. + */ + @Test + public void getAudit() throws JsonGenerationException, JsonMappingException, IOException { + AuditOXM oxm = new AuditOXM(Version.v8); + + AuditDoc doc = oxm.getAuditDoc(); + + ObjectMapper mapper = new ObjectMapper(); + + String json = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(doc); + System.out.println(json); + } +} diff --git a/aai-resources/src/test/java/org/openecomp/aai/schema/db/ManageSchemaTest.java b/aai-resources/src/test/java/org/openecomp/aai/schema/db/ManageSchemaTest.java new file mode 100644 index 0000000..9b7dd7c --- /dev/null +++ b/aai-resources/src/test/java/org/openecomp/aai/schema/db/ManageSchemaTest.java @@ -0,0 +1,120 @@ +/*- + * ============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.schema.db; + +import java.io.IOException; +import java.util.Set; + +import org.codehaus.jackson.JsonParseException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import org.openecomp.aai.db.schema.DBIndex; +import org.openecomp.aai.db.schema.ManageTitanSchema; +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.schema.TitanManagement; + +@Ignore("not ready yet") +public class ManageSchemaTest { + + private TitanGraph graph = null; + @BeforeClass + public static void before() { + System.setProperty("AJSC_HOME", "./src/test/resources/");; + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + + } + + @Before + public void beforeTest() { + //graph = TitanFactory.open("src/test/resources/inmemory_titan.properties"); + graph = TitanFactory.open("bundleconfig-local/etc/appprops/aaiconfig.properties"); + } + + /* + @Test + public void populateEmptyGraph() { + ManageTitanSchema schema = new ManageTitanSchema(graph); + schema.buildSchema(); + } + + @Test + public void modifyIndex() { + ManageTitanSchema schema = new ManageTitanSchema(graph); + schema.buildSchema(); + Vertex v = graph.addVertex(); + v.setProperty("aai-node-type", "pserver"); + v.setProperty("hostname", "test1"); + v.setProperty("internet-topology", "test2"); + graph.commit(); + DBIndex index = new DBIndex(); + index.setName("internet-topology"); + index.setUnique(false); + schema.updateIndex(index); + + } + */ + @Test + public void closeRunningInstances() { + + TitanManagement mgmt = graph.openManagement(); + Set<String> instances = mgmt.getOpenInstances(); + + for (String instance : instances) { + + if (!instance.contains("(current)")) { + mgmt.forceCloseInstance(instance); + } + } + mgmt.commit(); + + graph.close(); + + } + @Test + public void addNewIndex() throws JsonParseException, JsonMappingException, IOException { + ObjectMapper mapper = new ObjectMapper(); + String content = " {\r\n" + + " \"name\" : \"equipment-name\",\r\n" + + " \"unique\" : false,\r\n" + + " \"properties\" : [ {\r\n" + + " \"name\" : \"equipment-name\",\r\n" + + " \"cardinality\" : \"SINGLE\",\r\n" + + " \"typeClass\" : \"java.lang.String\"\r\n" + + " } ]\r\n" + + " }"; + DBIndex index = mapper.readValue(content, DBIndex.class); + ManageTitanSchema schema = new ManageTitanSchema(graph); + TitanManagement mgmt = graph.openManagement(); + Set<String> instances = mgmt.getOpenInstances(); + System.out.println(instances); + schema.updateIndex(index); + + graph.close(); + + } + +} diff --git a/aai-resources/src/test/java/org/openecomp/aai/util/AAIApiServerURLBaseTest.java b/aai-resources/src/test/java/org/openecomp/aai/util/AAIApiServerURLBaseTest.java new file mode 100644 index 0000000..394f636 --- /dev/null +++ b/aai-resources/src/test/java/org/openecomp/aai/util/AAIApiServerURLBaseTest.java @@ -0,0 +1,85 @@ +/*- + * ============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.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/aai-resources/src/test/java/org/openecomp/aai/util/AAIApiVersionTest.java b/aai-resources/src/test/java/org/openecomp/aai/util/AAIApiVersionTest.java new file mode 100644 index 0000000..f82fc5d --- /dev/null +++ b/aai-resources/src/test/java/org/openecomp/aai/util/AAIApiVersionTest.java @@ -0,0 +1,90 @@ +/*- + * ============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.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/aai-resources/src/test/java/org/openecomp/aai/util/AAIAppServletContextListenerTest.java b/aai-resources/src/test/java/org/openecomp/aai/util/AAIAppServletContextListenerTest.java new file mode 100644 index 0000000..deafd5b --- /dev/null +++ b/aai-resources/src/test/java/org/openecomp/aai/util/AAIAppServletContextListenerTest.java @@ -0,0 +1,178 @@ +/*- + * ============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.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 org.openecomp.aai.dbmap.AAIGraph; +import org.openecomp.aai.logging.ErrorLogHelper; + +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/aai-resources/src/test/java/org/openecomp/aai/util/AAICSVWriterTest.java b/aai-resources/src/test/java/org/openecomp/aai/util/AAICSVWriterTest.java new file mode 100644 index 0000000..c3e525c --- /dev/null +++ b/aai-resources/src/test/java/org/openecomp/aai/util/AAICSVWriterTest.java @@ -0,0 +1,177 @@ +/*- + * ============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.junit.Assert.fail; + +import java.io.File; +import java.io.FileNotFoundException; +import java.io.FileWriter; +import java.io.IOException; +import java.io.PrintWriter; +import java.io.Writer; +import java.nio.file.Files; +import java.nio.file.Paths; + +import org.junit.After; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.powermock.modules.agent.PowerMockAgent; +import org.powermock.modules.junit4.rule.PowerMockRule; + +public class AAICSVWriterTest { + + @Rule + public PowerMockRule rule = new PowerMockRule(); + + static { + PowerMockAgent.initializeIfNeeded(); + } + + + Writer writer; + File f; + AAICSVWriter testObj; + String fileName = "test_csvWriter.csv"; + String lineEnd = "\n"; + char quoteChar = '\"'; + String separator = ","; + String str1[], str2[]; + + /** + * Initialize. + */ + @Before + public void initialize(){ + str1 = new String[]{"s0", "s1"}; + + str2 = new String[]{"t0", "t1"}; + + try { + f = new File(fileName); + f.createNewFile(); + writer = new PrintWriter(f); + testObj = new AAICSVWriter(new FileWriter(fileName), separator, quoteChar, lineEnd); + } catch (FileNotFoundException e) { + fail("Input csv file not found."); + e.printStackTrace(); + } catch (IOException e) { + fail("Can't create csv file."); + e.printStackTrace(); + } + } + + /** + * Test writeNextLine with String arrays. + */ + @Test + public void testWriteNextLine(){ + populateAndGetFileSize(false, str1, str2); + String wholeText = str1[0] + separator + str1[1] + lineEnd + str2[0] + separator + str2[1] + lineEnd; + assertTrue("CSV file missing text", allLinesFound(wholeText)); + } + + /** + * Test writeNextLine with null. + */ + @Test + public void testWriteNextLine_withNull(){ + populateAndGetFileSize(false, null, null); + assertTrue("CSV file should not contain any text", f.length() == 0); + } + + + /** + * Test writeColumn with String arrays. + */ + @Test + public void testWriteColumn(){ + populateAndGetFileSize(true, str1, str2); + String wholeText = str1[0] + str1[1] + lineEnd + str2[0] + str2[1] + lineEnd; + assertTrue("CSV file missing text", allLinesFound(wholeText)); + } + + + /** + * Test writeColumn with null. + */ + @Test + public void testWriteColumn_withNull(){ + populateAndGetFileSize(true, null, null); + assertTrue("CSV file should not contain any text", f.length() == 0); + } + + /** + * Helper method to create file with given data. + * + * @param isColumnWise True if csv file is to be written in column wise, false otherwise + * @param c1 First set of data + * @param c2 Second set of data + */ + private void populateAndGetFileSize(boolean isColumnWise, String c1[], String c2[]){ + if ( isColumnWise ){ + testObj.writeColumn(c1); + testObj.writeColumn(c2); + } else{ + testObj.writeNext(c1, false); + testObj.writeNext(c2, false); + } + try { + testObj.close(); + } catch (IOException e) { + fail("Can't close stream"); + e.printStackTrace(); + } + } + + + /** + * Helper method to check if a file contains required data. + * + * @param all Data to look for + * @return True if data is found, false otherwise + */ + private boolean allLinesFound(String all){ + String fileContents = ""; + try { + fileContents = new String(Files.readAllBytes(Paths.get(fileName))); + } catch (IOException e1) { + fail("csv file not found"); + e1.printStackTrace(); + } + + return all.equals(fileContents); + } + + + /** + * Cleanup. + */ + @After + public void cleanup(){ + if ( f.exists() ){ + f.delete(); + } + } + +} diff --git a/aai-resources/src/test/java/org/openecomp/aai/util/AAIConfigPasswordDecodingTest.java b/aai-resources/src/test/java/org/openecomp/aai/util/AAIConfigPasswordDecodingTest.java new file mode 100644 index 0000000..bdf0fb1 --- /dev/null +++ b/aai-resources/src/test/java/org/openecomp/aai/util/AAIConfigPasswordDecodingTest.java @@ -0,0 +1,53 @@ +/*- + * ============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.Test; + +import org.openecomp.aai.exceptions.AAIException; + +public class AAIConfigPasswordDecodingTest { + + /** + * Configure. + * + * @throws AAIException the AAI exception + */ + @BeforeClass + public static void configure() throws AAIException { + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local");; //fake prop file for testing + } + + /** + * Password check. + * + * @throws AAIException the AAI exception + */ + @Test + public void passwordCheck() throws AAIException { + assertEquals("password", "aaiuser123", AAIConfig.get("ecm.auth.password")); + } + +} diff --git a/aai-resources/src/test/java/org/openecomp/aai/util/AAIRSyncUtilityTest.java b/aai-resources/src/test/java/org/openecomp/aai/util/AAIRSyncUtilityTest.java new file mode 100644 index 0000000..c15a99f --- /dev/null +++ b/aai-resources/src/test/java/org/openecomp/aai/util/AAIRSyncUtilityTest.java @@ -0,0 +1,221 @@ +/*- + * ============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.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.aai.exceptions.AAIException; + +@Ignore +public class AAIRSyncUtilityTest { + + AAIRSyncUtility syncUtil; + AAIRSyncUtility syncUtilOmitDoCommand; + AAIConfig aaiConfig; + String hostName; + String transId = UUID.randomUUID().toString(); + + @BeforeClass + public static void configure() throws AAIException { + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local");; //fake prop file for testing + } + + /** + * 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. + */ + @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/bundleconfig-local/etc/appprops/aaiconfig.properties"); + } + catch (SecurityException e) {fail();} + catch (NoSuchFieldException e) {fail();} + catch (Exception e) {fail();} + + AAIConfig.reloadConfig(); + } + +} diff --git a/aai-resources/src/test/java/org/openecomp/aai/util/AAIUtilsTest.java b/aai-resources/src/test/java/org/openecomp/aai/util/AAIUtilsTest.java new file mode 100644 index 0000000..0bba892 --- /dev/null +++ b/aai-resources/src/test/java/org/openecomp/aai/util/AAIUtilsTest.java @@ -0,0 +1,112 @@ +/*- + * ============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.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/aai-resources/src/test/java/org/openecomp/aai/util/CNNameTest.java b/aai-resources/src/test/java/org/openecomp/aai/util/CNNameTest.java new file mode 100644 index 0000000..8f3cfa5 --- /dev/null +++ b/aai-resources/src/test/java/org/openecomp/aai/util/CNNameTest.java @@ -0,0 +1,138 @@ +/*- + * ============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.mockito.Mockito; +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.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; + org.openecomp.aai.logging.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 org.openecomp.aai.logging.CNName getTestObj(final boolean instanceStarted){ + return new org.openecomp.aai.logging.CNName(){ + @Override + public boolean isStarted(){ + return instanceStarted; + } + }; + } +} + + + diff --git a/aai-resources/src/test/java/org/openecomp/aai/util/CustomLogPatternLayoutTest.java b/aai-resources/src/test/java/org/openecomp/aai/util/CustomLogPatternLayoutTest.java new file mode 100644 index 0000000..e087108 --- /dev/null +++ b/aai-resources/src/test/java/org/openecomp/aai/util/CustomLogPatternLayoutTest.java @@ -0,0 +1,51 @@ +/*- + * ============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.openecomp.aai.logging.CNName; +import org.openecomp.aai.logging.CustomLogPatternLayout; +import org.junit.Test; + +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'", org.openecomp.aai.logging.CNName.class.getName().equals(s)); + } + +} diff --git a/aai-resources/src/test/java/org/openecomp/aai/util/DbTestConfig.java b/aai-resources/src/test/java/org/openecomp/aai/util/DbTestConfig.java new file mode 100644 index 0000000..4f84519 --- /dev/null +++ b/aai-resources/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/aai-resources/src/test/java/org/openecomp/aai/util/DbTestFileWatcher.java b/aai-resources/src/test/java/org/openecomp/aai/util/DbTestFileWatcher.java new file mode 100644 index 0000000..05a4cfe --- /dev/null +++ b/aai-resources/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/aai-resources/src/test/java/org/openecomp/aai/util/DbTestGetFileTime.java b/aai-resources/src/test/java/org/openecomp/aai/util/DbTestGetFileTime.java new file mode 100644 index 0000000..d56a4d2 --- /dev/null +++ b/aai-resources/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/aai-resources/src/test/java/org/openecomp/aai/util/DbTestProcessBuilder.java b/aai-resources/src/test/java/org/openecomp/aai/util/DbTestProcessBuilder.java new file mode 100644 index 0000000..8d8ebe0 --- /dev/null +++ b/aai-resources/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/aai-resources/src/test/java/org/openecomp/aai/util/HbaseSaltPrefixerTest.java b/aai-resources/src/test/java/org/openecomp/aai/util/HbaseSaltPrefixerTest.java new file mode 100644 index 0000000..4e19c35 --- /dev/null +++ b/aai-resources/src/test/java/org/openecomp/aai/util/HbaseSaltPrefixerTest.java @@ -0,0 +1,39 @@ +/*- + * ============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; + +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/aai-resources/src/test/java/org/openecomp/aai/workarounds/LegacyURITransformerTest.java b/aai-resources/src/test/java/org/openecomp/aai/workarounds/LegacyURITransformerTest.java new file mode 100644 index 0000000..25dc648 --- /dev/null +++ b/aai-resources/src/test/java/org/openecomp/aai/workarounds/LegacyURITransformerTest.java @@ -0,0 +1,104 @@ +/*- + * ============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.workarounds; + +import static org.junit.Assert.assertEquals; + +import java.io.File; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; + +import org.junit.BeforeClass; +import org.junit.Test; + +import org.openecomp.aai.introspection.Version; + + +public class LegacyURITransformerTest { + + private LegacyURITransformer uriTransformer = LegacyURITransformer.getInstance(); + private String fromSuccess = "http://myhostname.com:8443/aai/{version}/cloud-infrastructure/tenants/tenant/key1/vservers/vserver/key2"; + private String toSuccess = "http://myhostname.com:8443/aai/servers/{version}/key1/vservers/key2"; + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + + /** + * Test spec. + * + * @param version the version + * @param toExpected the to expected + * @param fromExpected the from expected + * @throws URISyntaxException + * @throws MalformedURLException the malformed URL exception + */ + public void testSpec(Version version, String toExpected, String fromExpected) throws URISyntaxException { + + URI toExpectedUri = new URI(toExpected.replace("{version}",version.toString())); + URI fromExpectedUri = new URI(fromExpected.replace("{version}",version.toString())); + + URI result = toLegacyURISpec(version, fromExpectedUri); + + assertEquals("to", toExpectedUri, result); + + result = fromLegacyURISpec(version, toExpectedUri); + + assertEquals("from", fromExpectedUri, result); + } + + + /** + * To legacy URL spec. + * + * @param version the version + * @param url the url + * @return the url + * @throws URISyntaxException + * @throws MalformedURLException the malformed URL exception + */ + public URI toLegacyURISpec(Version version, URI uri) throws URISyntaxException { + return uri; + } + + /** + * From legacy URL spec. + * + * @param version the version + * @param url the url + * @return the url + * @throws URISyntaxException + * @throws MalformedURLException the malformed URL exception + */ + public URI fromLegacyURISpec(Version version, URI uri) throws URISyntaxException { + return uri; + } + + +} |