diff options
author | Venkata Harish K Kajur <vk250x@att.com> | 2017-09-28 13:56:02 -0400 |
---|---|---|
committer | Venkata Harish K Kajur <vk250x@att.com> | 2017-09-28 17:46:16 -0400 |
commit | b33b55b16d1c230fb1bf454d7d517f2c2d57941b (patch) | |
tree | 4802fbdf61c2e8c1cf19c35cd3dc9b0df96d5ed3 /aai-resources/src/test/java/org/onap | |
parent | 9d5eff1a6c19f9af9329f76f3e58d8935eb28dad (diff) |
Change package names org.openecomp to org.onap
Issue-ID: AAI-61 AAI-82
Change-Id: Ib1d937fb31b1e737c4651eac9c0193fd05d97f01
Signed-off-by: Venkata Harish K Kajur <vk250x@att.com>
Diffstat (limited to 'aai-resources/src/test/java/org/onap')
36 files changed, 4515 insertions, 0 deletions
diff --git a/aai-resources/src/test/java/org/onap/aai/AAISetup.java b/aai-resources/src/test/java/org/onap/aai/AAISetup.java new file mode 100644 index 0000000..65048eb --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/AAISetup.java @@ -0,0 +1,58 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai; + +import org.apache.commons.io.IOUtils; +import org.junit.BeforeClass; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.introspection.ModelInjestor; +import org.onap.aai.serialization.queryformats.QueryFormatTestHelper; +import org.onap.aai.util.AAIConstants; + +import java.io.IOException; +import java.io.InputStream; + +import static org.junit.Assert.assertNotNull; + +public abstract class AAISetup { + + @BeforeClass + public static void setupBundleconfig() throws Exception { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "src/test/resources/bundleconfig-local"); + QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), + "src/test/resources/bundleconfig-local/etc/oxm/"); + } + + public String getPayload(String filename) throws IOException { + + InputStream inputStream = getClass() + .getClassLoader() + .getResourceAsStream(filename); + + String message = String.format("Unable to find the %s in src/test/resources", filename); + assertNotNull(message, inputStream); + + String resource = IOUtils.toString(inputStream); + return resource; + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/interceptors/AAILogJAXRSInInterceptorTest.java b/aai-resources/src/test/java/org/onap/aai/interceptors/AAILogJAXRSInInterceptorTest.java new file mode 100644 index 0000000..3b1dac2 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/interceptors/AAILogJAXRSInInterceptorTest.java @@ -0,0 +1,60 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.interceptors; + +import org.apache.cxf.message.Exchange; +import org.apache.cxf.message.ExchangeImpl; +import org.apache.cxf.message.Message; +import org.junit.Before; +import org.junit.Test; +import org.onap.aai.AAISetup; + +import java.io.IOException; +import java.io.InputStream; + +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class AAILogJAXRSInInterceptorTest extends AAISetup { + + private AAILogJAXRSInInterceptor aaiLogJAXRSInInterceptor; + + @Before + public void setup(){ + aaiLogJAXRSInInterceptor = new AAILogJAXRSInInterceptor(); + } + + @Test + public void testHandleMessageWhenNotCamelRequest() throws IOException { + + Message message = mock(Message.class); + Exchange exchange = new ExchangeImpl(); + InputStream is = getClass().getClassLoader().getResourceAsStream("logback.xml"); + + when(message.getExchange()).thenReturn(exchange); + when(message.getContent(InputStream.class)).thenReturn(is); + +// when(message.get(Message.QUERY_STRING)).thenReturn("/somestring"); + when(message.get("CamelHttpUrl")).thenReturn("/somestring"); + aaiLogJAXRSInInterceptor.handleMessage(message); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/interceptors/PostAaiAjscInterceptorTest.java b/aai-resources/src/test/java/org/onap/aai/interceptors/PostAaiAjscInterceptorTest.java new file mode 100644 index 0000000..2842e26 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/interceptors/PostAaiAjscInterceptorTest.java @@ -0,0 +1,74 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.interceptors; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.logging.LoggingContext; + +import javax.servlet.http.HttpServletRequest; + +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertTrue; + +public class PostAaiAjscInterceptorTest { + + private PostAaiAjscInterceptor postAaiAjscInterceptor; + + @Before + public void setup(){ + postAaiAjscInterceptor = new PostAaiAjscInterceptor(); + } + + @Test + public void getInstance() throws Exception { + PostAaiAjscInterceptor interceptor = PostAaiAjscInterceptor.getInstance(); + assertNotNull(interceptor); + } + + @Test + public void testAllowOrRejectIfSuccess() throws Exception { + + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + LoggingContext.put(LoggingContext.LoggingField.RESPONSE_CODE.toString(), "SUCCESS"); + Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("/fadsjoifj")); + + boolean success = postAaiAjscInterceptor.allowOrReject(request, null, null); + + assertTrue("Expecting the post interceptor to return success regardless", success); + } + + @Test + public void testAllowOrRejectIfFailure() throws Exception { + + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + LoggingContext.put(LoggingContext.LoggingField.RESPONSE_CODE.toString(), "ERR."); + Mockito.when(request.getRequestURL()).thenReturn(new StringBuffer("/fadsjoifj")); + + boolean success = postAaiAjscInterceptor.allowOrReject(request, null, null); + + assertTrue("Expecting the post interceptor to return success regardless", success); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/interceptors/PreAaiAjscInterceptorTest.java b/aai-resources/src/test/java/org/onap/aai/interceptors/PreAaiAjscInterceptorTest.java new file mode 100644 index 0000000..49b5664 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/interceptors/PreAaiAjscInterceptorTest.java @@ -0,0 +1,62 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.interceptors; + +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; + +import javax.servlet.http.HttpServletRequest; + +import static org.junit.Assert.*; +import static org.mockito.Matchers.anyString; + +public class PreAaiAjscInterceptorTest { + + private PreAaiAjscInterceptor preAaiAjscInterceptor; + + @Before + public void setup(){ + preAaiAjscInterceptor = new PreAaiAjscInterceptor(); + } + + @Test + public void getInstance() throws Exception { + PreAaiAjscInterceptor interceptor = PreAaiAjscInterceptor.getInstance(); + assertNotNull(interceptor); + } + + @Test + public void testAllowOrRejectIfSuccess() throws Exception { + + HttpServletRequest request = Mockito.mock(HttpServletRequest.class); + + Mockito.when(request.getRequestURI()).thenReturn("/fadsjoifj"); + Mockito.when(request.getHeader(anyString())).thenReturn("JUNIT-Test"); + Mockito.when(request.getMethod()).thenReturn("GET"); + + boolean success = preAaiAjscInterceptor.allowOrReject(request, null, null); + + assertTrue("Expecting the post interceptor to return success regardless", success); + } + +} diff --git a/aai-resources/src/test/java/org/onap/aai/migration/VertexMergeTest.java b/aai-resources/src/test/java/org/onap/aai/migration/VertexMergeTest.java new file mode 100644 index 0000000..9e68965 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/migration/VertexMergeTest.java @@ -0,0 +1,181 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.migration; + +import com.thinkaurelius.titan.core.Cardinality; +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.schema.TitanManagement; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.*; +import org.onap.aai.AAISetup; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.dbmap.DBConnectionType; +import org.onap.aai.introspection.Loader; +import org.onap.aai.introspection.LoaderFactory; +import org.onap.aai.introspection.ModelType; +import org.onap.aai.introspection.Version; +import org.onap.aai.serialization.db.DBSerializer; +import org.onap.aai.serialization.db.EdgeRules; +import org.onap.aai.serialization.engines.QueryStyle; +import org.onap.aai.serialization.engines.TitanDBEngine; +import org.onap.aai.serialization.engines.TransactionalGraphEngine; + +import java.io.UnsupportedEncodingException; +import java.util.*; + +import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder; +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertThat; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +@Ignore +public class VertexMergeTest extends AAISetup { + + + private final static Version version = Version.v10; + private final static ModelType introspectorFactoryType = ModelType.MOXY; + private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL; + private final static DBConnectionType type = DBConnectionType.REALTIME; + private Loader loader; + private TransactionalGraphEngine dbEngine; + private TitanGraph graph; + private EdgeRules rules; + private GraphTraversalSource g; + private Graph tx; + + @Before + public void setUp() throws Exception { + graph = TitanFactory.build().set("storage.backend","inmemory").open(); + tx = graph.newTransaction(); + g = tx.traversal(); + loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); + dbEngine = new TitanDBEngine( + queryStyle, + type, + loader); + rules = EdgeRules.getInstance(); + + TitanManagement mgmt = graph.openManagement(); + mgmt.makePropertyKey("test-list").dataType(String.class).cardinality(Cardinality.SET).make(); + mgmt.commit(); + Vertex pserverSkeleton = g.addV().property("aai-node-type", "pserver").property("hostname", "TEST1") + .property("source-of-truth", "AAI-EXTENSIONS").property("fqdn", "test1.com").property("test-list", "value1").next(); + + Vertex pInterface1 = g.addV().property("aai-node-type", "p-interface").property("interface-name", "p-interface1") + .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/TEST1/p-interfaces/p-interface/p-interface1").next(); + + Vertex pInterface2 = g.addV().property("aai-node-type", "p-interface").property("interface-name", "p-interface2") + .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/TEST1/p-interfaces/p-interface/p-interface2").next(); + + Vertex pInterface2Secondary = g.addV().property("aai-node-type", "p-interface").property("interface-name", "p-interface2").property("special-prop", "value") + .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/TEST1/p-interfaces/p-interface/p-interface2").next(); + + Vertex lInterface1 = g.addV().property("aai-node-type", "l-interface").property("interface-name", "l-interface1").property("special-prop", "value") + .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/TEST1/p-interfaces/p-interface/p-interface2/l-interfaces/l-interface/l-interface1").next(); + + Vertex lInterface1Canopi = g.addV().property("aai-node-type", "l-interface").property("interface-name", "l-interface1") + .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/TEST1/p-interfaces/p-interface/p-interface2/l-interfaces/l-interface/l-interface1").next(); + + Vertex logicalLink = g.addV().property("aai-node-type", "logical-link").property("link-name", "logical-link1") + .property(AAIProperties.AAI_URI, "/network/logical-links/logical-link/logical-link1").next(); + Vertex pserverCanopi = g.addV().property("aai-node-type", "pserver").property("hostname", "TEST1") + .property("source-of-truth", "CANOPI-WS").property("fqdn", "test2.com").property("test-list", "value2").next(); + + Vertex complex1 = g.addV().property("aai-node-type", "complex").property("physical-location-id", "complex1") + .property("source-of-truth", "RO").next(); + + Vertex complex2 = g.addV().property("aai-node-type", "complex").property("physical-location-id", "complex2") + .property("source-of-truth", "RCT").next(); + + Vertex vserver1 = g.addV().property("aai-node-type", "vserver").property("vserver-id", "vserver1") + .property("source-of-truth", "RO").next(); + + Vertex vserver2 = g.addV().property("aai-node-type", "vserver").property("vserver-id", "vserver2") + .property("source-of-truth", "RCT").next(); + Vertex vserver3 = g.addV().property("aai-node-type", "vserver").property("vserver-id", "vserver3") + .property("source-of-truth", "RCT").next(); + Vertex vserver4 = g.addV().property("aai-node-type", "vserver").property("vserver-id", "vserver4") + .property("source-of-truth", "RCT").next(); + Vertex vserver5 = g.addV().property("aai-node-type", "vserver").property("vserver-id", "vserver5") + .property("source-of-truth", "RCT").next(); + + + rules.addEdge(g, pserverSkeleton, complex1); + rules.addEdge(g, pserverSkeleton, vserver1); + rules.addEdge(g, pserverSkeleton, vserver2); + rules.addTreeEdge(g, pserverSkeleton, pInterface1); + rules.addTreeEdge(g, pserverSkeleton, pInterface2Secondary); + rules.addTreeEdge(g, pInterface2Secondary, lInterface1); + rules.addEdge(g, lInterface1, logicalLink); + rules.addEdge(g, pserverCanopi, complex2); + rules.addEdge(g, pserverCanopi, vserver3); + rules.addEdge(g, pserverCanopi, vserver4); + rules.addEdge(g, pserverCanopi, vserver5); + rules.addTreeEdge(g, pserverCanopi, pInterface2); + rules.addTreeEdge(g, pInterface2, lInterface1Canopi); + + Map<String, Set<String>> forceCopy = new HashMap<>(); + Set<String> forceSet = new HashSet<>(); + forceSet.add("fqdn"); + forceCopy.put("pserver", forceSet); + + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + GraphTraversalSource traversal = g; + GraphTraversalSource readOnly = g; + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(adminSpy.getReadOnlyTraversalSource()).thenReturn(readOnly); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "Merge test"); + + VertexMerge merge = new VertexMerge.Builder(loader, spy, serializer).build(); + merge.performMerge(pserverCanopi, pserverSkeleton, forceCopy); + } + + @After + public void cleanUp() { + tx.tx().rollback(); + graph.close(); + } + + @Test + public void run() throws UnsupportedEncodingException { + + assertEquals("pserver merged", false, g.V().has("hostname", "TEST1").has("source-of-truth", "AAI-EXTENSIONS").hasNext()); + assertThat("pserver list merge", Arrays.asList("value1", "value2"), containsInAnyOrder(g.V().has("hostname", "TEST1").values("test-list").toList().toArray())); + assertEquals("canopi pserver has one edge to vserver2", 1, g.V().has("hostname", "TEST1").both().has("vserver-id", "vserver2").toList().size()); + assertEquals("canopi pserver has one edge to vserver1", 1, g.V().has("hostname", "TEST1").both().has("vserver-id", "vserver1").toList().size()); + assertEquals("canopi pserver retained edge to complex2", true, g.V().has("hostname", "TEST1").both().has("physical-location-id", "complex2").hasNext()); + assertEquals("canopi pserver received forced prop", "test1.com", g.V().has("hostname", "TEST1").values("fqdn").next()); + assertEquals("pserver skeleton child copied", true, g.V().has("hostname", "TEST1").both().has("interface-name", "p-interface1").hasNext()); + assertEquals("pserver skeleton child merged", true, g.V().has("hostname", "TEST1").both().has("interface-name", "p-interface2").has("special-prop", "value").hasNext()); + assertEquals("l-interface child merged", true, g.V().has("hostname", "TEST1").both().has("interface-name", "p-interface2").both().has("interface-name", "l-interface1").has("special-prop", "value").hasNext()); + assertEquals("l-interface child cousin edge merged", true, g.V().has("hostname", "TEST1").both().has("interface-name", "p-interface2").both().has("interface-name", "l-interface1").both().has("link-name", "logical-link1").hasNext()); + assertEquals("one l-interface1 found", new Long(1), g.V().has("interface-name", "l-interface1").count().next()); + assertEquals("one p-interface2 found", new Long(1), g.V().has("interface-name", "p-interface2").count().next()); + + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/BulkAddConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/BulkAddConsumerTest.java new file mode 100644 index 0000000..28ded9d --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/BulkAddConsumerTest.java @@ -0,0 +1,189 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.commons.io.IOUtils; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.AAISetup; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.introspection.ModelInjestor; +import org.onap.aai.introspection.Version; + +import javax.ws.rs.core.*; +import java.io.IOException; +import java.io.InputStream; +import java.util.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.when; + +public class BulkAddConsumerTest extends AAISetup { + + protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); + + protected static final Set<Integer> VALID_HTTP_STATUS_CODES = new HashSet<>(); + + static { + VALID_HTTP_STATUS_CODES.add(200); + VALID_HTTP_STATUS_CODES.add(201); + VALID_HTTP_STATUS_CODES.add(204); + } + + protected BulkConsumer bulkConsumer; + + protected HttpHeaders httpHeaders; + + protected UriInfo uriInfo; + + protected MultivaluedMap<String, String> headersMultiMap; + protected MultivaluedMap<String, String> queryParameters; + + protected List<String> aaiRequestContextList; + + protected List<MediaType> outputMediaTypes; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(BulkAddConsumerTest.class.getName()); + + @BeforeClass + public static void setupRest(){ + AAIGraph.getInstance(); + ModelInjestor.getInstance(); + } + + @Before + public void setup(){ + logger.info("Starting the setup for the integration tests of Rest Endpoints"); + + bulkConsumer = getConsumer(); + httpHeaders = Mockito.mock(HttpHeaders.class); + uriInfo = Mockito.mock(UriInfo.class); + + headersMultiMap = new MultivaluedHashMap<>(); + queryParameters = Mockito.spy(new MultivaluedHashMap<>()); + + headersMultiMap.add("X-FromAppId", "JUNIT"); + headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); + headersMultiMap.add("Real-Time", "true"); + headersMultiMap.add("Accept", "application/json"); + headersMultiMap.add("aai-request-context", ""); + + outputMediaTypes = new ArrayList<>(); + outputMediaTypes.add(APPLICATION_JSON); + + aaiRequestContextList = new ArrayList<>(); + aaiRequestContextList.add(""); + + when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes); + when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap); + + when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList); + + + when(uriInfo.getQueryParameters()).thenReturn(queryParameters); + when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters); + + // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be very unreasonable + Mockito.doReturn(null).when(queryParameters).remove(anyObject()); + + when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON); + } + + @Test + public void testBulkAdd() throws IOException { + + String uri = "/aai/v11/bulkadd"; + + when(uriInfo.getPath()).thenReturn(uri); + when(uriInfo.getPath(false)).thenReturn(uri); + + String payload = getBulkPayload("pserver-transactions"); + Response response = bulkConsumer.bulkAdd( + payload, + Version.getLatest().toString(), + httpHeaders, + uriInfo, + null + ); + + System.out.println("Code: " + response.getStatus() + "\tResponse: " + response.getEntity()); + assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); + } + + @Test + public void testBulkAddThrowExceptionWhenPayloadContainsNoTransactions(){ + + String uri = "/aai/v11/bulkadd"; + + when(uriInfo.getPath()).thenReturn(uri); + when(uriInfo.getPath(false)).thenReturn(uri); + + String payload = "{\"transactions\":[]}"; + Response response = bulkConsumer.bulkAdd( + payload, + Version.getLatest().toString(), + httpHeaders, + uriInfo, + null + ); + + System.out.println("Code: " + response.getStatus() + "\tResponse: " + response.getEntity()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + } + + @Test + public void testBulkAddThrowExceptionWhenInvalidJson() throws IOException { + + String uri = "/aai/v11/bulkadd"; + + when(uriInfo.getPath()).thenReturn(uri); + when(uriInfo.getPath(false)).thenReturn(uri); + + String payload = "{"; + Response response = bulkConsumer.bulkAdd( + payload, + Version.getLatest().toString(), + httpHeaders, + uriInfo, + null + ); + + System.out.println("Code: " + response.getStatus() + "\tResponse: " + response.getEntity()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + + // TODO - Verify the result output and check if it contains an 400 in the list + } + + public String getBulkPayload(String bulkName) throws IOException { + return getPayload("payloads/bulk/" + bulkName + ".json"); + } + + public BulkConsumer getConsumer(){ + return new BulkAddConsumer(); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java new file mode 100644 index 0000000..99bccc7 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java @@ -0,0 +1,75 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.apache.commons.io.IOUtils; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.AAISetup; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.introspection.ModelInjestor; +import org.onap.aai.introspection.Version; + +import javax.ws.rs.core.*; +import java.io.IOException; +import java.io.InputStream; +import java.util.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.when; + +public class BulkProcessConsumerTest extends BulkAddConsumerTest { + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(BulkProcessConsumerTest.class.getName()); + + @Test + public void testBulkAddCreatedWhenOneTransactionInPayloadContainsNotAllowedVerb() throws IOException { + + String uri = "/aai/v11/bulkadd"; + + when(uriInfo.getPath()).thenReturn(uri); + when(uriInfo.getPath(false)).thenReturn(uri); + + String payload = getBulkPayload("pserver-transactions-invalid"); + Response response = bulkConsumer.bulkAdd( + payload, + Version.getLatest().toString(), + httpHeaders, + uriInfo, + null + ); + + System.out.println("Code: " + response.getStatus() + "\tResponse: " + response.getEntity()); + assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); + } + + @Override + public BulkConsumer getConsumer(){ + return new BulkProcessConsumer(); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/ExampleConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/ExampleConsumerTest.java new file mode 100644 index 0000000..30a3832 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/ExampleConsumerTest.java @@ -0,0 +1,152 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.AAISetup; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.introspection.ModelInjestor; +import org.onap.aai.introspection.Version; + +import javax.ws.rs.core.*; + +import java.util.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.when; + +public class ExampleConsumerTest extends AAISetup { + + protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); + + private static final Set<Integer> VALID_HTTP_STATUS_CODES = new HashSet<>(); + + static { + VALID_HTTP_STATUS_CODES.add(200); + VALID_HTTP_STATUS_CODES.add(201); + VALID_HTTP_STATUS_CODES.add(204); + } + + private ExampleConsumer exampleConsumer; + + private HttpHeaders httpHeaders; + + private UriInfo uriInfo; + + private MultivaluedMap<String, String> headersMultiMap; + private MultivaluedMap<String, String> queryParameters; + + private List<String> aaiRequestContextList; + + private List<MediaType> outputMediaTypes; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(LegacyMoxyConsumerTest.class.getName()); + + @BeforeClass + public static void setupRest(){ + AAIGraph.getInstance(); + ModelInjestor.getInstance(); + } + + @Before + public void setup(){ + logger.info("Starting the setup for the integration tests of Rest Endpoints"); + + exampleConsumer = new ExampleConsumer(); + httpHeaders = Mockito.mock(HttpHeaders.class); + uriInfo = Mockito.mock(UriInfo.class); + + headersMultiMap = new MultivaluedHashMap<>(); + queryParameters = Mockito.spy(new MultivaluedHashMap<>()); + + headersMultiMap.add("X-FromAppId", "JUNIT"); + headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); + headersMultiMap.add("Real-Time", "true"); + headersMultiMap.add("Accept", "application/json"); + headersMultiMap.add("aai-request-context", ""); + + outputMediaTypes = new ArrayList<>(); + outputMediaTypes.add(APPLICATION_JSON); + + aaiRequestContextList = new ArrayList<>(); + aaiRequestContextList.add(""); + + when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes); + when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap); + + when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList); + + + when(uriInfo.getQueryParameters()).thenReturn(queryParameters); + when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters); + + // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be very unreasonable + Mockito.doReturn(null).when(queryParameters).remove(anyObject()); + + when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON); + } + + @Test + public void testGetExampleRespondsWithOkStatusForValidObject(){ + + Response response = exampleConsumer.getExample( + Version.getLatest().toString(), + "pserver", + httpHeaders, + uriInfo, + null); + + assertNotNull("Response from the example consumer returned null", response); + + int code = Response.Status.OK.getStatusCode(); + + assertEquals(response.getStatus(), code); + } + + @Test + public void testGetExampleFailureForInvalidObject(){ + + when(uriInfo.getPath()).thenReturn("examples/fakeObject"); + when(uriInfo.getPath(false)).thenReturn("examples/fakeObject"); + + Response response = exampleConsumer.getExample( + Version.getLatest().toString(), + "testRandomCrazyObject", + httpHeaders, + uriInfo, + null); + + assertNotNull("Response from the example consumer returned null", response); + + int code = Response.Status.BAD_REQUEST.getStatusCode(); + + assertEquals(response.getStatus(), code); + } + +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/ExceptionHandlerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/ExceptionHandlerTest.java new file mode 100644 index 0000000..d6714ba --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/ExceptionHandlerTest.java @@ -0,0 +1,159 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest; + +import com.fasterxml.jackson.core.JsonLocation; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.sun.istack.SAXParseException2; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; +import org.onap.aai.AAISetup; + +import javax.servlet.http.HttpServletRequest; +import javax.ws.rs.WebApplicationException; +import javax.ws.rs.core.HttpHeaders; +import javax.ws.rs.core.MediaType; +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.Response; +import java.util.ArrayList; +import java.util.List; +import java.util.UUID; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class ExceptionHandlerTest extends AAISetup { + + protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); + + @Mock + private HttpHeaders httpHeaders; + + @Mock + private HttpServletRequest request; + + @InjectMocks + private ExceptionHandler handler = new ExceptionHandler(); + + @Before + public void setup(){ + MockitoAnnotations.initMocks(this); + + MultivaluedHashMap headersMultiMap = new MultivaluedHashMap<>(); + + headersMultiMap.add("X-FromAppId", "JUNIT"); + headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); + headersMultiMap.add("Real-Time", "true"); + headersMultiMap.add("Accept", "application/json"); + headersMultiMap.add("aai-request-context", ""); + + List<MediaType> outputMediaTypes = new ArrayList<>(); + outputMediaTypes.add(APPLICATION_JSON); + when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes); + when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap); + } + + @Test + public void testConversionOfWebApplicationResponse() throws Exception { + + Exception exception = new WebApplicationException(); + Response response = handler.toResponse(exception); + + assertNotNull(response); + assertNull(response.getEntity()); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus()); + } + + @Test + public void testConversionOfWebApplicationResponseWhenUmarshalExceptionResultBadRequest() throws Exception { + + SAXParseException2 mockSaxParseException = mock(SAXParseException2.class); + Exception exception = new WebApplicationException(mockSaxParseException); + Response response = handler.toResponse(exception); + + assertNotNull(response); + assertNotNull(response.getEntity()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + } + + @Test + public void testConversionWhenJsonParseExceptionResultBadRequest() throws Exception { + + JsonLocation jsonLocation = mock(JsonLocation.class); + Exception exception = new JsonParseException("", jsonLocation); + Response response = handler.toResponse(exception); + + assertNotNull(response); + assertNotNull(response.getEntity()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + } + + @Test + public void testConversionWhenJsonMappingExceptionResultBadRequest() throws Exception { + + JsonLocation jsonLocation = mock(JsonLocation.class); + Exception exception = new JsonMappingException("", jsonLocation); + Response response = handler.toResponse(exception); + + assertNotNull(response); + assertNotNull(response.getEntity()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + } + + @Test + public void testConversionWhenUnknownExceptionResultBadRequest() throws Exception { + + Exception exception = mock(Exception.class); + Response response = handler.toResponse(exception); + + when(request.getMethod()).thenReturn("GET"); + + assertNotNull(response); + assertNotNull(response.getEntity()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + + + } + + @Test + public void testConversionWhenUnknownExceptionResultBadRequestForXmlResponseType() throws Exception { + + List<MediaType> outputMediaTypes = new ArrayList<>(); + outputMediaTypes.add(MediaType.valueOf("application/xml")); + when(request.getMethod()).thenReturn("GET"); + when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes); + + Exception exception = mock(Exception.class); + Response response = handler.toResponse(exception); + + assertNotNull(response); + assertNotNull(response.getEntity()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java new file mode 100644 index 0000000..00d2496 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java @@ -0,0 +1,638 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.json.JSONException; +import org.json.JSONObject; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.AAISetup; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.ModelInjestor; +import org.onap.aai.introspection.Version; +import org.skyscreamer.jsonassert.JSONAssert; + +import javax.ws.rs.core.*; +import java.io.IOException; +import java.util.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.when; + +public class LegacyMoxyConsumerTest extends AAISetup { + + protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); + + private static final Set<Integer> VALID_HTTP_STATUS_CODES = new HashSet<>(); + + static { + VALID_HTTP_STATUS_CODES.add(200); + VALID_HTTP_STATUS_CODES.add(201); + VALID_HTTP_STATUS_CODES.add(204); + } + + private LegacyMoxyConsumer legacyMoxyConsumer; + + private HttpHeaders httpHeaders; + + private UriInfo uriInfo; + + private MultivaluedMap<String, String> headersMultiMap; + private MultivaluedMap<String, String> queryParameters; + + private List<String> aaiRequestContextList; + + private List<MediaType> outputMediaTypes; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(LegacyMoxyConsumerTest.class.getName()); + + @BeforeClass + public static void setupRest(){ + AAIGraph.getInstance(); + ModelInjestor.getInstance(); + } + + @Before + public void setup(){ + logger.info("Starting the setup for the integration tests of Rest Endpoints"); + + legacyMoxyConsumer = new LegacyMoxyConsumer(); + httpHeaders = Mockito.mock(HttpHeaders.class); + uriInfo = Mockito.mock(UriInfo.class); + + headersMultiMap = new MultivaluedHashMap<>(); + queryParameters = Mockito.spy(new MultivaluedHashMap<>()); + + headersMultiMap.add("X-FromAppId", "JUNIT"); + headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); + headersMultiMap.add("Real-Time", "true"); + headersMultiMap.add("Accept", "application/json"); + headersMultiMap.add("aai-request-context", ""); + + outputMediaTypes = new ArrayList<>(); + outputMediaTypes.add(APPLICATION_JSON); + + aaiRequestContextList = new ArrayList<>(); + aaiRequestContextList.add(""); + + when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes); + when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap); + + when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList); + + + when(uriInfo.getQueryParameters()).thenReturn(queryParameters); + when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters); + + // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be very unreasonable + Mockito.doReturn(null).when(queryParameters).remove(anyObject()); + + when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON); + } + + @Test + public void testResponsePutGetDeleteOnResource() throws JSONException, IOException, AAIException { + + String uri = getUri(); + String payload = getResourcePayload(getObjectName()); + + assertNotNull("Introspector returned invalid string when marshalling the object", payload); + assertNotNull("Introspector failed to return a valid uri", uri); + + if(uri.length() != 0 && uri.charAt(0) == '/'){ + uri = uri.substring(1); + } + + when(uriInfo.getPath()).thenReturn(uri); + when(uriInfo.getPath(false)).thenReturn(uri); + + Response response = legacyMoxyConsumer.getLegacy( + "", + Version.getLatest().toString(), + uri, + "all", + "false", + httpHeaders, + uriInfo, + null + ); + + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); + + response = legacyMoxyConsumer.update( + payload, + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + null + ); + + int code = response.getStatus(); + if(!VALID_HTTP_STATUS_CODES.contains(code)){ + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + } + + assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); + + queryParameters.add("depth", "10000"); + + response = legacyMoxyConsumer.getLegacy( + "", + Version.getLatest().toString(), + uri, + "10000", + "false", + httpHeaders, + uriInfo, + null + ); + + code = response.getStatus(); + if(!VALID_HTTP_STATUS_CODES.contains(code)){ + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + } + + String pserverEntity = response.getEntity().toString(); + JSONObject pserverJsonbject = new JSONObject(pserverEntity); + + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + + JSONAssert.assertEquals(payload, pserverEntity, false); + + String resourceVersion = pserverJsonbject.getString("resource-version"); + + queryParameters.add("resource-version", resourceVersion); + + response = legacyMoxyConsumer.delete( + "v11", + uri, + httpHeaders, + uriInfo, + "", + null + ); + + code = response.getStatus(); + if(!VALID_HTTP_STATUS_CODES.contains(code)){ + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + } + + assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); + + response = legacyMoxyConsumer.getLegacy( + "", + Version.getLatest().toString(), + uri, + "all", + "false", + httpHeaders, + uriInfo, + null + ); + + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); + } + + @Test + public void testPutPserverAndCloudRegionRelationship() throws IOException, JSONException { + + String pserverData = getRelationshipPayload("pserver"); + String complexData = getRelationshipPayload("complex"); + + String hostname = "590a8943-1200-43b3-825b-75dde6b8f44a"; + String physicalLocationId ="e13d4587-19ad-4bf5-80f5-c021efb5b61c"; + + String pserverUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname); + String cloudRegionUri = String.format("cloud-infrastructure/complexes/complex/%s", physicalLocationId); + + doSetupResource(pserverUri, pserverData); + doSetupResource(cloudRegionUri, complexData); + + String cloudToPserverRelationshipData = getRelationshipPayload("pserver-complex-relationship"); + String cloudToPserverRelationshipUri = String.format( + "cloud-infrastructure/pservers/pserver/%s/relationship-list/relationship", hostname); + + Response response = legacyMoxyConsumer.updateRelationship( + cloudToPserverRelationshipData, + Version.getLatest().toString(), + cloudToPserverRelationshipUri, + httpHeaders, + uriInfo, + null + ); + + assertNotNull("Response from the legacy moxy consumer returned null", response); + int code = response.getStatus(); + if(!VALID_HTTP_STATUS_CODES.contains(code)){ + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + } + + assertEquals("Expected to return status created from the response", + Response.Status.OK.getStatusCode(), response.getStatus()); + logger.info("Response Code: " + code + "\tEntity: " + response.getEntity()); + + // TODO - Need to actually verify the relationship between pserver and cloud-region + + response = legacyMoxyConsumer.deleteRelationship( + cloudToPserverRelationshipData, + Version.getLatest().toString(), + cloudToPserverRelationshipUri, + httpHeaders, + uriInfo, + null + ); + + code = response.getStatus(); + if(!VALID_HTTP_STATUS_CODES.contains(code)){ + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + } + + assertEquals(Response.Status.NO_CONTENT.getStatusCode(), response.getStatus()); + } + + @Test + public void testPutPassWithEmptyData() throws JSONException { + + String payload = "{}"; + String pserverUri = String.format("cloud-infrastructure/pservers/pserver/%s", UUID.randomUUID().toString()); + + doSetupResource(pserverUri, payload); + + payload = ""; + pserverUri = String.format("cloud-infrastructure/pservers/pserver/%s", UUID.randomUUID().toString()); + doSetupResource(pserverUri, payload); + } + + @Test + public void testFailureWithInvalidUri() throws JSONException { + + String payload = "{}"; + String uri = "fake-infrastructure/pservers/pserver/fajsidj"; + + when(uriInfo.getPath()).thenReturn(uri); + when(uriInfo.getPath(false)).thenReturn(uri); + + Response response = legacyMoxyConsumer.update( + payload, + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + null + ); + + int code = response.getStatus(); + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); + } + + @Test + public void testInvalidUriThrowRandomException() throws JSONException { + + String payload = "{}"; + String uri = "fake-infrastructure/pservers/pserver/fajsidj"; + + when(uriInfo.getPath()).thenReturn(uri); + when(uriInfo.getPath(false)).thenThrow(new IllegalArgumentException()); + + Response response = legacyMoxyConsumer.update( + payload, + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + null + ); + + int code = response.getStatus(); + assertNotNull("Response from the legacy moxy consumer returned null", response); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + + response = legacyMoxyConsumer.updateRelationship( + payload, + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + null + ); + + code = response.getStatus(); + assertNotNull("Response from the legacy moxy consumer returned null", response); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + + response = legacyMoxyConsumer.getLegacy( + "", + Version.getLatest().toString(), + uri, + "all", + "false", + httpHeaders, + uriInfo, + null + ); + + assertNotNull("Response from the legacy moxy consumer returned null", response); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); + + response = legacyMoxyConsumer.delete( + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + "", + null + ); + + code = response.getStatus(); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); + + response = legacyMoxyConsumer.deleteRelationship( + payload, + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + null + ); + code = response.getStatus(); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); + } + + @Test + public void testInvalidUriContainingRelatedToShouldThrowAAIException() throws JSONException { + + String payload = "{}"; + String uri = "cloud-infrastructure/related-to/fsdf"; + + when(uriInfo.getPath()).thenReturn(uri); + when(uriInfo.getPath(false)).thenReturn(uri); + + Response response = legacyMoxyConsumer.update( + payload, + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + null + ); + + int code = response.getStatus(); + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); + + response = legacyMoxyConsumer.updateRelationship( + payload, + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + null + ); + + code = response.getStatus(); + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); + + response = legacyMoxyConsumer.getLegacy( + "", + Version.getLatest().toString(), + uri, + "all", + "false", + httpHeaders, + uriInfo, + null + ); + + assertNotNull("Response from the legacy moxy consumer returned null", response); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); + + queryParameters.add("resource-version", "3434394839483"); + response = legacyMoxyConsumer.delete( + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + "", + null + ); + + code = response.getStatus(); + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); + + response = legacyMoxyConsumer.deleteRelationship( + payload, + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + null + ); + code = response.getStatus(); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code); + } + + @Test + @Ignore("Unable to test this method due to WRITE_BIGDECIMAL_AS_PLAIN error") + public void testPatchWithValidData() throws IOException { + + String payload = getResourcePayload("pserver-patch-test"); + String uri = getUri("pserver-patch-test"); + + if(uri.length() != 0 && uri.charAt(0) == '/'){ + uri = uri.substring(1); + } + + when(uriInfo.getPath()).thenReturn(uri); + when(uriInfo.getPath(false)).thenReturn(uri); + + Response response = legacyMoxyConsumer.getLegacy( + "", + Version.getLatest().toString(), + uri, + "all", + "false", + httpHeaders, + uriInfo, + null + ); + + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); + + response = legacyMoxyConsumer.update( + payload, + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + null + ); + + int code = response.getStatus(); + if(!VALID_HTTP_STATUS_CODES.contains(code)){ + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + } + + assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); + + String patchData = "{\"in-maint\": false}"; + + headersMultiMap.add("Content-Type", "application/json"); + + outputMediaTypes.remove(APPLICATION_JSON); + outputMediaTypes.add(MediaType.valueOf("application/merge-patch+json")); + + response = legacyMoxyConsumer.patch( + patchData, + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + null + ); + + code = response.getStatus(); + assertNotNull("Response from the patch returned null", response); + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + assertEquals(Response.Status.OK.getStatusCode(), code); + + } + + protected void doSetupResource(String uri, String payload) throws JSONException { + + when(uriInfo.getPath()).thenReturn(uri); + when(uriInfo.getPath(false)).thenReturn(uri); + + Response response = legacyMoxyConsumer.getLegacy( + "", + Version.getLatest().toString(), + uri, + "all", + "false", + httpHeaders, + uriInfo, + null + ); + + assertNotNull("Response from the legacy moxy consumer returned null", response); + assertEquals("Expected to not have the data already in memory", + Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); + + response = legacyMoxyConsumer.update( + payload, + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + null + ); + + assertNotNull("Response from the legacy moxy consumer returned null", response); + int code = response.getStatus(); + if(!VALID_HTTP_STATUS_CODES.contains(code)){ + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + } + assertEquals("Expected to return status created from the response", + Response.Status.CREATED.getStatusCode(), response.getStatus()); + + queryParameters.add("depth", "10000"); + response = legacyMoxyConsumer.getLegacy( + "", + Version.getLatest().toString(), + uri, + "all", + "false", + httpHeaders, + uriInfo, + null + ); + + assertNotNull("Response from the legacy moxy consumer returned null", response); + assertEquals("Expected to return the pserver data that was just put in memory", + Response.Status.OK.getStatusCode(), response.getStatus()); + + if("".equalsIgnoreCase(payload)){ + payload = "{}"; + } + + JSONAssert.assertEquals(payload, response.getEntity().toString(), false); + } + + @Test + public void testDeleteRelationshipThrowsException(){ + + String payload = ""; + String hostname = "testData"; + String uri = String.format("cloud-infrastructure/pservers/pserver/%s/relationship-list/relationship", hostname); + + when(uriInfo.getPath()).thenReturn(uri); + when(uriInfo.getPath(false)).thenReturn(uri); + + Response response = legacyMoxyConsumer.deleteRelationship( + payload, + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + null + ); + + int code = response.getStatus(); + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), code); + } + + // TODO - Change this to be abstract and inheritable + public String getObjectName(){ + return "pserver"; + } + + public String getResourcePayload(String resourceName) throws IOException { + return getPayload("payloads/resource/" + resourceName + ".json"); + } + + public String getRelationshipPayload(String relationshipName) throws IOException { + return getPayload("payloads/relationship/" + relationshipName + ".json"); + } + + public String getUri(String hostname){ + return String.format("cloud-infrastructure/pservers/pserver/%s", hostname); + } + + public String getUri(){ + return getUri("pserver-hostname-test"); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java new file mode 100644 index 0000000..c2a6c4a --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java @@ -0,0 +1,200 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.json.JSONException; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.AAISetup; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.ModelInjestor; +import org.onap.aai.introspection.Version; + +import javax.ws.rs.core.*; +import java.io.IOException; +import java.util.*; + +import static org.junit.Assert.*; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.when; + +public class URLFromVertexIdConsumerTest extends AAISetup { + + protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); + + private static final Set<Integer> VALID_HTTP_STATUS_CODES = new HashSet<>(); + + static { + VALID_HTTP_STATUS_CODES.add(200); + VALID_HTTP_STATUS_CODES.add(201); + VALID_HTTP_STATUS_CODES.add(204); + } + + private URLFromVertexIdConsumer urlFromVertexIdConsumer; + private LegacyMoxyConsumer legacyMoxyConsumer; + + private HttpHeaders httpHeaders; + + private UriInfo uriInfo; + + private MultivaluedMap<String, String> headersMultiMap; + private MultivaluedMap<String, String> queryParameters; + + private List<String> aaiRequestContextList; + + private List<MediaType> outputMediaTypes; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(LegacyMoxyConsumerTest.class.getName()); + + @BeforeClass + public static void setupRest(){ + AAIGraph.getInstance(); + ModelInjestor.getInstance(); + } + + @Before + public void setup(){ + logger.info("Starting the setup for the integration tests of Rest Endpoints"); + + urlFromVertexIdConsumer = new URLFromVertexIdConsumer(); + legacyMoxyConsumer = new LegacyMoxyConsumer(); + + httpHeaders = Mockito.mock(HttpHeaders.class); + uriInfo = Mockito.mock(UriInfo.class); + + headersMultiMap = new MultivaluedHashMap<>(); + queryParameters = Mockito.spy(new MultivaluedHashMap<>()); + + headersMultiMap.add("X-FromAppId", "JUNIT"); + headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); + headersMultiMap.add("Real-Time", "true"); + headersMultiMap.add("Accept", "application/json"); + headersMultiMap.add("aai-request-context", ""); + + outputMediaTypes = new ArrayList<>(); + outputMediaTypes.add(APPLICATION_JSON); + + aaiRequestContextList = new ArrayList<>(); + aaiRequestContextList.add(""); + + when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes); + when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap); + + when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList); + + + when(uriInfo.getQueryParameters()).thenReturn(queryParameters); + when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters); + + // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be very unreasonable + Mockito.doReturn(null).when(queryParameters).remove(anyObject()); + + when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON); + } + + @Test + public void testResponsePutGetDeleteOnResource() throws JSONException, IOException, AAIException { + + String uri = "cloud-infrastructure/pservers/pserver/" + UUID.randomUUID().toString(); + String payload = "{}"; + + when(uriInfo.getPath()).thenReturn(uri); + when(uriInfo.getPath(false)).thenReturn(uri); + + Response response = legacyMoxyConsumer.getLegacy( + "", + Version.getLatest().toString(), + uri, + "all", + "false", + httpHeaders, + uriInfo, + null + ); + + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); + + response = legacyMoxyConsumer.update( + payload, + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + null + ); + + int code = response.getStatus(); + if(!VALID_HTTP_STATUS_CODES.contains(code)){ + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + } + + assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); + + MultivaluedMap<String, Object> responseHeaders = response.getMetadata(); + + assertNotNull("Unable to retrieve the response headers from response object", responseHeaders); + assertTrue("Response doesn't contain the key vertexId", responseHeaders.containsKey("vertex-id")); + + String vertexId = responseHeaders.get("vertex-id").get(0).toString(); + + response = urlFromVertexIdConsumer.generateUrlFromVertexId( + "", + Version.getLatest().toString(), + Long.valueOf(vertexId).longValue(), + httpHeaders, + uriInfo, + null + ); + + assertNotNull(response); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + } + + @Test + public void testObjectNotFoundInDBReturnsNotFoundStatus() throws JSONException, IOException, AAIException { + + String uri = "cloud-infrastructure/pservers/pserver/testRandom"; + + when(uriInfo.getPath()).thenReturn(uri); + when(uriInfo.getPath(false)).thenReturn(uri); + + String vertexId = "384584"; + + Response response = urlFromVertexIdConsumer.generateUrlFromVertexId( + "", + Version.getLatest().toString(), + Long.valueOf(vertexId).longValue(), + httpHeaders, + uriInfo, + null + ); + + assertNotNull("Check if the response is not null", response); + + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java new file mode 100644 index 0000000..fa80805 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java @@ -0,0 +1,179 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.json.JSONException; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.AAISetup; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.exceptions.AAIException; +import org.onap.aai.introspection.ModelInjestor; +import org.onap.aai.introspection.Version; + +import javax.ws.rs.core.*; +import java.io.IOException; +import java.util.*; + +import static org.junit.Assert.*; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.when; + +public class VertexIdConsumerTest extends AAISetup { + + protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); + + private static final Set<Integer> VALID_HTTP_STATUS_CODES = new HashSet<>(); + + static { + VALID_HTTP_STATUS_CODES.add(200); + VALID_HTTP_STATUS_CODES.add(201); + VALID_HTTP_STATUS_CODES.add(204); + } + + private VertexIdConsumer vertexIdConsumer; + private LegacyMoxyConsumer legacyMoxyConsumer; + + private HttpHeaders httpHeaders; + + private UriInfo uriInfo; + + private MultivaluedMap<String, String> headersMultiMap; + private MultivaluedMap<String, String> queryParameters; + + private List<String> aaiRequestContextList; + + private List<MediaType> outputMediaTypes; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(LegacyMoxyConsumerTest.class.getName()); + + @BeforeClass + public static void setupRest(){ + AAIGraph.getInstance(); + ModelInjestor.getInstance(); + } + + @Before + public void setup(){ + logger.info("Starting the setup for the integration tests of Rest Endpoints"); + + vertexIdConsumer = new VertexIdConsumer(); + legacyMoxyConsumer = new LegacyMoxyConsumer(); + + httpHeaders = Mockito.mock(HttpHeaders.class); + uriInfo = Mockito.mock(UriInfo.class); + + headersMultiMap = new MultivaluedHashMap<>(); + queryParameters = Mockito.spy(new MultivaluedHashMap<>()); + + headersMultiMap.add("X-FromAppId", "JUNIT"); + headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); + headersMultiMap.add("Real-Time", "true"); + headersMultiMap.add("Accept", "application/json"); + headersMultiMap.add("aai-request-context", ""); + + outputMediaTypes = new ArrayList<>(); + outputMediaTypes.add(APPLICATION_JSON); + + aaiRequestContextList = new ArrayList<>(); + aaiRequestContextList.add(""); + + when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes); + when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap); + + when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList); + + + when(uriInfo.getQueryParameters()).thenReturn(queryParameters); + when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters); + + // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be very unreasonable + Mockito.doReturn(null).when(queryParameters).remove(anyObject()); + + when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON); + } + + @Test + public void testResponsePutGetDeleteOnResource() throws JSONException, IOException, AAIException { + + String uri = "cloud-infrastructure/pservers/pserver/" + UUID.randomUUID().toString(); + String payload = "{}"; + + when(uriInfo.getPath()).thenReturn(uri); + when(uriInfo.getPath(false)).thenReturn(uri); + + Response response = legacyMoxyConsumer.getLegacy( + "", + Version.getLatest().toString(), + uri, + "all", + "false", + httpHeaders, + uriInfo, + null + ); + + assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus()); + + response = legacyMoxyConsumer.update( + payload, + Version.getLatest().toString(), + uri, + httpHeaders, + uriInfo, + null + ); + + int code = response.getStatus(); + if(!VALID_HTTP_STATUS_CODES.contains(code)){ + System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity()); + } + + assertEquals(Response.Status.CREATED.getStatusCode(), response.getStatus()); + + MultivaluedMap<String, Object> responseHeaders = response.getMetadata(); + + assertNotNull("Unable to retrieve the response headers from response object", responseHeaders); + assertTrue("Response doesn't contain the key vertexId", responseHeaders.containsKey("vertex-id")); + + String vertexId = responseHeaders.get("vertex-id").get(0).toString(); + + response = vertexIdConsumer.getByVertexId( + "", + Version.getLatest().toString(), + Long.valueOf(vertexId).longValue(), + "10000", + httpHeaders, + uriInfo, + null + ); + + assertNotNull(response); + String pserverObject = response.getEntity().toString(); + + System.out.println(pserverObject); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerTest.java new file mode 100644 index 0000000..66846b6 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerTest.java @@ -0,0 +1,128 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest.retired; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.introspection.Version; + +import javax.ws.rs.core.*; +import java.util.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.when; + +public abstract class RetiredConsumerTest { + + protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); + + private static final Set<Integer> VALID_HTTP_STATUS_CODES = new HashSet<>(); + + static { + VALID_HTTP_STATUS_CODES.add(200); + VALID_HTTP_STATUS_CODES.add(201); + VALID_HTTP_STATUS_CODES.add(204); + } + + protected RetiredConsumer retiredConsumer; + protected HttpHeaders httpHeaders; + protected UriInfo uriInfo; + + private MultivaluedMap<String, String> headersMultiMap; + private MultivaluedMap<String, String> queryParameters; + + private List<String> aaiRequestContextList; + + private List<MediaType> outputMediaTypes; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(RetiredConsumer.class.getName()); + + @Before + public void setup(){ + logger.info("Starting the setup for the integration tests of Rest Endpoints"); + + retiredConsumer = getRetiredConsumer(); + httpHeaders = Mockito.mock(HttpHeaders.class); + uriInfo = Mockito.mock(UriInfo.class); + + headersMultiMap = new MultivaluedHashMap<>(); + queryParameters = Mockito.spy(new MultivaluedHashMap<>()); + + headersMultiMap.add("X-FromAppId", "JUNIT"); + headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); + headersMultiMap.add("Real-Time", "true"); + headersMultiMap.add("Accept", "application/json"); + headersMultiMap.add("aai-request-context", ""); + + outputMediaTypes = new ArrayList<>(); + outputMediaTypes.add(APPLICATION_JSON); + + aaiRequestContextList = new ArrayList<>(); + aaiRequestContextList.add(""); + + when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes); + when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap); + + when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList); + + + when(uriInfo.getQueryParameters()).thenReturn(queryParameters); + when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters); + + // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be very unreasonable + Mockito.doReturn(null).when(queryParameters).remove(anyObject()); + + when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON); + } + + @Test + public void testRetiredForAllEndPoints(){ + when(uriInfo.getPath()).thenReturn("/aai/v3/cloud-infrastructure/pservers/pserver/test-pserver1"); + + Response response = retiredConsumer.createMessageGet(Version.getLatest().toString(), httpHeaders, uriInfo, null); + assertNotNull(response); + assertEquals(Response.Status.GONE.getStatusCode(), response.getStatus()); + + response = retiredConsumer.createMessagePost(Version.getLatest().toString(), httpHeaders, uriInfo, null); + assertNotNull(response); + assertEquals(Response.Status.GONE.getStatusCode(), response.getStatus()); + + response = retiredConsumer.createMessagePatch(Version.getLatest().toString(), httpHeaders, uriInfo, null); + assertNotNull(response); + assertEquals(Response.Status.GONE.getStatusCode(), response.getStatus()); + + response = retiredConsumer.createMessagePut(Version.getLatest().toString(), httpHeaders, uriInfo, null); + assertNotNull(response); + assertEquals(Response.Status.GONE.getStatusCode(), response.getStatus()); + + response = retiredConsumer.createMessageDelete(Version.getLatest().toString(), httpHeaders, uriInfo, null); + assertNotNull(response); + assertEquals(Response.Status.GONE.getStatusCode(), response.getStatus()); + } + + public abstract RetiredConsumer getRetiredConsumer(); +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/retired/V3ThroughV7ConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/retired/V3ThroughV7ConsumerTest.java new file mode 100644 index 0000000..b605bad --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/retired/V3ThroughV7ConsumerTest.java @@ -0,0 +1,30 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest.retired; + +public class V3ThroughV7ConsumerTest extends RetiredConsumerTest { + + @Override + public RetiredConsumer getRetiredConsumer() { + return new V3ThroughV7Consumer(); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/retired/V7V8ModelsTest.java b/aai-resources/src/test/java/org/onap/aai/rest/retired/V7V8ModelsTest.java new file mode 100644 index 0000000..be5ed82 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/retired/V7V8ModelsTest.java @@ -0,0 +1,30 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest.retired; + +public class V7V8ModelsTest extends RetiredConsumerTest { + + @Override + public RetiredConsumer getRetiredConsumer() { + return new V7V8Models(); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/retired/V7V8NamedQueriesTest.java b/aai-resources/src/test/java/org/onap/aai/rest/retired/V7V8NamedQueriesTest.java new file mode 100644 index 0000000..f9a6e8c --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/retired/V7V8NamedQueriesTest.java @@ -0,0 +1,30 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest.retired; + +public class V7V8NamedQueriesTest extends RetiredConsumerTest { + + @Override + public RetiredConsumer getRetiredConsumer() { + return new V7V8NamedQueries(); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/tools/ModelVersionTransformerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/tools/ModelVersionTransformerTest.java new file mode 100644 index 0000000..911fc2d --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/tools/ModelVersionTransformerTest.java @@ -0,0 +1,137 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest.tools; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.AAISetup; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.introspection.ModelInjestor; +import org.skyscreamer.jsonassert.JSONAssert; + +import javax.ws.rs.core.*; +import java.util.*; + +import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.when; + +public class ModelVersionTransformerTest extends AAISetup { + + + protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); + + private static final Set<Integer> VALID_HTTP_STATUS_CODES = new HashSet<>(); + + static { + VALID_HTTP_STATUS_CODES.add(200); + VALID_HTTP_STATUS_CODES.add(201); + VALID_HTTP_STATUS_CODES.add(204); + } + + private ModelVersionTransformer modelVersionTransformer; + + private HttpHeaders httpHeaders; + + private UriInfo uriInfo; + + private MultivaluedMap<String, String> headersMultiMap; + private MultivaluedMap<String, String> queryParameters; + + private List<String> aaiRequestContextList; + + private List<MediaType> outputMediaTypes; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(ModelVersionTransformerTest.class.getName()); + + @BeforeClass + public static void setupRest(){ + AAIGraph.getInstance(); + ModelInjestor.getInstance(); + } + + @Before + public void setup(){ + logger.info("Starting the setup for the integration tests of Rest Endpoints"); + + modelVersionTransformer = new ModelVersionTransformer(); + httpHeaders = Mockito.mock(HttpHeaders.class); + uriInfo = Mockito.mock(UriInfo.class); + + headersMultiMap = new MultivaluedHashMap<>(); + queryParameters = Mockito.spy(new MultivaluedHashMap<>()); + + headersMultiMap.add("X-FromAppId", "JUNIT"); + headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); + headersMultiMap.add("Real-Time", "true"); + headersMultiMap.add("Content-Type", "application/xml"); + headersMultiMap.add("Accept", "application/json"); + headersMultiMap.add("aai-request-context", ""); + + outputMediaTypes = new ArrayList<>(); + outputMediaTypes.add(APPLICATION_JSON); + + aaiRequestContextList = new ArrayList<>(); + aaiRequestContextList.add(""); + + when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes); + when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap); + when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList); + + + when(uriInfo.getQueryParameters()).thenReturn(queryParameters); + when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters); + + // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be very unreasonable + Mockito.doReturn(null).when(queryParameters).remove(anyObject()); + + when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON); + } + + @Test + public void modelTransform() throws Exception { + + String modelXmlPayload = getPayload("payloads/modeltransforms/model.xml"); + String modelJsonPayload = getPayload("payloads/modeltransforms/model.json"); + + String uri = "modeltransform"; + + when(uriInfo.getPath()).thenReturn(uri); + // Comment the following line for the null pointer exception + when(uriInfo.getPath(false)).thenReturn(uri); + + outputMediaTypes = new ArrayList<>(); + outputMediaTypes.add(MediaType.valueOf("application/xml")); + + when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes); + when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap); + when(httpHeaders.getMediaType()).thenReturn(MediaType.valueOf("application/xml")); + + Response response = modelVersionTransformer.modelTransform(modelXmlPayload,uri, httpHeaders, uriInfo, null); + + assertNotNull(response); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/util/EchoResponseTest.java b/aai-resources/src/test/java/org/onap/aai/rest/util/EchoResponseTest.java new file mode 100644 index 0000000..5f62342 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/util/EchoResponseTest.java @@ -0,0 +1,137 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest.util; + +import com.att.eelf.configuration.EELFLogger; +import com.att.eelf.configuration.EELFManager; +import org.junit.Before; +import org.junit.Test; +import org.mockito.Mockito; +import org.onap.aai.AAISetup; + +import javax.ws.rs.core.*; +import java.util.*; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Matchers.anyObject; +import static org.mockito.Mockito.mock; +import static org.mockito.Mockito.when; + +public class EchoResponseTest extends AAISetup { + + protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json"); + + private static final Set<Integer> VALID_HTTP_STATUS_CODES = new HashSet<>(); + + static { + VALID_HTTP_STATUS_CODES.add(200); + VALID_HTTP_STATUS_CODES.add(201); + VALID_HTTP_STATUS_CODES.add(204); + } + + private EchoResponse echoResponse; + + private HttpHeaders httpHeaders; + + private UriInfo uriInfo; + + private MultivaluedMap<String, String> headersMultiMap; + private MultivaluedMap<String, String> queryParameters; + + private List<String> aaiRequestContextList; + + private List<MediaType> outputMediaTypes; + + private static final EELFLogger logger = EELFManager.getInstance().getLogger(EchoResponseTest.class.getName()); + + @Before + public void setup(){ + logger.info("Starting the setup for the integration tests of Rest Endpoints"); + + echoResponse = new EchoResponse(); + httpHeaders = mock(HttpHeaders.class); + uriInfo = mock(UriInfo.class); + + headersMultiMap = new MultivaluedHashMap<>(); + queryParameters = Mockito.spy(new MultivaluedHashMap<>()); + + headersMultiMap.add("X-FromAppId", "JUNIT"); + headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString()); + headersMultiMap.add("Real-Time", "true"); + headersMultiMap.add("Accept", "application/json"); + headersMultiMap.add("aai-request-context", ""); + + outputMediaTypes = new ArrayList<>(); + outputMediaTypes.add(APPLICATION_JSON); + + aaiRequestContextList = new ArrayList<>(); + aaiRequestContextList.add(""); + + when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes); + when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap); + when(httpHeaders.getRequestHeader("X-FromAppId")).thenReturn(Arrays.asList("JUNIT")); + when(httpHeaders.getRequestHeader("X-TransactionId")).thenReturn(Arrays.asList("JUNIT")); + + when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList); + + + when(uriInfo.getQueryParameters()).thenReturn(queryParameters); + when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters); + + // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be very unreasonable + Mockito.doReturn(null).when(queryParameters).remove(anyObject()); + + when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON); + } + + @Test + public void testEchoResultWhenValidHeaders() throws Exception { + + Response response = echoResponse.echoResult(httpHeaders, null, ""); + + assertNotNull(response); + assertEquals(Response.Status.OK.getStatusCode(), response.getStatus()); + } + + @Test + public void testEchoResultWhenInValidHeadersThrowsBadRequest() throws Exception { + + httpHeaders = mock(HttpHeaders.class); + Response response = echoResponse.echoResult(httpHeaders, null, ""); + + assertNotNull(response); + assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus()); + } + + @Test + public void testEchoResultWhenValidHeadersButMediaTypeWrong() throws Exception { + + when(httpHeaders.getAcceptableMediaTypes()).thenThrow(new IllegalStateException()) + .thenReturn(outputMediaTypes); + + Response response = echoResponse.echoResult(httpHeaders, null, ""); + + assertNotNull(response); + assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus()); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java b/aai-resources/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java new file mode 100644 index 0000000..c4cc211 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java @@ -0,0 +1,36 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest.util; + +import org.junit.Test; + +import static org.junit.Assert.assertNotNull; + +public class LogFormatToolsTest { + + @Test + public void testLogFormatTools(){ + + String dateTime = new LogFormatTools().getCurrentDateTime(); + assertNotNull(dateTime); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java b/aai-resources/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java new file mode 100644 index 0000000..9ce81f4 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java @@ -0,0 +1,101 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.rest.util; + +import org.junit.Test; +import org.mockito.Mockito; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriInfo; +import java.io.UnsupportedEncodingException; + +import static org.junit.Assert.assertEquals; + +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/onap/aai/schema/db/AuditOXMTest.java b/aai-resources/src/test/java/org/onap/aai/schema/db/AuditOXMTest.java new file mode 100644 index 0000000..d3c7302 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/schema/db/AuditOXMTest.java @@ -0,0 +1,84 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.schema.db; + +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import org.codehaus.jackson.JsonGenerationException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.aai.AAISetup; +import org.onap.aai.db.schema.AuditDoc; +import org.onap.aai.db.schema.AuditOXM; +import org.onap.aai.db.schema.Auditor; +import org.onap.aai.db.schema.AuditorFactory; +import org.onap.aai.introspection.Version; + +import java.io.IOException; + +@Ignore("not ready for testing") +public class AuditOXMTest extends AAISetup { + + + /** + * 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/onap/aai/schema/db/ManageSchemaTest.java b/aai-resources/src/test/java/org/onap/aai/schema/db/ManageSchemaTest.java new file mode 100644 index 0000000..4eeb172 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/schema/db/ManageSchemaTest.java @@ -0,0 +1,114 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.schema.db; + +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.schema.TitanManagement; +import org.codehaus.jackson.JsonParseException; +import org.codehaus.jackson.map.JsonMappingException; +import org.codehaus.jackson.map.ObjectMapper; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.aai.AAISetup; +import org.onap.aai.db.schema.DBIndex; +import org.onap.aai.db.schema.ManageTitanSchema; + +import java.io.IOException; +import java.util.Set; + +@Ignore("not ready yet") +public class ManageSchemaTest extends AAISetup { + + private TitanGraph graph = null; + + @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/onap/aai/serialization/queryformats/QueryFormatTestHelper.java b/aai-resources/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java new file mode 100644 index 0000000..53d1d29 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java @@ -0,0 +1,76 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.serialization.queryformats; + +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.io.IoCore; +import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; +import org.onap.aai.db.props.AAIProperties; +import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException; +import org.onap.aai.serialization.queryformats.utils.UrlBuilder; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; + +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.when; + +public class QueryFormatTestHelper { + + + public static final String testResources = "src/test/resources/org.onap.aai/serialization/queryformats/"; + public static final String graphsonResources = "src/test/resources/org.onap.aai/serialization/queryformats/graphson/"; + + + public static void mockPathed(UrlBuilder mock) throws AAIFormatVertexException { + Answer<String> answer = new Answer<String>() { + public String answer(InvocationOnMock invocation) throws Throwable { + Vertex v = invocation.getArgumentAt(0, Vertex.class); + + return v.<String>property(AAIProperties.AAI_URI).orElse("urimissing"); + } + }; + when(mock.pathed(isA(Vertex.class))).thenAnswer(answer); + + } + + public static Graph loadGraphson(String fileName) throws IOException { + final Graph graph = TinkerGraph.open(); + graph.io(IoCore.graphson()).readGraph(QueryFormatTestHelper.graphsonResources + fileName); + + return graph; + } + + public static void setFinalStatic(Field field, Object newValue) throws Exception { + field.setAccessible(true); + // remove final modifier from field + Field modifiersField = Field.class.getDeclaredField("modifiers"); + modifiersField.setAccessible(true); + modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL); + field.set(null, newValue); + } + +} diff --git a/aai-resources/src/test/java/org/onap/aai/transforms/JoltTestUtil.java b/aai-resources/src/test/java/org/onap/aai/transforms/JoltTestUtil.java new file mode 100644 index 0000000..7784724 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/transforms/JoltTestUtil.java @@ -0,0 +1,61 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.transforms; + + +import com.bazaarvoice.jolt.ArrayOrderObliviousDiffy; +import com.bazaarvoice.jolt.Diffy; +import com.bazaarvoice.jolt.JsonUtils; +import org.junit.Assert; + +import java.io.IOException; + +public class JoltTestUtil { + + private static final Diffy diffy = new Diffy(); + private static final Diffy arrayOrderObliviousDiffy = new ArrayOrderObliviousDiffy(); + + public static void runDiffy( String failureMessage, Object expected, Object actual ) throws IOException { + runDiffy( diffy, failureMessage, expected, actual ); + } + + public static void runDiffy( Object expected, Object actual ) throws IOException { + runDiffy( diffy, "Failed", expected, actual ); + } + + public static void runArrayOrderObliviousDiffy( String failureMessage, Object expected, Object actual ) throws IOException { + runDiffy( arrayOrderObliviousDiffy, failureMessage, expected, actual ); + } + + public static void runArrayOrderObliviousDiffy( Object expected, Object actual ) throws IOException { + runDiffy( arrayOrderObliviousDiffy, "Failed", expected, actual ); + } + + + private static void runDiffy( Diffy diffy, String failureMessage, Object expected, Object actual ) { + String actualObject = JsonUtils.toPrettyJsonString( actual ); + Diffy.Result result = diffy.diff( expected, actual ); + if (!result.isEmpty()) { + Assert.fail( "\nActual object\n" + actualObject + "\n" + failureMessage + "\nDiffy output\n" + result.toString()); + } + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverterTest.java b/aai-resources/src/test/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverterTest.java new file mode 100644 index 0000000..43afa68 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverterTest.java @@ -0,0 +1,74 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.transforms; + +import org.junit.Test; +import org.junit.runner.RunWith; +import org.junit.runners.Parameterized; +import org.junit.runners.Parameterized.Parameters; + +import java.util.Arrays; +import java.util.Collection; + +import static org.junit.Assert.assertEquals; + +@RunWith(Parameterized.class) +public class LowerHyphenToLowerCamelConverterTest { + + private Converter converter = new LowerHyphenToLowerCamelConverter(); + + private String input; + private String expected; + + public LowerHyphenToLowerCamelConverterTest(String input, String expected){ + this.input = input; + this.expected = expected; + } + + /** + * Data Provider for the Lower Hyphen to Camel Converter Tests + * Make sure the capitalization is not lost during the conversion + * @return + */ + @Parameters + public static Collection<Object[]> data(){ + + return Arrays.asList(new Object[][]{ + {null, null}, + {"test-name", "testName"}, + {"test---name", "testName"}, // Case multiple + {"testName", "testName"}, // Case where upper case word shouldn't be lowercased + {"test-name-cool", "testNameCool"}, + {"test-name-Cool", "testNameCool"}, + {"test-name-Cool-Name-wow----Rest", "testNameCoolNameWowRest"}, + {"test-name#fast#", "testName#fast#"}, + {"test-name---", "testName"}, + {"----test-name", "TestName"}, + }); + } + + @Test + public void testIfInputSuccessfullyModified(){ + String actual = converter.convert(input); + assertEquals(expected, actual); + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/transforms/MapTraverserTest.java b/aai-resources/src/test/java/org/onap/aai/transforms/MapTraverserTest.java new file mode 100644 index 0000000..092e0fd --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/transforms/MapTraverserTest.java @@ -0,0 +1,55 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.transforms; + +import com.bazaarvoice.jolt.JsonUtils; +import org.junit.Test; + +import java.io.IOException; +import java.util.Map; + +public class MapTraverserTest { + + private final String testResources = "src/test/resources/maputils/testcases/"; + + private String[] testCases = { "TestCase1.json", "TestCase2.json" }; + private MapTraverser traverser = new MapTraverser(new LowerCamelToLowerHyphenConverter()); + + @Test(expected = NullPointerException.class) + public void testIfMapIsNullThrowNullPointerException(){ + Map<String, Object> map = null; + traverser.convertKeys(map); + } + + @Test + public void runTestCases() throws IOException { + + for(String testCase : testCases){ + Map<String, Object> values = JsonUtils.filepathToMap(testResources + testCase); + + Object input = values.get("input"); + Object actual = traverser.convertKeys((Map<String, Object>)input); + Object output = values.get("output"); + JoltTestUtil.runArrayOrderObliviousDiffy( "failed case " + testCase, output, actual ); + } + } +} diff --git a/aai-resources/src/test/java/org/onap/aai/util/AAIAppServletContextListenerTest.java b/aai-resources/src/test/java/org/onap/aai/util/AAIAppServletContextListenerTest.java new file mode 100644 index 0000000..c079007 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/util/AAIAppServletContextListenerTest.java @@ -0,0 +1,176 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +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; +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Rule; +import org.junit.Test; +import org.onap.aai.dbmap.AAIGraph; +import org.onap.aai.logging.ErrorLogHelper; +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 javax.servlet.ServletContextEvent; +import java.util.ArrayList; +import java.util.List; + +import static org.junit.Assert.assertTrue; + +@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/onap/aai/util/AAICSVWriterTest.java b/aai-resources/src/test/java/org/onap/aai/util/AAICSVWriterTest.java new file mode 100644 index 0000000..dae280f --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/util/AAICSVWriterTest.java @@ -0,0 +1,173 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +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; + +import java.io.*; +import java.nio.file.Files; +import java.nio.file.Paths; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +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/onap/aai/util/AAIRSyncUtilityTest.java b/aai-resources/src/test/java/org/onap/aai/util/AAIRSyncUtilityTest.java new file mode 100644 index 0000000..34f353d --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/util/AAIRSyncUtilityTest.java @@ -0,0 +1,213 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + + +import org.junit.Before; +import org.junit.Ignore; +import org.junit.Test; +import org.onap.aai.AAISetup; + +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 static org.junit.Assert.*; + +@Ignore +public class AAIRSyncUtilityTest extends AAISetup { + + 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. + */ + @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/onap/aai/util/DataConversionHelperTest.java b/aai-resources/src/test/java/org/onap/aai/util/DataConversionHelperTest.java new file mode 100644 index 0000000..3eb21b1 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/util/DataConversionHelperTest.java @@ -0,0 +1,89 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import org.junit.Rule; +import org.junit.Test; +import org.powermock.modules.agent.PowerMockAgent; +import org.powermock.modules.junit4.rule.PowerMockRule; + +import static org.junit.Assert.assertEquals; + +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/aai-resources/src/test/java/org/onap/aai/util/DbTestConfig.java b/aai-resources/src/test/java/org/onap/aai/util/DbTestConfig.java new file mode 100644 index 0000000..eac8350 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/util/DbTestConfig.java @@ -0,0 +1,296 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import java.io.*; +import java.net.InetAddress; +import java.util.*; + +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/onap/aai/util/DbTestFileWatcher.java b/aai-resources/src/test/java/org/onap/aai/util/DbTestFileWatcher.java new file mode 100644 index 0000000..9141bd6 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/util/DbTestFileWatcher.java @@ -0,0 +1,65 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import java.io.File; +import java.util.TimerTask; + +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/onap/aai/util/DbTestGetFileTime.java b/aai-resources/src/test/java/org/onap/aai/util/DbTestGetFileTime.java new file mode 100644 index 0000000..aa8aff8 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/util/DbTestGetFileTime.java @@ -0,0 +1,56 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.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/onap/aai/util/DbTestProcessBuilder.java b/aai-resources/src/test/java/org/onap/aai/util/DbTestProcessBuilder.java new file mode 100644 index 0000000..9777f79 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/util/DbTestProcessBuilder.java @@ -0,0 +1,215 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import java.io.*; +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/onap/aai/util/HbaseSaltPrefixerTest.java b/aai-resources/src/test/java/org/onap/aai/util/HbaseSaltPrefixerTest.java new file mode 100644 index 0000000..b42c592 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/util/HbaseSaltPrefixerTest.java @@ -0,0 +1,40 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import org.junit.Test; + +import static org.junit.Assert.assertTrue; + +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/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java b/aai-resources/src/test/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java new file mode 100644 index 0000000..90e16c3 --- /dev/null +++ b/aai-resources/src/test/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java @@ -0,0 +1,72 @@ +/** + * ============LICENSE_START======================================================= + * org.onap.aai + * ================================================================================ + * Copyright © 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========================================================= + * + * ECOMP is a trademark and service mark of AT&T Intellectual Property. + */ +package org.onap.aai.util; + +import org.junit.Test; + +import java.io.ByteArrayOutputStream; +import java.io.PrintStream; +import java.util.regex.Matcher; +import java.util.regex.Pattern; + +import static org.junit.Assert.assertTrue; + + +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); + } + +} |