diff options
Diffstat (limited to 'aai-core/src/test/java')
29 files changed, 5232 insertions, 0 deletions
diff --git a/aai-core/src/test/java/org/openecomp/aai/exceptions/AAIExceptionTest.java b/aai-core/src/test/java/org/openecomp/aai/exceptions/AAIExceptionTest.java new file mode 100644 index 00000000..231101a8 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/exceptions/AAIExceptionTest.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.exceptions; + + +import static org.junit.Assert.assertEquals; + +import org.junit.BeforeClass; + +import org.junit.Test; + +import static org.junit.Assert.assertEquals; + +public class AAIExceptionTest { + private static final String code = "4004"; + private static final String details = "This is a detailed description of the exception."; + private static final Throwable cause = new RuntimeException("This is a runtime exception."); + private static final Throwable noMessage = new RuntimeException(); + + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + /** + * Test constructor with 0 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith0Params() throws Exception { + AAIException exception = new AAIException(); + assertEquals(exception, exception); + } + + /** + * Test constructor with 1 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith1Params() throws Exception { + AAIException exception = new AAIException(code); + assertEquals(exception, exception); + } + + /** + * Test constructor with 2 params details. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith2ParamsDetails() throws Exception { + AAIException exception = new AAIException(code, details); + assertEquals(details, exception.getMessage()); + } + + /** + * Test constructor with 2 params cause. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith2ParamsCause() throws Exception { + AAIException exception = new AAIException(code, cause); + assertEquals(cause.getMessage(), exception.getMessage()); + } + + /** + * Test constructor with 2 params null message. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith2ParamsNullMessage() throws Exception { + AAIException exception = new AAIException(code, noMessage); + assertEquals(noMessage.toString(), exception.getMessage()); + } + + /** + * Test constructor with 3 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith3Params() throws Exception { + AAIException exception = new AAIException(code, cause, details); + String details = "This is a runtime exception.-This is a detailed description of the exception."; + assertEquals(details, exception.getMessage()); + } + + /** + * Test constructor with 3 params null message. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith3ParamsNullMessage() throws Exception { + AAIException exception = new AAIException(code, noMessage, details); + String detailString = new String(noMessage.toString() + "-" + details); + assertEquals(detailString, exception.getMessage()); + } +} diff --git a/aai-core/src/test/java/org/openecomp/aai/exceptions/AAIExceptionWithInfoTest.java b/aai-core/src/test/java/org/openecomp/aai/exceptions/AAIExceptionWithInfoTest.java new file mode 100644 index 00000000..03de45d8 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/exceptions/AAIExceptionWithInfoTest.java @@ -0,0 +1,146 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.exceptions; + +import org.junit.Test; + +import java.util.HashMap; + +import static org.junit.Assert.assertEquals; + +public class AAIExceptionWithInfoTest { + + + private static final HashMap<String, Object> map = new HashMap<String, Object>(); + + { + map.put("itemInteger", 1); + map.put("itemString", "Two"); + map.put("itemThree", Boolean.TRUE); + } + + private static final String info = "An error has occurred."; + private static final String code = "4004"; + private static final String details = "This is a detailed description of the exception."; + private static final Throwable cause = new RuntimeException("This is a runtime exception."); + + /** + * Test constructor with 2 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith2Params() throws Exception { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(map, info); + + assertEquals(map, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test constructor with 3 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith3Params() throws Exception { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, map, info); + + assertEquals(code, exception.getErrorObject().getErrorCode()); + assertEquals(map, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test constructor with 4 params I. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith4ParamsI() throws Exception { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, details, map, info); + + assertEquals(code, exception.getErrorObject().getErrorCode()); + assertEquals(details, exception.getMessage()); + assertEquals(map, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test constructor with 4 params II. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith4ParamsII() throws Exception { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, cause, map, info); + + assertEquals(code, exception.getErrorObject().getErrorCode()); + assertEquals(cause.getMessage(), exception.getMessage()); + assertEquals(map, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test constructor with 5 params. + * + * @throws Exception the exception + */ + @Test + public void testConstructorWith5Params() throws Exception { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(code, cause, details, map, info); + + assertEquals(code, exception.getErrorObject().getErrorCode()); + assertEquals(cause.getMessage() + "-" + details, exception.getMessage()); + assertEquals(map, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test set info hash. + */ + @Test + public void testSetInfoHash() { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(map, info); + + HashMap<String, Object> newMap = new HashMap<String, Object>(); + newMap.put("itemInteger", 2); + exception.setInfoHash(newMap); + + assertEquals(newMap, exception.getInfoHash()); + assertEquals(info, exception.getInfo()); + } + + /** + * Test set info. + */ + @Test + public void testSetInfo() { + AAIExceptionWithInfo exception = new AAIExceptionWithInfo(map, info); + + String newInfo = "This is updated info."; + exception.setInfo(newInfo); + + assertEquals(map, exception.getInfoHash()); + assertEquals(newInfo, exception.getInfo()); + } + +} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/IntrospectorTestSpec.java b/aai-core/src/test/java/org/openecomp/aai/introspection/IntrospectorTestSpec.java new file mode 100644 index 00000000..3f9eafd5 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/introspection/IntrospectorTestSpec.java @@ -0,0 +1,60 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.introspection; + +import com.google.common.collect.Sets; +import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; + +import java.util.Set; + +import static org.junit.Assert.assertEquals; + +public class IntrospectorTestSpec { + + + + /** + * Container test set. + * + * @param wrappedPortGroups the wrapped port groups + * @throws AAIUnknownObjectException + */ + protected void containerTestSet(Introspector wrappedPortGroups) throws AAIUnknownObjectException { + + assertEquals( + "isContainer", + true, + wrappedPortGroups.isContainer()); + + assertEquals( + "newInstanceOfNestedProperty", + "PortGroup", + wrappedPortGroups.newInstanceOfNestedProperty("port-group").getClass().getSimpleName()); + + assertEquals( + "isComplexGenericType", + true, + wrappedPortGroups.isComplexGenericType("port-group")); + + + } + +} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/MoxyEngineTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/MoxyEngineTest.java new file mode 100644 index 00000000..7e6dacee --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/introspection/MoxyEngineTest.java @@ -0,0 +1,68 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.introspection; + +import org.eclipse.persistence.dynamic.DynamicEntity; +import org.eclipse.persistence.jaxb.UnmarshallerProperties; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.BeforeClass; +import org.junit.Test; +import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; +import org.openecomp.aai.serialization.queryformats.QueryFormatTestHelper; +import org.openecomp.aai.util.AAIConstants; + +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import java.io.StringReader; + +public class MoxyEngineTest extends IntrospectorTestSpec { + + /** + * Configure. + * @throws Exception + * @throws SecurityException + * @throws NoSuchFieldException + */ + @BeforeClass + public static void configure() throws NoSuchFieldException, SecurityException, Exception { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/org/openecomp/aai/introspection/"); + } + + /** + * Container object. + * @throws AAIUnknownObjectException + */ + @Test + public void containerObject() throws AAIUnknownObjectException { + + Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); + + Introspector obj = loader.introspectorFromName("port-groups"); + + this.containerTestSet(obj); + + } + + + +} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/PojoInjestorTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/PojoInjestorTest.java new file mode 100644 index 00000000..90d754a3 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/introspection/PojoInjestorTest.java @@ -0,0 +1,66 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.introspection; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.openecomp.aai.db.props.AAIProperties; + +import javax.xml.bind.JAXBContext; +import javax.xml.bind.JAXBException; +import javax.xml.bind.Marshaller; + +import static org.junit.Assert.*; + +public class PojoInjestorTest { + + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + @Test + public void getVersionTest() { + String latestVersion = "org.openecomp.aai.yang.VnfImage"; + PojoInjestor testPI = new PojoInjestor(); + assertEquals("", AAIProperties.LATEST, testPI.getVersion(latestVersion)); + + String oldVersion = "org.openecomp.aai.yang.v8.VnfImage"; + assertEquals("", Version.v8, testPI.getVersion(oldVersion)); + } + + @Test + public void getContextForVersionTest() { + PojoInjestor testPI = new PojoInjestor(); + JAXBContext context = testPI.getContextForVersion(Version.v9); + try { + Marshaller marshaller = context.createMarshaller(); + //this will fail if the context wasn't initialized successfully (I think) + marshaller.setProperty(org.eclipse.persistence.jaxb.MarshallerProperties.MEDIA_TYPE, "application/json"); + } catch (JAXBException e) { + e.printStackTrace(); + fail("failed on setting marshaller property"); + } + //if we get to here that means everything went ok + assertTrue(true); + } +} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/PojoLoaderTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/PojoLoaderTest.java new file mode 100644 index 00000000..f782e66b --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/introspection/PojoLoaderTest.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.introspection; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.openecomp.aai.domain.yang.v9.VnfImage; +import org.openecomp.aai.introspection.exceptions.AAIUnmarshallingException; +import org.openecomp.aai.restcore.MediaType; + +import static org.junit.Assert.assertTrue; +import static org.junit.Assert.fail; + +public class PojoLoaderTest { + + + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + @Test + public void test() { + Loader pojoLoader = LoaderFactory.createLoaderForVersion(ModelType.POJO, Version.v9); + String payload = "{\"vnf-image-uuid\":\"myuuid\",\"application\":\"testApp\",\"application-vendor\":\"testVendor\",\"application-version\":\"versionTest\"}"; + try { + Introspector intro = pojoLoader.unmarshal("vnf-image", payload, MediaType.APPLICATION_JSON_TYPE); + VnfImage myVnfImage = (VnfImage) intro.getUnderlyingObject(); + assertTrue("myuuid".equals(myVnfImage.getVnfImageUuid())); + assertTrue("testApp".equals(myVnfImage.getApplication())); + assertTrue("testVendor".equals(myVnfImage.getApplicationVendor())); + assertTrue("versionTest".equals(myVnfImage.getApplicationVersion())); + } catch (AAIUnmarshallingException e) { + e.printStackTrace(); + fail("AAIUnmarshallingException thrown"); + } + } + +} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/PojoStrategyTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/PojoStrategyTest.java new file mode 100644 index 00000000..d2f67836 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/introspection/PojoStrategyTest.java @@ -0,0 +1,43 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.introspection; + +import org.junit.Test; +import org.openecomp.aai.domain.yang.CloudRegion; +import org.openecomp.aai.domain.yang.VolumeGroup; +import org.openecomp.aai.schema.enums.ObjectMetadata; + +import static org.junit.Assert.assertEquals; + +public class PojoStrategyTest { + + @Test + public void getMetadataTest() { + Introspector cloudregion = IntrospectorFactory.newInstance(ModelType.POJO, new CloudRegion()); + assertEquals("cloud-infrastructure", cloudregion.getMetadata(ObjectMetadata.NAMESPACE)); + assertEquals("cloud-regions", cloudregion.getMetadata(ObjectMetadata.CONTAINER)); + + Introspector volumegroup = IntrospectorFactory.newInstance(ModelType.POJO, new VolumeGroup()); + assertEquals("cloud-region", volumegroup.getMetadata(ObjectMetadata.DEPENDENT_ON)); + assertEquals("", volumegroup.getMetadata(ObjectMetadata.NAMESPACE)); + } + +} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/PropertyPredicatesTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/PropertyPredicatesTest.java new file mode 100644 index 00000000..6b37f4c6 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/introspection/PropertyPredicatesTest.java @@ -0,0 +1,79 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.introspection; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; +import org.openecomp.aai.serialization.queryformats.QueryFormatTestHelper; +import org.openecomp.aai.util.AAIConstants; + +import java.util.Set; + +import static org.hamcrest.Matchers.hasItems; +import static org.hamcrest.Matchers.not; +import static org.junit.Assert.assertThat; + +public class PropertyPredicatesTest { + + + private final static Version version = Version.v10; + private static Loader loader; + private final static ModelType introspectorFactoryType = ModelType.MOXY; + private static Introspector obj; + + @BeforeClass + public static void setup() throws NoSuchFieldException, SecurityException, Exception { + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/org/openecomp/aai/introspection/"); + loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); + obj = loader.introspectorFromName("test-object"); + + } + + @Test + public void includeInTestGeneration() throws AAIUnknownObjectException { + + Set<String> props = obj.getProperties(PropertyPredicates.includeInTestGeneration()); + + assertThat("props not found", props, + not(hasItems("persona-model-ver", "not-visible-test-element", "model-invariant-id", "model-version-id"))); + } + + @Test + public void isVisible() throws AAIUnknownObjectException { + + Set<String> props = obj.getProperties(PropertyPredicates.isVisible()); + + assertThat("props not found", props, not(hasItems("persona-model-ver"))); + } + + @Test + public void all() throws AAIUnknownObjectException { + + Set<String> props = obj.getProperties(); + + assertThat("all found", props, hasItems("persona-model-ver", "not-visible-test-element")); + } + + +} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/ReflectionEngineTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/ReflectionEngineTest.java new file mode 100644 index 00000000..37df2aeb --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/introspection/ReflectionEngineTest.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.introspection; + +import org.junit.BeforeClass; +import org.junit.Test; +import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; +import org.openecomp.aai.restcore.CustomJacksonJaxBJsonProvider; + +import javax.xml.bind.JAXBException; +import java.io.ByteArrayInputStream; +import java.io.IOException; +import java.io.InputStream; +import java.nio.charset.StandardCharsets; + +public class ReflectionEngineTest extends IntrospectorTestSpec { + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + /** + * Container object. + * + * @throws InstantiationException the instantiation exception + * @throws IllegalAccessException the illegal access exception + * @throws ClassNotFoundException the class not found exception + * @throws AAIUnknownObjectException + */ + @Test + public void containerObject() throws InstantiationException, IllegalAccessException, ClassNotFoundException, AAIUnknownObjectException { + Object javaObj = null; + String className = "org.openecomp.aai.domain.yang.v8.PortGroups"; + javaObj = Class.forName(className).newInstance(); + + Introspector obj = IntrospectorFactory.newInstance(ModelType.POJO, javaObj); + + this.containerTestSet(obj); + } +} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/sideeffect/DataCopyTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/sideeffect/DataCopyTest.java new file mode 100644 index 00000000..3a45a9f4 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/introspection/sideeffect/DataCopyTest.java @@ -0,0 +1,278 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.introspection.sideeffect; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import java.io.FileInputStream; +import java.io.IOException; +import java.io.UnsupportedEncodingException; +import java.lang.reflect.InvocationTargetException; +import java.net.MalformedURLException; +import java.net.URISyntaxException; + +import org.apache.commons.io.IOUtils; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import org.openecomp.aai.db.props.AAIProperties; +import org.openecomp.aai.dbmap.DBConnectionType; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Introspector; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.introspection.sideeffect.exceptions.AAIMissingRequiredPropertyException; +import org.openecomp.aai.parsers.query.QueryParser; +import org.openecomp.aai.serialization.db.DBSerializer; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; +import org.openecomp.aai.serialization.queryformats.QueryFormatTestHelper; +import org.openecomp.aai.util.AAIConstants; +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanTransaction; + +public class DataCopyTest { + + private static TitanGraph graph; + 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 static Loader loader; + private static TransactionalGraphEngine dbEngine; + @Mock private Vertex self; + @Mock private VertexProperty<String> prop; + @Mock private QueryParser uriQuery; + @Rule + public ExpectedException thrown = ExpectedException.none(); + + + @BeforeClass + public static void setup() throws NoSuchFieldException, SecurityException, Exception { + graph = TitanFactory.build().set("storage.backend","inmemory").open(); + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/org/openecomp/aai/introspection/"); + loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); + dbEngine = new TitanDBEngine( + queryStyle, + type, + loader); + + graph.traversal().addV("aai-node-type", "model", "model-invariant-id", "key1").as("v1") + .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key2", "model-version", "testValue").addInE("has", "v1", "isParent", true) + .addV("aai-node-type", "model", "model-invariant-id", "key3").as("v2") + .addV("aai-node-type", "model-ver", "model-ver", "myValue", "model-version-id", "key4").addInE("has", "v2", "isParent", true) + .next(); + graph.tx().commit(); + } + + @AfterClass + public static void tearDown() { + graph.tx().rollback(); + graph.close(); + } + + @Before + public void initMock() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void runPopulatePersonaModelVer() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v10); + final Introspector obj = loader.introspectorFromName("test-object"); + obj.setValue("vnf-id", "myId"); + obj.setValue("model-invariant-id", "key1"); + obj.setValue("model-version-id", "key2"); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + TitanTransaction g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataCopy.class).build(); + + runner.execute(obj, self); + + assertEquals("value populated", "testValue", obj.getValue("persona-model-ver")); + + g.rollback(); + + + } + + @Test + public void runPopulateModelVersionId() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); + final Introspector obj = loader.introspectorFromName("test-object"); + obj.setValue("vnf-id", "myId"); + obj.setValue("persona-model-id", "key1"); + obj.setValue("persona-model-version", "testValue"); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + TitanTransaction g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataCopy.class).build(); + + runner.execute(obj, self); + + assertEquals("value populated", "key2", obj.getValue("model-version-id")); + + g.rollback(); + } + + @Test + public void verifyNestedSideEffect() throws URISyntaxException, AAIException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, IOException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v10); + final Introspector obj = loader.unmarshal("customer", this.getJsonString("nested-case.json")); + System.out.println(obj.marshal(true)); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + TitanTransaction g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.tx()).thenReturn(g); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + when(uriQuery.isDependent()).thenReturn(false); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + Vertex v= serializer.createNewVertex(obj); + serializer.serializeToDb(obj, v, uriQuery, obj.getURI(), "test"); + + assertEquals("nested value populated", "testValue", g.traversal().V().has("service-instance-id", "nested-instance-key").next().property("persona-model-version").orElse("")); + + g.rollback(); + + } + + @Test + public void expectedMissingPropertyExceptionInURI() throws AAIException, UnsupportedEncodingException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v10); + final Introspector obj = loader.introspectorFromName("test-object"); + obj.setValue("vnf-id", "myId"); + obj.setValue("model-invariant-id", "key1"); + + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + TitanTransaction g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataCopy.class).build(); + + thrown.expect(AAIMissingRequiredPropertyException.class); + runner.execute(obj, self); + } + + @Test + public void expectedMissingPropertyExceptionForResultingObject() throws AAIException, UnsupportedEncodingException { + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v10); + final Introspector obj = loader.introspectorFromName("test-object"); + obj.setValue("vnf-id", "myId"); + obj.setValue("model-invariant-id", "key3"); + obj.setValue("model-version-id", "key4"); + + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + TitanTransaction g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataCopy.class).build(); + + thrown.expect(AAIMissingRequiredPropertyException.class); + runner.execute(obj, self); + } + + @Test + public void expectNoProcessingWithNoProperties() throws AAIException, UnsupportedEncodingException { + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v10); + final Introspector obj = loader.introspectorFromName("test-object"); + obj.setValue("vnf-id", "myId"); + + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + TitanTransaction g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataCopy.class).build(); + + runner.execute(obj, self); + + assertEquals("no model-version-id", true, obj.getValue("model-version-id") == null); + assertEquals("no model-invariant-id", true, obj.getValue("model-invariant-id") == null); + + } + + private String getJsonString(String filename) throws IOException { + + + FileInputStream is = new FileInputStream("src/test/resources/org/openecomp/aai/introspection/sideeffect/" + filename); + String s = IOUtils.toString(is, "UTF-8"); + IOUtils.closeQuietly(is); + + return s; + } +} diff --git a/aai-core/src/test/java/org/openecomp/aai/introspection/sideeffect/DataLinkTest.java b/aai-core/src/test/java/org/openecomp/aai/introspection/sideeffect/DataLinkTest.java new file mode 100644 index 00000000..063a7c15 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/introspection/sideeffect/DataLinkTest.java @@ -0,0 +1,268 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.introspection.sideeffect; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import java.io.UnsupportedEncodingException; +import java.lang.reflect.InvocationTargetException; +import java.net.MalformedURLException; +import java.net.URISyntaxException; +import java.util.List; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.structure.VertexProperty; +import org.junit.AfterClass; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; +import org.mockito.Mock; +import org.mockito.MockitoAnnotations; + +import org.openecomp.aai.db.props.AAIProperties; +import org.openecomp.aai.dbmap.DBConnectionType; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Introspector; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.parsers.query.QueryParser; +import org.openecomp.aai.serialization.db.DBSerializer; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; +import org.openecomp.aai.serialization.queryformats.QueryFormatTestHelper; +import org.openecomp.aai.util.AAIConstants; +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanTransaction; + +public class DataLinkTest { + + private static TitanGraph graph; + 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 static Loader loader; + private static TransactionalGraphEngine dbEngine; + @Mock private QueryParser parser; + @Mock private Vertex self; + @Mock private VertexProperty<String> prop; + @Rule + public ExpectedException thrown = ExpectedException.none(); + + + @BeforeClass + public static void setup() throws NoSuchFieldException, SecurityException, Exception { + graph = TitanFactory.build().set("storage.backend","inmemory").open(); + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/org/openecomp/aai/introspection/"); + loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); + dbEngine = new TitanDBEngine( + queryStyle, + type, + loader); + + graph.traversal().addV("aai-node-type", "vpn-binding", "vpn-id", "addKey").as("v1") + .addV("aai-node-type", "vpn-binding", "vpn-id", "modifyKey").as("v2") + .addV("aai-node-type", "route-target", "global-route-target", "modifyTargetKey", "route-target-role", "modifyRoleKey", "linked", true).addInE("has", "v2", "isParent", true) + .addV("aai-node-type", "vpn-binding", "vpn-id", "deleteKey").as("v3") + .addV("aai-node-type", "route-target", "global-route-target", "deleteTargetKey", "route-target-role", "deleteRoleKey", "linked", true).addInE("has", "v3", "isParent", true) + .addV("aai-node-type", "vpn-binding", "vpn-id", "getKey").as("v4") + .addV("aai-node-type", "route-target", "global-route-target", "getTargetKey", "route-target-role", "getRoleKey", "linked", true).addInE("has", "v4", "isParent", true) + .addV("aai-node-type", "vpn-binding", "vpn-id", "getKeyNoLink").as("v5") + .addV("aai-node-type", "route-target", "global-route-target", "getTargetKeyNoLink", "route-target-role", "getRoleKeyNoLink").addInE("has", "v5", "isParent", true) + .next(); + graph.tx().commit(); + } + + @AfterClass + public static void tearDown() { + graph.tx().rollback(); + graph.close(); + } + + @Before + public void initMock() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void verifyCreationOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); + final Introspector obj = loader.introspectorFromName("vpn-binding"); + obj.setValue("vpn-id", "addKey"); + obj.setValue("global-route-target", "key1"); + obj.setValue("route-target-role", "key2"); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + TitanTransaction g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(spy.tx()).thenReturn(g); + when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build(); + + runner.execute(obj, self); + + assertEquals("route-target vertex found", true, traversal.V() + .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "key1").has("route-target-role", "key2").has("linked", true).hasNext()); + + g.rollback(); + + } + + @Test + public void verifyModificationOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); + final Introspector obj = loader.introspectorFromName("vpn-binding"); + obj.setValue("vpn-id", "modifyKey"); + obj.setValue("global-route-target", "modifyTargetKey2"); + obj.setValue("route-target-role", "modifyRoleKey2"); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + TitanTransaction g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(spy.tx()).thenReturn(g); + when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build(); + + runner.execute(obj, self); + + assertEquals("route-target vertex found", true, traversal.V() + .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "modifyTargetKey2").has("route-target-role", "modifyRoleKey2").has("linked", true).hasNext()); + assertEquals("previous link removed", true, traversal.V() + .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "modifyTargetKey").has("route-target-role", "modifyRoleKey").hasNot("linked").hasNext()); + g.rollback(); + + } + + @Test + public void verifyDeleteOfVertex() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); + final Introspector obj = loader.introspectorFromName("vpn-binding"); + obj.setValue("vpn-id", "deleteKey"); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + TitanTransaction g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(spy.tx()).thenReturn(g); + when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataLinkWriter.class).build(); + + runner.execute(obj, self); + + assertEquals("route-target vertex not found", false, traversal.V() + .has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "deleteTargetKey").has("route-target-role", "deleteRoleKey").has("linked", true).hasNext()); + g.rollback(); + + } + + @Test + public void verifyPropertyPopulation() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { + + final Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9); + final Introspector obj = loader.introspectorFromName("vpn-binding"); + obj.setValue("vpn-id", "getKey"); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + TitanTransaction g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(spy.tx()).thenReturn(g); + when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + SideEffectRunner runner = new SideEffectRunner + .Builder(spy, serializer).addSideEffect(DataLinkReader.class).build(); + + runner.execute(obj, self); + + assertEquals("both properties have been populated in target object", true, obj.getValue("global-route-target").equals("getTargetKey") && obj.getValue("route-target-role").equals("getRoleKey")); + g.rollback(); + + } + + @Test + public void verifyPropertyPopulationWithV10OnlyPut() throws URISyntaxException, AAIException, UnsupportedEncodingException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, SecurityException, InstantiationException, NoSuchMethodException, MalformedURLException { + final Introspector obj = loader.introspectorFromName("vpn-binding"); + obj.setValue("vpn-id", "getKeyNoLink"); + final Introspector routeTargets = loader.introspectorFromName("route-targets"); + obj.setValue("route-targets", routeTargets.getUnderlyingObject()); + List<Object> targets = routeTargets.getValue("route-target"); + final Introspector routeTargetOne = loader.introspectorFromName("route-target"); + routeTargetOne.setValue("global-route-target", "getTargetKeyNoLink"); + routeTargetOne.setValue("route-target-role", "getRoleKeyNoLink"); + targets.add(routeTargetOne.getUnderlyingObject()); + final Introspector routeTargetTwo = loader.introspectorFromName("route-target"); + routeTargetTwo.setValue("global-route-target", "getTargetKeyNoLink2"); + routeTargetTwo.setValue("route-target-role", "getRoleKeyNoLink2"); + targets.add(routeTargetTwo.getUnderlyingObject()); + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + TitanTransaction g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.tx()).thenReturn(g); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + when(spy.tx()).thenReturn(g); + when(parser.isDependent()).thenReturn(false); + when(self.<String>property(AAIProperties.AAI_URI)).thenReturn(prop); + when(prop.orElse(null)).thenReturn(obj.getURI()); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + Vertex v = serializer.createNewVertex(obj); + serializer.serializeToDb(obj, v, parser, obj.getURI(), "testing"); + Vertex routeTargetOneV = traversal.V().has("global-route-target", "getTargetKeyNoLink").next(); + Vertex routeTargetTwoV = traversal.V().has("global-route-target", "getTargetKeyNoLink2").next(); + + assertEquals("first route target put has linked", true, routeTargetOneV.property(AAIProperties.LINKED).orElse(false)); + assertEquals("second route target put does not have linked", false, routeTargetTwoV.property(AAIProperties.LINKED).orElse(false)); + + g.rollback(); + + } +} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/query/GraphTraversalTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/query/GraphTraversalTest.java new file mode 100644 index 00000000..2f0d67df --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/parsers/query/GraphTraversalTest.java @@ -0,0 +1,704 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.parsers.query; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.ArrayList; +import java.util.List; + +import javax.ws.rs.core.MultivaluedHashMap; +import javax.ws.rs.core.MultivaluedMap; +import javax.ws.rs.core.UriBuilder; + +import org.apache.tinkerpop.gremlin.process.traversal.P; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import org.openecomp.aai.db.props.AAIProperties; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; +import org.openecomp.aai.serialization.queryformats.QueryFormatTestHelper; +import org.openecomp.aai.util.AAIConstants; + + +public class GraphTraversalTest { + + private static TransactionalGraphEngine dbEngine; + + private static TransactionalGraphEngine dbEnginev9; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Configure. + * @throws Exception + * @throws SecurityException + * @throws NoSuchFieldException + */ + @BeforeClass + public static void configure() throws NoSuchFieldException, SecurityException, Exception { + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/org/openecomp/aai/introspection/"); + dbEngine = + new TitanDBEngine(QueryStyle.TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST), + false); + + dbEnginev9 = + new TitanDBEngine(QueryStyle.TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v9), + false); + } + + /** + * Parent query. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("physical-location-id", "key1").has("aai-node-type", "complex"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal to normal query", + expected.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be complex", + "complex", + query.getResultType()); + assertEquals( + "result type should be empty", + "", + query.getParentResultType()); + assertEquals("dependent",false, query.isDependent()); + + + } + + /** + * Child query. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void childQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("physical-location-id", "key1").has("aai-node-type", "complex") + .out("hasCtagPool") + .has("aai-node-type", "ctag-pool") + .has("target-pe", "key2").has("availability-zone-name", "key3"); + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("physical-location-id", "key1").has("aai-node-type", "complex"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for complex", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be complex", + "complex", + query.getParentResultType()); + assertEquals( + "result type should be ctag-pool", + "ctag-pool", + query.getResultType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + /** + * Naming exceptions. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void namingExceptions() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("aai-node-type", "port-group") + .has("interface-id", "key2").out("hasCTag") + .has("aai-node-type", "cvlan-tag") + .has("cvlan-tag", 655); + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("aai-node-type", "port-group") + .has("interface-id", "key2"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + assertEquals( + "result type should be port-group", + "port-group", + query.getParentResultType()); + assertEquals( + "contaner type should be empty", + "", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + /** + * Gets the all. + * + * @return the all + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void getAll() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("aai-node-type", "port-group") + .has("interface-id", "key2").out("hasCTag") + .has("aai-node-type", "cvlan-tag"); + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("aai-node-type", "port-group") + .has("interface-id", "key2"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be port-group", + "port-group", + query.getParentResultType()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + assertEquals( + "container type should be cvlan-tags", + "cvlan-tags", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + @Test + public void getAllParent() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("aai-node-type", "pserver"); + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("aai-node-type", "pserver"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for pserver", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "parent result type should be empty", + "", + query.getParentResultType()); + assertEquals( + "result type should be pserver", + "pserver", + query.getResultType()); + assertEquals( + "container type should be pservers", + "pservers", + query.getContainerType()); + assertEquals("dependent",false, query.isDependent()); + + + } + + + /** + * Gets the via query param. + * + * @return the via query param + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void getViaQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + map.putSingle("tenant-name", "Tenant1"); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid") + .has("aai-node-type", "cloud-region") + .out("has") + .has("aai-node-type", "tenant") + .has("tenant-name", "Tenant1"); + + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid") + .has("aai-node-type", "cloud-region"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for cloud-region", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be cloud-region", + "cloud-region", + query.getParentResultType()); + assertEquals( + "result type should be tenant", + "tenant", + query.getResultType()); + assertEquals( + "container type should be empty", + "", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + } + + @Test + public void getViaDuplicateQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + List<String> values = new ArrayList<>(); + values.add("Tenant1"); + values.add("Tenant2"); + map.put("tenant-name", values); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid") + .has("aai-node-type", "cloud-region") + .out("has") + .has("aai-node-type", "tenant") + .has("tenant-name", P.within(values)); + + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("cloud-owner", "mycloudowner").has("cloud-region-id", "mycloudregionid") + .has("aai-node-type", "cloud-region"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for cloud-region", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be cloud-region", + "cloud-region", + query.getParentResultType()); + assertEquals( + "result type should be tenant", + "tenant", + query.getResultType()); + assertEquals( + "container type should be empty", + "", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + } + + /** + * Gets the plural via query param. + * + * @return the plural via query param + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void getPluralViaQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vnfcs").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + map.putSingle("prov-status", "up"); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("aai-node-type", "vnfc") + .has("prov-status", "up"); + + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("aai-node-type", "vnfc"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "parent result type should be empty", + "", + query.getParentResultType()); + assertEquals( + "result type should be vnfc", + "vnfc", + query.getResultType()); + assertEquals( + "container type should be empty", + "vnfcs", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + } + + /** + * Gets the all query param naming exception. + * + * @return the all query param naming exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void getAllQueryParamNamingException() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + map.putSingle("cvlan-tag", "333"); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("aai-node-type", "port-group") + .has("interface-id", "key2").out("hasCTag") + .has("aai-node-type", "cvlan-tag") + .has("cvlan-tag", 333); + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("vnf-id", "key1").has("aai-node-type", "vce") + .out("hasPortGroup") + .has("aai-node-type", "port-group") + .has("interface-id", "key2"); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be port-group", + "port-group", + query.getParentResultType()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + assertEquals( + "container type should be cvlan-tags", + "cvlan-tags", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + /** + * Abstract type. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void abstractType() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("vnf/key1").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("vnf-id", "key1").or( + __.has(AAIProperties.NODE_TYPE, "vce"), + __.has(AAIProperties.NODE_TYPE, "vpe"), + __.has(AAIProperties.NODE_TYPE, "generic-vnf")); + + GraphTraversal<Vertex, Vertex> expectedParent = expected; + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be empty", + "", + query.getParentResultType()); + assertEquals( + "result type should be vnf", + "vnf", + query.getResultType()); + + assertEquals("dependent",false, query.isDependent()); + + + } + + /** + * Non parent abstract type. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void nonParentAbstractType() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key2/vnf/key1").build(); + thrown.expect(AAIException.class); + thrown.expectMessage(containsString("not a valid path")); + dbEngine.getQueryBuilder().createQueryFromURI(uri); + } + + @Test + public void parentAbstractTypeWithNesting() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("vnf/key1/vf-modules/vf-module/key2").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("vnf-id", "key1").or( + __.has(AAIProperties.NODE_TYPE, "vce"), + __.has(AAIProperties.NODE_TYPE, "vpe"), + __.has(AAIProperties.NODE_TYPE, "generic-vnf")) + .filter(x -> true).outE().has("isParent", true).inV().has("vf-module-id", "key2"); + + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("vnf-id", "key1").or( + __.has(AAIProperties.NODE_TYPE, "vce"), + __.has(AAIProperties.NODE_TYPE, "vpe"), + __.has(AAIProperties.NODE_TYPE, "generic-vnf")); + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent gremlin query should be equal the query for ", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "result type should be vnf", + "vnf", + query.getParentResultType()); + assertEquals( + "result type should be vf-module", + "vf-module", + query.getResultType()); + + assertEquals("dependent",true, query.isDependent()); + + } + + @Test + public void getViaBadQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/cloud-regions/cloud-region/a/b/tenants/tenant").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + map.putSingle("tenant-n231ame", "Tenant1"); + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + + } + + @Test + public void getPluralViaBadQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/cloud-regions/cloud-region/a/b/tenants").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + map.putSingle("tenant-n231ame", "Tenant1"); + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + + } + + @Test + public void getPluralViaDuplicateQueryParam() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vnfcs").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + List<String> values = new ArrayList<>(); + values.add("up"); + values.add("down"); + values.add("left"); + values.add("right"); + values.add("start"); + map.put("prov-status", values); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri, map); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("aai-node-type", "vnfc") + .has("prov-status", P.within(values)); + + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("aai-node-type", "vnfc"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + assertEquals( + "parent result type should be empty", + "", + query.getParentResultType()); + assertEquals( + "result type should be vnfc", + "vnfc", + query.getResultType()); + assertEquals( + "container type should be empty", + "vnfcs", + query.getContainerType()); + assertEquals("dependent",true, query.isDependent()); + + } + + @Test + public void dbAliasedSearch() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/test-objects").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + map.putSingle("persona-model-customization-id", "key2"); + QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri, map); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("aai-node-type", "test-object") + .has("model-customization-id", "key2"); + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("aai-node-type", "test-object"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + + assertEquals( + "result type should be", + "test-object", + query.getResultType()); + assertEquals( + "result type should be empty", + "", + query.getParentResultType()); + assertEquals("dependent",true, query.isDependent()); + + + } + + @Test + public void dataLinkedSearch() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vpn-bindings").build(); + MultivaluedMap<String, String> map = new MultivaluedHashMap<>(); + map.putSingle("global-route-target", "key2"); + QueryParser query = dbEnginev9.getQueryBuilder().createQueryFromURI(uri, map); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .has("aai-node-type", "vpn-binding") + .where(__.out("has").has(AAIProperties.NODE_TYPE, "route-target").has("global-route-target", "key2")); + GraphTraversal<Vertex, Vertex> expectedParent = __.<Vertex>start() + .has("aai-node-type", "vpn-binding"); + + assertEquals( + "gremlin query should be " + expected.toString(), + expected.toString(), + query.getQueryBuilder().getQuery().toString()); + assertEquals( + "parent", + expectedParent.toString(), + query.getQueryBuilder().getParentQuery().getQuery().toString()); + + assertEquals( + "result type should be", + "vpn-binding", + query.getResultType()); + assertEquals( + "result type should be empty", + "", + query.getParentResultType()); + assertEquals("dependent",true, query.isDependent()); + + + } +} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/query/LegacyQueryTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/query/LegacyQueryTest.java new file mode 100644 index 00000000..4302de61 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/parsers/query/LegacyQueryTest.java @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.parsers.query; + +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.BeforeClass; +import org.junit.Test; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelInjestor; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; + +import javax.ws.rs.core.UriBuilder; +import javax.xml.bind.JAXBException; +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import static org.junit.Assert.assertEquals; + + +public class LegacyQueryTest { + private ModelInjestor injestor = ModelInjestor.getInstance(); + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8), + false); + private final Version version = Version.v8; + private DynamicJAXBContext context = injestor.getContextForVersion(version); + + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + /** + * Parent query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + + URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key1").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + String expected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal to normal query", + expected, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be pserver", + "pserver", + query.getResultType()); + + } + + /** + * Child query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/pservers/pserver/key1/lag-interfaces/lag-interface/key2").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + + String expected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')" + + ".in('tosca.relationships.BindsTo').has('aai-node-type', 'lag-interface')" + + ".has('interface-name', 'key2')"; + String parentExpected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be for node", + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be for parent", + parentExpected, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be lag-interface", + "lag-interface", + query.getResultType()); + } + + /** + * Naming exceptions. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); + + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')" + + ".has('cvlan-tag', 655)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + + } + +} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/query/RelationshipGremlinQueryTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/query/RelationshipGremlinQueryTest.java new file mode 100644 index 00000000..eef3529c --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/parsers/query/RelationshipGremlinQueryTest.java @@ -0,0 +1,677 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.parsers.query; + +import static org.hamcrest.CoreMatchers.containsString; +import static org.junit.Assert.assertEquals; + +import java.io.StringReader; +import java.io.UnsupportedEncodingException; + +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; + +import org.eclipse.persistence.dynamic.DynamicEntity; +import org.eclipse.persistence.jaxb.UnmarshallerProperties; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Introspector; +import org.openecomp.aai.introspection.IntrospectorFactory; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelInjestor; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; + +public class RelationshipGremlinQueryTest { + + private ModelInjestor injestor = ModelInjestor.getInstance(); + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8), + false); + private final Version version = Version.v8; + private DynamicJAXBContext context = injestor.getContextForVersion(version); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + + /** + * Parent query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + + String content = + "{" + + "\"related-to\" : \"pserver\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal to normal query", + expected, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be pserver", + "pserver", + query.getResultType()); + + } + + /** + * Child query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"lag-interface\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = ".has('hostname', 'key1').has('aai-node-type', 'pserver').in('tosca.relationships.BindsTo').has('aai-node-type', 'lag-interface')" + + ".has('interface-name', 'key2')"; + String parentExpected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be for node", + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be for parent", + parentExpected, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be lag-interface", + "lag-interface", + query.getResultType()); + } + + /** + * Naming exceptions. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vce.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"port-group.interface-id\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," + + "\"relationship-value\" : \"655\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')" + + ".has('cvlan-tag', 655)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + + } + + /** + * Scrambled relationship. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void scrambledRelationship() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," + + "\"relationship-value\" : \"key5\"" + + "},{" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"l-interface.interface-name\"," + + "\"relationship-value\" : \"key3\"" + + "},{" + + "\"relationship-key\" : \"vlan.vlan-interface\"," + + "\"relationship-value\" : \"key4\"" + + "},{" + + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}]" + + "}"; + scrambledRelationshipSpec(content); + } + + /** + * Reversed relationship. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void reversedRelationship() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," + + "\"relationship-value\" : \"key5\"" + + "},{" + + "\"relationship-key\" : \"vlan.vlan-interface\"," + + "\"relationship-value\" : \"key4\"" + + "},{" + + "\"relationship-key\" : \"l-interface.interface-name\"," + + "\"relationship-value\" : \"key3\"" + + "},{" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}]" + + "}"; + scrambledRelationshipSpec(content); + } + + /** + * Ordered ambiguous relationship. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void orderedAmbiguousRelationship() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "},{" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"l-interface.interface-name\"," + + "\"relationship-value\" : \"key3\"" + + "},{" + + "\"relationship-key\" : \"vlan.vlan-interface\"," + + "\"relationship-value\" : \"key4\"" + + "},{" + + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," + + "\"relationship-value\" : \"key5\"" + + "}]" + + "}"; + scrambledRelationshipSpec(content); + } + + /** + * Scrambled relationship spec. + * + * @param content the content + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + public void scrambledRelationshipSpec(String content) throws JAXBException, UnsupportedEncodingException, AAIException { + + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'generic-vnf')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'lag-interface')" + + ".has('interface-name', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'l-interface')" + + ".has('interface-name', 'key3').out('tosca.relationships.LinksTo').has('aai-node-type', 'vlan')" + + ".has('vlan-interface', 'key4').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'l3-interface-ipv4-address-list')" + + ".has('l3-interface-ipv4-address', 'key5')"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'generic-vnf')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'lag-interface')" + + ".has('interface-name', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'l-interface')" + + ".has('interface-name', 'key3').out('tosca.relationships.LinksTo').has('aai-node-type', 'vlan')" + + ".has('vlan-interface', 'key4')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for vlan", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be l3-interface-ipv4-address-list", + "l3-interface-ipv4-address-list", + query.getResultType()); + + } + + /** + * Short circuit. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void shortCircuit() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"related-link\" : \"http://mock-system-name.com:8443/aai/v6/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vce.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"port-group.interface-id\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," + + "\"relationship-value\" : \"655\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')" + + ".has('cvlan-tag', 655)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + + } + + @Test + public void shorterCircuit() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"related-link\" : \"file:///network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655\"" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')" + + ".has('cvlan-tag', 655)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'port-group')" + + ".has('interface-id', 'key2')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + + } + + /** + * Double key. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void doubleKey() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"ctag-pool\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"complex.physical-location-id\"," + + "\"relationship-value\" : \"key1\"" + + " }, { " + + "\"relationship-key\" : \"ctag-pool.target-pe\"," + + " \"relationship-value\" : \"key2\"" + + " },{" + + "\"relationship-key\" : \"ctag-pool.availability-zone-name\"," + + "\"relationship-value\" : \"key3\"" + + "}]" + + "}"; + + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'ctag-pool')" + + ".has('target-pe', 'key2')" + + ".has('availability-zone-name', 'key3')"; + String expectedParent = + ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')"; + + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be ctag-pool", + "ctag-pool", + query.getResultType()); + + } + + /** + * Abstract type. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void abstractType() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"vnf\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + " }]" + + "}"; + + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('vnf-id', 'key1')" + + ".has('aai-node-type', P.within('vce','vpe','generic-vnf'))"; + + String expectedParent = + ".has('vnf-id', 'key1')" + + ".has('aai-node-type', P.within('vce','vpe','generic-vnf'))"; + + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be vnf", + "vnf", + query.getResultType()); + + } + + /** + * Invalid node name. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void invalidNodeName() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "},{" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"l-infeaterface.interface-name\"," + + "\"relationship-value\" : \"key3\"" + + "},{" + + "\"relationship-key\" : \"vlan.vlan-interface\"," + + "\"relationship-value\" : \"key4\"" + + "},{" + + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," + + "\"relationship-value\" : \"key5\"" + + "}]" + + "}"; + thrown.expect(AAIException.class); + thrown.expectMessage(containsString("invalid object name")); + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + } + + /** + * Invalid property name. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void invalidPropertyName() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"l3-interface-ipv4-address-list\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"generic-vnf.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "},{" + + "\"relationship-key\" : \"lag-interface.intfdaferface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"l-interface.interface-name\"," + + "\"relationship-value\" : \"key3\"" + + "},{" + + "\"relationship-key\" : \"vlan.vlan-interface\"," + + "\"relationship-value\" : \"key4\"" + + "},{" + + "\"relationship-key\" : \"l3-interface-ipv4-address-list.l3-interface-ipv4-address\"," + + "\"relationship-value\" : \"key5\"" + + "}]" + + "}"; + thrown.expect(AAIException.class); + thrown.expectMessage(containsString("invalid property name")); + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + } +} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/query/RelationshipQueryTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/query/RelationshipQueryTest.java new file mode 100644 index 00000000..18fc16d0 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/parsers/query/RelationshipQueryTest.java @@ -0,0 +1,282 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.parsers.query; + +import static org.junit.Assert.assertEquals; + +import java.io.StringReader; +import java.io.UnsupportedEncodingException; + +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; + +import org.eclipse.persistence.dynamic.DynamicEntity; +import org.eclipse.persistence.jaxb.UnmarshallerProperties; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.BeforeClass; +import org.junit.Test; + +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Introspector; +import org.openecomp.aai.introspection.IntrospectorFactory; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelInjestor; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; + +public class RelationshipQueryTest { + private ModelInjestor injestor = ModelInjestor.getInstance(); + + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_TRAVERSAL, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8), + false); + private final Version version = Version.v8; + private DynamicJAXBContext context = injestor.getContextForVersion(version); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + + /** + * Parent query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + + String content = + "{" + + "\"related-to\" : \"pserver\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal to normal query", + expected, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be pserver", + "pserver", + query.getResultType()); + + } + + /** + * Child query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"lag-interface\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String expected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver').in('tosca.relationships.BindsTo').has('aai-node-type', 'lag-interface')" + + ".has('interface-name', 'key2')"; + String parentExpected = + ".has('hostname', 'key1').has('aai-node-type', 'pserver')"; + assertEquals( + "gremlin query should be for node", + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be for parent", + parentExpected, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be lag-interface", + "lag-interface", + query.getResultType()); + } + + /** + * Naming exceptions. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vce.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"port-group.interface-id\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," + + "\"relationship-value\" : \"655\"" + + "}]" + + "}"; + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String expected = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce').in('org.onap.relationships.inventory.BelongsTo')" + + ".has('aai-node-type', 'port-group').has('interface-id', 'key2').in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'cvlan-tag')" + + ".has('cvlan-tag', 655)"; + String expectedParent = + ".has('vnf-id', 'key1').has('aai-node-type', 'vce').in('org.onap.relationships.inventory.BelongsTo')" + + ".has('aai-node-type', 'port-group').has('interface-id', 'key2')"; + + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be cvlan-tag", + "cvlan-tag", + query.getResultType()); + + } + + /** + * Double key. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void doubleKey() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"ctag-pool\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"complex.physical-location-id\"," + + "\"relationship-value\" : \"key1\"" + + " }, { " + + "\"relationship-key\" : \"ctag-pool.target-pe\"," + + " \"relationship-value\" : \"key2\"" + + " },{" + + "\"relationship-key\" : \"ctag-pool.availability-zone-name\"," + + "\"relationship-value\" : \"key3\"" + + "}]" + + "}"; + + + Unmarshaller unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String expected = + ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')" + + ".in('org.onap.relationships.inventory.BelongsTo').has('aai-node-type', 'ctag-pool')" + + ".has('target-pe', 'key2')" + + ".has('availability-zone-name', 'key3')"; + String expectedParent = + ".has('physical-location-id', 'key1').has('aai-node-type', 'complex')"; + + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be equal the query for port group", + expectedParent, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "result type should be ctag-pool", + "ctag-pool", + query.getResultType()); + + } + +} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryTest.java new file mode 100644 index 00000000..fd05dede --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/parsers/query/UniqueRelationshipQueryTest.java @@ -0,0 +1,305 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.parsers.query; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.eclipse.persistence.dynamic.DynamicEntity; +import org.eclipse.persistence.jaxb.UnmarshallerProperties; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.Before; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.*; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; + +import javax.xml.bind.JAXBException; +import javax.xml.bind.Unmarshaller; +import javax.xml.transform.stream.StreamSource; +import java.io.StringReader; +import java.io.UnsupportedEncodingException; + +import static org.junit.Assert.assertEquals; + +@Ignore +public class UniqueRelationshipQueryTest { + private ModelInjestor injestor = ModelInjestor.getInstance(); + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_UNIQUE, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8), + false); + private final Version version = Version.v8; + private DynamicJAXBContext context = injestor.getContextForVersion(version); + private Unmarshaller unmarshaller = null; + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + + /** + * Setup. + * + * @throws JAXBException the JAXB exception + */ + @Before + public void setup() throws JAXBException { + unmarshaller = context.createUnmarshaller(); + unmarshaller.setProperty(UnmarshallerProperties.MEDIA_TYPE, "application/json"); + unmarshaller.setProperty(UnmarshallerProperties.JSON_INCLUDE_ROOT, false); + unmarshaller.setProperty(UnmarshallerProperties.JSON_WRAPPER_AS_ARRAY_NAME, true); + } + + /** + * Parent query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + + String content = + "{" + + "\"related-to\" : \"pserver\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}]" + + "}"; + + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String key = "pserver/key1"; + GraphTraversal<Vertex, Vertex> expected = + __.<Vertex>start().has("aai-unique-key", key); + String resultType = "pserver"; + String containerType = ""; + + testSet(query, expected, expected, resultType, containerType); + + } + + /** + * Child query. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void childQuery() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"lag-interface\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"pserver.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"lag-interface.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "}]" + + "}"; + + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String key = "pserver/key1/lag-interface/key2"; + GraphTraversal<Vertex, Vertex> expected = + __.<Vertex>start().has("aai-unique-key", key); + GraphTraversal<Vertex, Vertex> parentExpected = + __.<Vertex>start().has("aai-unique-key", "pserver/key1"); + String resultType = "lag-interface"; + String containerType = ""; + + testSet(query, expected, parentExpected, resultType, containerType); + } + + /** + * Naming exceptions. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void namingExceptions() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vce.vnf-id\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"port-group.interface-id\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"cvlan-tag.cvlan-tag\"," + + "\"relationship-value\" : \"655\"" + + "}]" + + "}"; + + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String key = "vce/key1/port-group/key2/cvlan-tag/655"; + GraphTraversal<Vertex, Vertex> expected = + __.<Vertex>start().has("aai-unique-key", key); + GraphTraversal<Vertex, Vertex> parentExpected = + __.<Vertex>start().has("aai-unique-key", "vce/key1/port-group/key2"); + String resultType = "cvlan-tag"; + String containerType = ""; + + testSet(query, expected, parentExpected, resultType, containerType); + + } + + /** + * Double key. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void doubleKey() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"service-capability\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"service-capability.service-type\"," + + "\"relationship-value\" : \"key1\"" + + " }, { " + + "\"relationship-key\" : \"service-capability.vnf-type\"," + + " \"relationship-value\" : \"key2\"" + + " }]" + + "}"; + + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + + String key = "service-capability/key1/key2"; + GraphTraversal<Vertex, Vertex> expected = + __.<Vertex>start().has("aai-unique-key", key); + GraphTraversal<Vertex, Vertex> parentExpected = + __.<Vertex>start().has("aai-unique-key", "service-capability/key1/key2"); + String resultType = "service-capability"; + String containerType = ""; + + testSet(query, expected, parentExpected, resultType, containerType); + + } + + /** + * Short circuit. + * + * @throws JAXBException the JAXB exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void shortCircuit() throws JAXBException, UnsupportedEncodingException, AAIException { + String content = + "{" + + "\"related-to\" : \"cvlan-tag\"," + + "\"related-link\" : \"http://mock-system-name.com:8443/aai/v6/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655\"," + + "\"relationship-data\" : [{" + + "\"relationship-key\" : \"vce.hostname\"," + + "\"relationship-value\" : \"key1\"" + + "}, {" + + "\"relationship-key\" : \"port-group.interface-name\"," + + "\"relationship-value\" : \"key2\"" + + "},{" + + "\"relationship-key\" : \"cvlan-tag.-name\"," + + "\"relationship-value\" : \"655\"" + + "}]" + + "}"; + + Object obj = context.newDynamicEntity("Relationship"); + + DynamicEntity entity = (DynamicEntity)unmarshaller.unmarshal(new StreamSource(new StringReader(content)), obj.getClass()).getValue(); + + Introspector wrappedObj = IntrospectorFactory.newInstance(ModelType.MOXY, entity); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromRelationship(wrappedObj); + String key = "vce/key1/port-group/key2/cvlan-tag/655"; + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", key); + GraphTraversal<Vertex, Vertex> parentExpected = __.<Vertex>start().has("aai-unique-key", "vce/key1/port-group/key2"); + String resultType = "cvlan-tag"; + String containerType = ""; + + testSet(query, expected, parentExpected, resultType, containerType); + + } + + /** + * Test set. + * + * @param query the query + * @param expected the expected + * @param parentExpected the parent expected + * @param resultType the result type + * @param containerType the container type + */ + public void testSet(QueryParser query, GraphTraversal<Vertex, Vertex> expected, GraphTraversal<Vertex, Vertex> parentExpected, String resultType, String containerType) { + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be " + parentExpected, + parentExpected, + query.getParentQueryBuilder().getParentQuery()); + assertEquals( + "result type should be " + resultType, + resultType, + query.getResultType()); + assertEquals( + "container type should be " + containerType, + containerType, + query.getContainerType()); + } +} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/query/UniqueURIQueryTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/query/UniqueURIQueryTest.java new file mode 100644 index 00000000..534386d0 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/parsers/query/UniqueURIQueryTest.java @@ -0,0 +1,205 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.parsers.query; + +import static org.junit.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import javax.ws.rs.core.UriBuilder; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext; +import org.junit.BeforeClass; +import org.junit.Ignore; +import org.junit.Test; + +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelInjestor; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; + +@Ignore +public class UniqueURIQueryTest { + private ModelInjestor injestor = ModelInjestor.getInstance(); + private TransactionalGraphEngine dbEngine = + new TitanDBEngine(QueryStyle.GREMLIN_UNIQUE, + LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8), + false); + private final Version version = Version.v8; + private DynamicJAXBContext context = injestor.getContextForVersion(version); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "."); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + + /** + * Parent query. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1").build(); + String key = "complex/key1"; + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", key); + String parentResultType = ""; + String resultType = "complex"; + String containerType = ""; + + testSet(query, expected, expected, parentResultType, resultType, containerType); + + } + + /** + * Parent plural query. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void parentPluralQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-node-type", "complex"); + String parentResultType = ""; + String resultType = "complex"; + String containerType = "complexes"; + + testSet(query, expected, expected, parentResultType, resultType, containerType); + + } + + /** + * Child query. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void childQuery() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + String parentKey = "complex/key1"; + String key = parentKey + "/ctag-pool/key2/key3"; + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", key); + GraphTraversal<Vertex, Vertex> parentExpected = __.<Vertex>start().has("aai-unique-key", parentKey); + String parentResultType = "complex"; + String resultType = "ctag-pool"; + String containerType = ""; + + testSet(query, expected, parentExpected, parentResultType, resultType, containerType); + + } + + /** + * Naming exceptions. + * + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void namingExceptions() throws UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + String parentKey = "vce/key1/port-group/key2"; + String key = parentKey + "/cvlan-tag/655"; + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", key); + GraphTraversal<Vertex, Vertex> parentExpected = __.<Vertex>start().has("aai-unique-key", parentKey); + String parentResultType = "port-group"; + String resultType = "cvlan-tag"; + String containerType = ""; + + testSet(query, expected, parentExpected, parentResultType, resultType, containerType); + + } + + /** + * Gets the all. + * + * @return the all + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void getAll() throws UnsupportedEncodingException, AAIException { + String parentURI = "network/vces/vce/key1/port-groups/port-group/key2"; + String parentKey = "vce/key1/port-group/key2"; + URI uri = UriBuilder.fromPath(parentURI + "/cvlan-tags").build(); + QueryParser query = dbEngine.getQueryBuilder().createQueryFromURI(uri); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("aai-unique-key", parentKey).out("hasCTag").has("aai-node-type", "cvlan-tag"); + GraphTraversal<Vertex, Vertex> parentExpected = __.<Vertex>start().has("aai-unique-key",parentKey); + String parentResultType = "port-group"; + String resultType = "cvlan-tag"; + String containerType = "cvlan-tags"; + + testSet(query, expected, parentExpected, parentResultType, resultType, containerType); + + } + + /** + * Test set. + * + * @param query the query + * @param expected the expected + * @param parentExpected the parent expected + * @param parentResultType the parent result type + * @param resultType the result type + * @param containerType the container type + */ + public void testSet(QueryParser query, GraphTraversal<Vertex, Vertex> expected, GraphTraversal<Vertex, Vertex> parentExpected, String parentResultType, String resultType, String containerType) { + assertEquals( + "gremlin query should be " + expected, + expected, + query.getQueryBuilder().getQuery()); + assertEquals( + "parent gremlin query should be " + parentExpected, + parentExpected, + query.getQueryBuilder().getParentQuery().getQuery()); + assertEquals( + "parent result type should be " + parentResultType, + parentResultType, + query.getParentResultType()); + assertEquals( + "result type should be " + resultType, + resultType, + query.getResultType()); + assertEquals( + "container type should be " + containerType, + containerType, + query.getContainerType()); + } +} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/relationship/RelationshipToURITest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/relationship/RelationshipToURITest.java new file mode 100644 index 00000000..2be7887b --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/parsers/relationship/RelationshipToURITest.java @@ -0,0 +1,229 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.parsers.relationship; + +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; + +import java.io.FileInputStream; +import java.io.IOException; +import java.net.URI; +import java.net.URISyntaxException; + +import org.apache.commons.io.IOUtils; +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Introspector; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.parsers.exceptions.AAIIdentityMapParseException; +import org.openecomp.aai.parsers.exceptions.AmbiguousMapAAIException; +import org.openecomp.aai.serialization.queryformats.QueryFormatTestHelper; +import org.openecomp.aai.util.AAIConstants; + +public class RelationshipToURITest { + + + + private final ModelType modelType = ModelType.MOXY; + private final Version version10 = Version.v10; + private final Version version9 = Version.v9; + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + @BeforeClass + public static void setup() throws NoSuchFieldException, SecurityException, Exception { + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/org/openecomp/aai/introspection/"); + + } + + @Test + public void onlyLink() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("only-related-link.json")); + URI expected = new URI("/aai/v10/network/test-objects/test-object/key1"); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected.getPath(), uri.getPath()); + } + + @Test + public void onlyData() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("only-relationship-data.json")); + URI expected = new URI("/network/test-objects/test-object/key1"); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected, uri); + } + + @Test + public void failV10() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("both-failv10-successv9.json")); + URI expected = new URI("/aai/v10/network/test-objects/test-object/key1"); + + thrown.expect(AAIIdentityMapParseException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + + URI uri = parse.getUri(); + + } + + @Test + public void successV9() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version9); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("both-failv10-successv9.json")); + URI expected = new URI("/network/test-objects/test-object/key2"); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected, uri); + + + } + + @Test + public void failV9() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version9); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("both-successv10-failv9.json")); + URI expected = new URI("/network/test-objects/test-object/key1"); + + thrown.expect(AAIIdentityMapParseException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + + URI uri = parse.getUri(); + + } + + @Test + public void successV10() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("both-successv10-failv9.json")); + URI expected = new URI("/aai/v10/network/test-objects/test-object/key1"); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected, uri); + + + } + + @Test + public void ambiguousRelationship() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("ambiguous-relationship.json")); + URI expected = new URI("/aai/v10/network/test-objects/test-object/key1"); + + thrown.expect(AmbiguousMapAAIException.class); + thrown.expect(hasProperty("code", is("AAI_6146"))); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected, uri); + + + } + + @Test + public void moreItemsThanRequired() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("too-many-items-relationship.json")); + URI expected = new URI("/network/generic-vnfs/generic-vnf/key1/l-interfaces/l-interface/key2"); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected.toString(), uri.toString()); + + } + + @Test + public void twoTopLevelNodes() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("two-top-level-relationship.json")); + URI expected = new URI("/network/generic-vnfs/generic-vnf/key1/l-interfaces/l-interface/key2"); + + thrown.expect(AmbiguousMapAAIException.class); + thrown.expect(hasProperty("code", is("AAI_6146"))); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected, uri); + + } + + @Test + public void topLevelWithTwoKeys() throws AAIException, URISyntaxException, IOException { + Loader loader = LoaderFactory.createLoaderForVersion(modelType, version10); + Introspector obj = loader.unmarshal("relationship", this.getJsonString("top-level-two-keys-relationship.json")); + URI expected = new URI("/cloud-infrastructure/cloud-regions/cloud-region/key1/key2/availability-zones/availability-zone/key3"); + + RelationshipToURI parse = new RelationshipToURI(loader, obj); + + URI uri = parse.getUri(); + + assertEquals("related-link is equal", expected.toString(), uri.toString()); + + } + + + private String getJsonString(String filename) throws IOException { + + + FileInputStream is = new FileInputStream("src/test/resources/org/openecomp/aai/parsers/relationship/" + filename); + String s = IOUtils.toString(is, "UTF-8"); + IOUtils.closeQuietly(is); + + return s; + } +} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIParserTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIParserTest.java new file mode 100644 index 00000000..b413c9d1 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIParserTest.java @@ -0,0 +1,113 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.parsers.uri; + +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; + +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import javax.ws.rs.core.UriBuilder; +import javax.xml.bind.JAXBException; + +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; + + +public class URIParserTest { + + private Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + /** + * Invalid path. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void invalidPath() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/network/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3001"))); + + new URIToDBKey(loader, uri); + } + + /** + * Invalid path no name space. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void invalidPathNoNameSpace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + + new URIToDBKey(loader, uri); + } + + /** + * Invalid path partial. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void invalidPathPartial() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + + new URIToDBKey(loader, uri); + } +} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToExtensionInformationTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToExtensionInformationTest.java new file mode 100644 index 00000000..5c82e452 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToExtensionInformationTest.java @@ -0,0 +1,147 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.parsers.uri; + +import static org.junit.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; +import java.net.URI; + +import javax.ws.rs.core.UriBuilder; +import javax.xml.bind.JAXBException; + +import org.junit.BeforeClass; +import org.junit.Test; + +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.restcore.HttpMethod; + + +public class URIToExtensionInformationTest { + + private Loader v6Loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8); + private Loader v7Loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v8); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + /** + * Vservers V 7. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void vserversV7() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + v7Loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/key1/vservers/vserver/key2").build(); + URIToExtensionInformation parse = new URIToExtensionInformation(v7Loader, uri); + + String namespace = "cloudInfrastructure"; + String preMethodName = "DynamicAddCloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserverPreProc"; + String postMethodName = "DynamicAddCloudInfrastructureCloudRegionsCloudRegionTenantsTenantVserversVserverPostProc"; + String topLevel = "CloudRegion"; + testSpec(parse, HttpMethod.PUT, namespace, preMethodName, postMethodName, topLevel); + + } + + /** + * New vce V 6. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void newVceV6() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + v6Loader.getVersion() + "/network/newvces/newvce/key1").build(); + URIToExtensionInformation parse = new URIToExtensionInformation(v6Loader, uri); + + String namespace = "network"; + String preMethodName = "DynamicDelNetworkNewvcesNewvcePreProc"; + String postMethodName = "DynamicDelNetworkNewvcesNewvcePostProc"; + String topLevel = "Newvce"; + testSpec(parse, HttpMethod.DELETE, namespace, preMethodName, postMethodName, topLevel); + + } + + /** + * New vce V 7. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void newVceV7() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + v7Loader.getVersion() + "/network/newvces/newvce/key1").build(); + URIToExtensionInformation parse = new URIToExtensionInformation(v7Loader, uri); + + String namespace = "network"; + String preMethodName = "DynamicDelNetworkNewvcesNewvcePreProc"; + String postMethodName = "DynamicDelNetworkNewvcesNewvcePostProc"; + String topLevel = "Newvce"; + testSpec(parse, HttpMethod.DELETE, namespace, preMethodName, postMethodName, topLevel); + + } + + /** + * Test spec. + * + * @param info the info + * @param httpMethod the http method + * @param namespace the namespace + * @param preMethodName the pre method name + * @param postMethodName the post method name + * @param topLevel the top level + */ + private void testSpec(URIToExtensionInformation info, HttpMethod httpMethod, String namespace, String preMethodName, String postMethodName, String topLevel) { + + + String namespaceResult = info.getNamespace(); + String methodNameResult = info.getMethodName(httpMethod, true); + + assertEquals("namespace", namespace, namespaceResult); + assertEquals("preprocess method name", preMethodName, methodNameResult); + methodNameResult = info.getMethodName(httpMethod, false); + + assertEquals("postprocess method name", postMethodName, methodNameResult); + + String topLevelResult = info.getTopObject(); + + assertEquals("topLevel", topLevel, topLevelResult); + } + + +} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToObjectTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToObjectTest.java new file mode 100644 index 00000000..5313aeca --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToObjectTest.java @@ -0,0 +1,260 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.parsers.uri; + +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.util.HashMap; + +import javax.ws.rs.core.UriBuilder; +import javax.xml.bind.JAXBException; + +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import org.openecomp.aai.db.props.AAIProperties; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Introspector; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.introspection.exceptions.AAIUnknownObjectException; + + + +public class URIToObjectTest { + + private Version version = Version.v8; + private Version currentVersion = AAIProperties.LATEST; + private Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, version); + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + + /** + * Uri. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void uri() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getTopEntity(); + String expected = "{\"cloud-owner\":\"mycloudowner\",\"cloud-region-id\":\"mycloudregionid\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}"; + String topEntity = "cloud-region"; + String entity = "l-interface"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + + } + + /** + * Uri no version. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIUnknownObjectException + */ + @Test + public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, AAIUnknownObjectException { + URI uri = UriBuilder.fromPath("/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + HashMap<String, Introspector> relatedObjects = new HashMap<>(); + Introspector tenantObj = this.loader.introspectorFromName("tenant"); + tenantObj.setValue("tenant-id", "key1"); + tenantObj.setValue("tenant-name", "name1"); + relatedObjects.put(tenantObj.getObjectId(), tenantObj); + Introspector vserverObj = this.loader.introspectorFromName("vserver"); + vserverObj.setValue("vserver-id", "key2"); + vserverObj.setValue("vserver-name", "name2"); + relatedObjects.put(vserverObj.getObjectId(), vserverObj); + + URIToObject parse = new URIToObject(loader, uri, relatedObjects); + Introspector result = parse.getTopEntity(); + String expected = "{\"cloud-owner\":\"mycloudowner\",\"cloud-region-id\":\"mycloudregionid\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"tenant-name\":\"name1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"vserver-name\":\"name2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}"; + String topEntity = "cloud-region"; + String entity = "l-interface"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + + + } + + + /** + * Bad URI. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void badURI() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + + new URIToObject(loader, uri); + } + + /** + * Starts with valid namespace. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void startsWithValidNamespace() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/cloud-infrastructure/cloud-regions/cloud-region/mycloudowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getTopEntity(); + String expected = "{\"cloud-owner\":\"mycloudowner\",\"cloud-region-id\":\"mycloudregionid\",\"tenants\":{\"tenant\":[{\"tenant-id\":\"key1\",\"vservers\":{\"vserver\":[{\"vserver-id\":\"key2\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"key3\"}]}}]}}]}}"; + String topEntity = "cloud-region"; + String entity = "l-interface"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + } + + /** + * Single top level. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void singleTopLevel() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/network/generic-vnfs/generic-vnf/key1").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getTopEntity(); + String expected = "{\"vnf-id\":\"key1\"}"; + + String topEntity = "generic-vnf"; + String entity = "generic-vnf"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + + } + + /** + * Naming exceptions. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void namingExceptions() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/655").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getTopEntity(); + String expected = "{\"vnf-id\":\"key1\",\"port-groups\":{\"port-group\":[{\"interface-id\":\"key2\",\"cvlan-tags\":{\"cvlan-tag-entry\":[{\"cvlan-tag\":655}]}}]}}"; + String topEntity = "vce"; + String entity = "cvlan-tag"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + + } + + /** + * No list object. + * + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws AAIException the AAI exception + */ + @Test + public void noListObject() throws IllegalArgumentException, UnsupportedEncodingException, AAIException { + URI uri = UriBuilder.fromPath("/aai/v6/network/vpls-pes/vpls-pe/0e6189fd-9257-49b9-a3be-d7ba980ccfc9/lag-interfaces/lag-interface/8ae5aa76-d597-4382-b219-04f266fe5e37/l-interfaces/l-interface/9e141d03-467b-437f-b4eb-b3133ec1e205/l3-interface-ipv4-address-list/8f19f0ea-a81f-488e-8d5c-9b7b53696c11").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getTopEntity(); + String topEntity = "vpls-pe"; + String entity = "l3-interface-ipv4-address-list"; + String expected = "{\"equipment-name\":\"0e6189fd-9257-49b9-a3be-d7ba980ccfc9\",\"lag-interfaces\":{\"lag-interface\":[{\"interface-name\":\"8ae5aa76-d597-4382-b219-04f266fe5e37\",\"l-interfaces\":{\"l-interface\":[{\"interface-name\":\"9e141d03-467b-437f-b4eb-b3133ec1e205\",\"l3-interface-ipv4-address-list\":[{\"l3-interface-ipv4-address\":\"8f19f0ea-a81f-488e-8d5c-9b7b53696c11\"}]}]}}]}}"; + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + + } + + @Test + public void relativePath() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("./l-interfaces/l-interface/key1").build(); + URIToObject parse = new URIToObject(loader, uri); + Introspector result = parse.getEntity(); + String expected = "{\"interface-name\":\"key1\"}"; + + String topEntity = "l-interface"; + String entity = "l-interface"; + + testSet(result.marshal(false), parse, expected, topEntity, entity, version); + + } + + /** + * Test set. + * + * @param json the json + * @param parse the parse + * @param expected the expected + * @param topEntity the top entity + * @param entity the entity + * @param version the version + */ + public void testSet(String json, URIToObject parse, String expected, String topEntity, String entity, Version version) { + assertEquals("blah", expected, json); + + assertEquals("top entity", topEntity, parse.getTopEntityName()); + + assertEquals("entity", entity, parse.getEntityName()); + + assertEquals("entity object", entity, parse.getEntity().getDbName()); + + assertEquals("parent list object", 1, parse.getParentList().size()); + + assertEquals("object version", version, parse.getObjectVersion()); + } +} diff --git a/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToRelationshipObjectTest.java b/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToRelationshipObjectTest.java new file mode 100644 index 00000000..8ecc5459 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/parsers/uri/URIToRelationshipObjectTest.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.parsers.uri; + +import static org.hamcrest.Matchers.hasProperty; +import static org.hamcrest.Matchers.is; +import static org.junit.Assert.assertTrue; + +import java.io.UnsupportedEncodingException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; + +import javax.ws.rs.core.UriBuilder; +import javax.xml.bind.JAXBException; + +import org.junit.BeforeClass; +import org.junit.Rule; +import org.junit.Test; +import org.junit.rules.ExpectedException; + +import org.openecomp.aai.db.props.AAIProperties; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Introspector; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; + + +public class URIToRelationshipObjectTest { + + private Version latest = AAIProperties.LATEST; + private Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, latest); + + @Rule + public ExpectedException thrown = ExpectedException.none(); + + /** + * Configure. + */ + @BeforeClass + public static void configure() { + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + } + + /** + * Uri. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws URISyntaxException + * @throws MalformedURLException the malformed URL exception + */ + @Test + public void uri() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); + Introspector result = parse.getResult(); + String expected = "\\{\"related-to\":\"l-interface\",\"related-link\":\".*?:8443/aai/" + latest + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3\",\"relationship-data\":\\[\\{\"relationship-key\":\"cloud-region.cloud-owner\",\"relationship-value\":\"mycloudregionowner\"\\},\\{\"relationship-key\":\"cloud-region.cloud-region-id\",\"relationship-value\":\"mycloudregionid\"\\},\\{\"relationship-key\":\"tenant.tenant-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"vserver.vserver-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"l-interface.interface-name\",\"relationship-value\":\"key3\"\\}\\]\\}"; + assertTrue("blah", result.marshal(false).matches(expected)); + + } + + /** + * Uri no version. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws URISyntaxException + * @throws MalformedURLException the malformed URL exception + */ + @Test + public void uriNoVersion() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException { + URI uri = UriBuilder.fromPath("/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3").build(); + URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); + Introspector result = parse.getResult(); + String expected = "\\{\"related-to\":\"l-interface\",\"related-link\":\".*?:8443/aai/" + latest + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interfaces/l-interface/key3\",\"relationship-data\":\\[\\{\"relationship-key\":\"cloud-region.cloud-owner\",\"relationship-value\":\"mycloudregionowner\"\\},\\{\"relationship-key\":\"cloud-region.cloud-region-id\",\"relationship-value\":\"mycloudregionid\"\\},\\{\"relationship-key\":\"tenant.tenant-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"vserver.vserver-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"l-interface.interface-name\",\"relationship-value\":\"key3\"\\}\\]\\}"; + assertTrue("blah", result.marshal(false).matches(expected)); + + + } + + /** + * Double key relationship. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws URISyntaxException + * @throws MalformedURLException the malformed URL exception + */ + @Test + public void doubleKeyRelationship() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException { + URI uri = UriBuilder.fromPath("/aai/" + latest + "/cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3/").build(); + URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); + Introspector result = parse.getResult(); + String expected = "\\{\"related-to\":\"ctag-pool\",\"related-link\":\".*?:8443/aai/" + latest + "/cloud-infrastructure/complexes/complex/key1/ctag-pools/ctag-pool/key2/key3\",\"relationship-data\":\\[\\{\"relationship-key\":\"complex.physical-location-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"ctag-pool.target-pe\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"ctag-pool.availability-zone-name\",\"relationship-value\":\"key3\"\\}\\]\\}"; + assertTrue("blah", result.marshal(false).matches(expected)); + + } + + /** + * Uri with non string key. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + * @throws URISyntaxException + * @throws MalformedURLException the malformed URL exception + */ + @Test + public void uriWithNonStringKey() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException, URISyntaxException { + URI uri = UriBuilder.fromPath("/aai/" + latest + "/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/144").build(); + URIToRelationshipObject parse = new URIToRelationshipObject(loader, uri); + Introspector result = parse.getResult(); + String expected = "\\{\"related-to\":\"cvlan-tag\",\"related-link\":\".*?:8443/aai/" + latest + "/network/vces/vce/key1/port-groups/port-group/key2/cvlan-tags/cvlan-tag/144\",\"relationship-data\":\\[\\{\"relationship-key\":\"vce.vnf-id\",\"relationship-value\":\"key1\"\\},\\{\"relationship-key\":\"port-group.interface-id\",\"relationship-value\":\"key2\"\\},\\{\"relationship-key\":\"cvlan-tag.cvlan-tag\",\"relationship-value\":\"144\"\\}\\]\\}"; + assertTrue("blah", result.marshal(false).matches(expected)); + } + /** + * Bad URI. + * + * @throws JAXBException the JAXB exception + * @throws AAIException the AAI exception + * @throws IllegalArgumentException the illegal argument exception + * @throws UnsupportedEncodingException the unsupported encoding exception + */ + @Test + public void badURI() throws JAXBException, AAIException, IllegalArgumentException, UnsupportedEncodingException { + URI uri = UriBuilder.fromPath("/aai/" + loader.getVersion() + "/cloud-infrastructure/cloud-regions/cloud-region/mycloudregionowner/mycloudregionid/tenants/tenant/key1/vservers/vserver/key2/l-interadsfaces/l-interface/key3").build(); + + thrown.expect(AAIException.class); + thrown.expect(hasProperty("code", is("AAI_3000"))); + + URIToObject parse = new URIToObject(loader, uri); + + } +} diff --git a/aai-core/src/test/java/org/openecomp/aai/query/builder/TraversalQueryTest.java b/aai-core/src/test/java/org/openecomp/aai/query/builder/TraversalQueryTest.java new file mode 100644 index 00000000..0a2d6541 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/query/builder/TraversalQueryTest.java @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.query.builder; + +import static org.junit.Assert.assertEquals; + +import java.io.UnsupportedEncodingException; +import java.net.URI; +import java.net.URISyntaxException; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.BeforeClass; +import org.junit.Test; +import org.mockito.Mock; + +import org.openecomp.aai.db.props.AAIProperties; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Introspector; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.serialization.queryformats.QueryFormatTestHelper; +import org.openecomp.aai.util.AAIConstants; + +public class TraversalQueryTest { + + public static Loader loader; + @Mock public GraphTraversalSource g; + @BeforeClass + public static void configure() throws NoSuchFieldException, SecurityException, Exception { + + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "src/test/resources/org/openecomp/aai/introspection/"); + loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, AAIProperties.LATEST); + } + + @Test + public void unionQuery() { + TraversalQuery tQ = new TraversalQuery(loader, g); + TraversalQuery tQ2 = new TraversalQuery(loader, g); + TraversalQuery tQ3 = new TraversalQuery(loader, g); + tQ.union( + tQ2.getVerticesByProperty("test1", "value1"), + tQ3.getVerticesByIndexedProperty("test2", "value2")); + + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start() + .union(__.has("test1", "value1"),__.has("test2", "value2")); + + assertEquals("they are equal", expected, tQ.getQuery()); + + } + + @Test + public void traversalClones() throws UnsupportedEncodingException, AAIException, URISyntaxException { + TraversalQuery tQ = new TraversalQuery(loader, g); + Introspector test = loader.introspectorFromName("test-object"); + QueryBuilder builder = tQ.createQueryFromURI(new URI("network/test-objects/test-object/key1")).getQueryBuilder(); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("vnf-id", "key1").has("aai-node-type", "test-object"); + GraphTraversal<Vertex, Vertex> containerExpected = __.<Vertex>start().has("aai-node-type", "test-object"); + + assertEquals("query object", expected.toString(), builder.getQuery().toString()); + assertEquals("container query object", containerExpected.toString(), builder.getContainerQuery().getQuery().toString()); + + } + + @Test + public void nestedTraversalClones() throws UnsupportedEncodingException, AAIException, URISyntaxException { + + TraversalQuery tQ = new TraversalQuery(loader, g); + QueryBuilder builder = tQ.createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1/l-interfaces/l-interface/key2")).getQueryBuilder(); + GraphTraversal<Vertex, Vertex> expected = __.<Vertex>start().has("vnf-id", "key1").has("aai-node-type", "generic-vnf").out("hasLInterface").has(AAIProperties.NODE_TYPE, "l-interface").has("interface-name", "key2"); + GraphTraversal<Vertex, Vertex> containerExpected = __.<Vertex>start().has("vnf-id", "key1").has("aai-node-type", "generic-vnf").out("hasLInterface").has(AAIProperties.NODE_TYPE, "l-interface"); + + assertEquals("query object", expected.toString(), builder.getQuery().toString()); + assertEquals("container query object", containerExpected.toString(), builder.getContainerQuery().getQuery().toString()); + + } + + + +} diff --git a/aai-core/src/test/java/org/openecomp/aai/serialization/db/DbAliasTest.java b/aai-core/src/test/java/org/openecomp/aai/serialization/db/DbAliasTest.java new file mode 100644 index 00000000..3f73b7c7 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/serialization/db/DbAliasTest.java @@ -0,0 +1,138 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.serialization.db; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.spy; +import static org.mockito.Mockito.when; + +import java.io.UnsupportedEncodingException; +import java.lang.reflect.InvocationTargetException; +import java.net.MalformedURLException; +import java.net.URI; +import java.net.URISyntaxException; +import java.util.Map; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.junit.After; +import org.junit.Before; +import org.junit.Test; + +import org.openecomp.aai.dbmap.DBConnectionType; +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.introspection.Introspector; +import org.openecomp.aai.introspection.Loader; +import org.openecomp.aai.introspection.LoaderFactory; +import org.openecomp.aai.introspection.ModelType; +import org.openecomp.aai.introspection.Version; +import org.openecomp.aai.parsers.query.QueryParser; +import org.openecomp.aai.schema.enums.PropertyMetadata; +import org.openecomp.aai.serialization.engines.QueryStyle; +import org.openecomp.aai.serialization.engines.TitanDBEngine; +import org.openecomp.aai.serialization.engines.TransactionalGraphEngine; +import com.thinkaurelius.titan.core.TitanFactory; +import com.thinkaurelius.titan.core.TitanGraph; +import com.thinkaurelius.titan.core.TitanTransaction; + +import java.util.Collections; + +public class DbAliasTest { + + + + private TitanGraph graph; + private final Version version = Version.v9; + private final ModelType introspectorFactoryType = ModelType.MOXY; + private final QueryStyle queryStyle = QueryStyle.TRAVERSAL; + private final DBConnectionType type = DBConnectionType.REALTIME; + private Loader loader; + private TransactionalGraphEngine dbEngine; + @Before + public void setup() throws NoSuchFieldException, SecurityException, Exception { + graph = TitanFactory.build().set("storage.backend","inmemory").open(); + System.setProperty("AJSC_HOME", "./src/test/resources/"); + System.setProperty("BUNDLECONFIG_DIR", "bundleconfig-local"); + loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version); + dbEngine = new TitanDBEngine( + queryStyle, + type, + loader); + } + + @After + public void tearDown() { + graph.tx().rollback(); + graph.close(); + } + + @Test + public void checkOnWrite() throws AAIException, UnsupportedEncodingException, URISyntaxException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, NoSuchMethodException, InterruptedException { + final String property = "persona-model-customization-id"; + String dbPropertyName = property; + TransactionalGraphEngine spy = spy(this.dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + TitanTransaction g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + QueryParser uriQuery = spy.getQueryBuilder().createQueryFromURI(new URI("network/generic-vnfs/generic-vnf/key1")); + Introspector obj = loader.introspectorFromName("generic-vnf"); + Vertex v = g.addVertex(); + Object id = v.id(); + obj.setValue("vnf-id", "key1"); + obj.setValue(property, "hello"); + serializer.serializeToDb(obj, v, uriQuery, "", ""); + g.commit(); + v = graph.traversal().V(id).next(); + Map<PropertyMetadata, String> map = obj.getPropertyMetadata(property); + if (map.containsKey(PropertyMetadata.DB_ALIAS)) { + dbPropertyName = map.get(PropertyMetadata.DB_ALIAS); + } + + assertEquals("dbAlias is ", "model-customization-id", dbPropertyName); + assertEquals("dbAlias property exists", "hello", v.property(dbPropertyName).orElse("")); + assertEquals("model property does not", "missing", v.property(property).orElse("missing")); + + } + + @Test + public void checkOnRead() throws AAIException, UnsupportedEncodingException, URISyntaxException, SecurityException, IllegalAccessException, IllegalArgumentException, InvocationTargetException, InstantiationException, NoSuchMethodException, InterruptedException, MalformedURLException { + final String property = "persona-model-customization-id"; + + TransactionalGraphEngine spy = spy(dbEngine); + TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin()); + Vertex v = graph.traversal().addV("vnf-id", "key1", "model-customization-id", "hello").next(); + graph.tx().commit(); + TitanTransaction g = graph.newTransaction(); + GraphTraversalSource traversal = g.traversal(); + when(spy.asAdmin()).thenReturn(adminSpy); + when(adminSpy.getTraversalSource()).thenReturn(traversal); + DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "AAI_TEST"); + Introspector obj = loader.introspectorFromName("generic-vnf"); + serializer.dbToObject(Collections.singletonList(v), obj, 0, true, "false"); + + assertEquals("dbAlias property exists", "hello", obj.getValue(property)); + + } + +} diff --git a/aai-core/src/test/java/org/openecomp/aai/serialization/db/EdgeRulesTest.java b/aai-core/src/test/java/org/openecomp/aai/serialization/db/EdgeRulesTest.java new file mode 100644 index 00000000..9411e319 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/serialization/db/EdgeRulesTest.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.serialization.db; + +import static org.junit.Assert.assertEquals; + +import java.util.Map; + +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.junit.Test; + +import org.openecomp.aai.exceptions.AAIException; +import org.openecomp.aai.serialization.db.exceptions.NoEdgeRuleFoundException; + +public class EdgeRulesTest { + + + + + @Test + public void verifyOutDirection() throws AAIException, NoEdgeRuleFoundException { + EdgeRules rules = EdgeRules.getInstance(); + EdgeRule rule = rules.getEdgeRule(EdgeType.TREE, "cloud-region", "flavor"); + + assertEquals("out direction", rule.getDirection(), Direction.OUT); + } + + @Test + public void verifyOutFlippedDirection() throws AAIException, NoEdgeRuleFoundException { + EdgeRules rules = EdgeRules.getInstance(); + EdgeRule rule = rules.getEdgeRule(EdgeType.TREE, "flavor", "cloud-region"); + + assertEquals("in direction", rule.getDirection(), Direction.IN); + } + + @Test + public void verifyInDirection() throws AAIException, NoEdgeRuleFoundException { + EdgeRules rules = EdgeRules.getInstance(); + EdgeRule rule = rules.getEdgeRule(EdgeType.COUSIN, "model-ver", "model-element"); + + assertEquals("in direction", rule.getDirection(), Direction.IN); + } + + @Test + public void verifyInFlippedDirection() throws AAIException, NoEdgeRuleFoundException { + EdgeRules rules = EdgeRules.getInstance(); + EdgeRule rule = rules.getEdgeRule(EdgeType.COUSIN, "model-element", "model-ver"); + + assertEquals("out direction", rule.getDirection(), Direction.OUT); + } + @Test + public void verifyMultipleGet() throws AAIException { + EdgeRules rules = EdgeRules.getInstance(); + Map<String, EdgeRule> ruleMap = rules.getEdgeRules("model-element", "model-ver"); + assertEquals("has isA rule", "isA", ruleMap.get("isA").getLabel()); + assertEquals("has startsWith rule", "startsWith", ruleMap.get("startsWith").getLabel()); + } + + @Test + public void verifyMultipleGetSingleRule() throws AAIException { + EdgeRules rules = EdgeRules.getInstance(); + Map<String, EdgeRule> ruleMap = rules.getEdgeRules("availability-zone", "complex"); + assertEquals("has groupsResourcesIn rule", "groupsResourcesIn", ruleMap.get("groupsResourcesIn").getLabel()); + } +} diff --git a/aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/QueryFormatTestHelper.java b/aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/QueryFormatTestHelper.java new file mode 100644 index 00000000..d6a45662 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/serialization/queryformats/QueryFormatTestHelper.java @@ -0,0 +1,76 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.serialization.queryformats; + +import static org.mockito.Matchers.isA; +import static org.mockito.Mockito.when; + +import java.io.IOException; +import java.lang.reflect.Field; +import java.lang.reflect.Modifier; + +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.openecomp.aai.db.props.AAIProperties; +import org.openecomp.aai.serialization.queryformats.exceptions.AAIFormatVertexException; +import org.openecomp.aai.serialization.queryformats.utils.UrlBuilder; + +public class QueryFormatTestHelper { + + + public static final String testResources = "src/test/resources/org/openecomp/aai/serialization/queryformats/"; + public static final String graphsonResources = "src/test/resources/org/openecomp/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-core/src/test/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedVertexTest.java b/aai-core/src/test/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedVertexTest.java new file mode 100644 index 00000000..18fa7db3 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/serialization/tinkerpop/TreeBackedVertexTest.java @@ -0,0 +1,150 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.serialization.tinkerpop; + +import static org.junit.Assert.assertEquals; + +import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource; +import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree; +import org.apache.tinkerpop.gremlin.structure.Direction; +import org.apache.tinkerpop.gremlin.structure.Element; +import org.apache.tinkerpop.gremlin.structure.Graph; +import org.apache.tinkerpop.gremlin.structure.T; +import org.apache.tinkerpop.gremlin.structure.Vertex; +import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph; +import org.junit.BeforeClass; +import org.junit.Test; + +import org.openecomp.aai.serialization.engines.query.GraphTraversalQueryEngine; + +public class TreeBackedVertexTest { + + + private static Graph graph = TinkerGraph.open(); + private static Object startKey = null; + private static Tree<Element> tree = null; + private static Tree<Element> treeDepth1 = null; + private static Tree<Element> treeDepth0NodeOnly = null; + @BeforeClass + public static void configure() { + GraphTraversalSource g = graph.traversal(); + + startKey = g.addV(T.label, "vserver").as("v1").property("test", "hello") + .addV(T.label, "vserver").as("v2") + .addV(T.label, "interface").property("name", "interface 1").as("v7").addInE("hasChild", "v2").property("isParent", true) + .addV(T.label, "pserver").property("name", "pserver 1").as("v4").addOutE("runsOn", "v1").property("isParent", false) + .addV(T.label, "interface").property("name", "interface 2").as("v3").addInE("hasChild", "v1").property("isParent", true) + .addV(T.label, "address").property("name", "address 1").addInE("hasChild", "v3").property("isParent", true) + .addV(T.label, "address").property("name", "address 2").addInE("hasChild", "v3").property("isParent", true) + .addV(T.label, "complex").property("name", "complex 1").addInE("locatedIn", "v4").property("isParent", false) + .addV(T.label, "interface").property("name", "interface 3").addInE("hasChild", "v4").property("isParent", true) + .addV(T.label, "subnet").property("name", "subnet 1").as("v5").addInE("in", "v3").property("isParent", false) + .addV(T.label, "address").property("name", "address 3").as("v6").addInE("hasChild", "v5").property("isParent", true) + .select("v1").next(); + + tree = new GraphTraversalQueryEngine(g).findSubGraph((Vertex)startKey); + treeDepth1 = new GraphTraversalQueryEngine(g).findSubGraph((Vertex)startKey, 1, false); + treeDepth0NodeOnly = new GraphTraversalQueryEngine(g).findSubGraph((Vertex)startKey, 0, true); + } + @Test + public void oneHopViaEdges() { + + //BulkSet set = (BulkSet)result; + TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); + + + assertEquals("locate child", v.edges(Direction.OUT).next().inVertex().property("name").orElse(""), "interface 2"); + assertEquals("locate cousin", v.edges(Direction.IN).next().outVertex().property("name").orElse(""), "pserver 1"); + + + } + + @Test + public void oneHopViaVertices() { + + //BulkSet set = (BulkSet)result; + TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); + + + assertEquals("locate child", "interface 2", v.vertices(Direction.OUT).next().property("name").orElse("")); + assertEquals("locate cousin", "pserver 1", v.vertices(Direction.IN).next().property("name").orElse("")); + + } + + @Test + public void twoHopCousinViaVertices() { + + //BulkSet set = (BulkSet)result; + TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); + + + assertEquals("locate child", "subnet 1", v.vertices(Direction.OUT).next().vertices(Direction.OUT, "in").next().property("name").orElse("")); + + } + + @Test + public void walkVerticesRestrictedDepth() { + + //BulkSet set = (BulkSet)result; + TreeBackedVertex v = new TreeBackedVertex((Vertex)treeDepth1.getObjectsAtDepth(1).iterator().next(), treeDepth1); + + + assertEquals("nothing returned", false, v.vertices(Direction.OUT).next() + .vertices(Direction.OUT, "hasChild").hasNext()); + + } + + @Test + public void walkVertices() { + TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); + assertEquals("locate child", "address 2", v.vertices(Direction.OUT).next() + .vertices(Direction.OUT, "hasChild").next().property("name").orElse("")); + } + + @Test + public void walkEdges() { + TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); + + assertEquals("locate child", "address 2", v.edges(Direction.OUT).next().inVertex() + .edges(Direction.OUT, "hasChild").next().inVertex().property("name").orElse("")); + } + + @Test + public void noEdgesFoudWithLabelVertices() { + TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); + + assertEquals("missing hello label", false , v.vertices(Direction.OUT, "hello").hasNext()); + } + + @Test + public void noEdgesFoudWithLabelEdges() { + TreeBackedVertex v = new TreeBackedVertex((Vertex)tree.getObjectsAtDepth(1).iterator().next(), tree); + + assertEquals("missing hello label", false , v.edges(Direction.OUT, "hello").hasNext()); + } + + @Test + public void depthZeroNodeOnly() { + TreeBackedVertex v = new TreeBackedVertex((Vertex)treeDepth0NodeOnly.getObjectsAtDepth(1).iterator().next(), treeDepth0NodeOnly); + assertEquals("no edges returned", false, v.edges(Direction.BOTH).hasNext()); + } + +} diff --git a/aai-core/src/test/java/org/openecomp/aai/util/CNNameTest.java b/aai-core/src/test/java/org/openecomp/aai/util/CNNameTest.java new file mode 100644 index 00000000..7017c354 --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/util/CNNameTest.java @@ -0,0 +1,133 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.util; + +import ch.qos.logback.access.spi.IAccessEvent; +import org.openecomp.aai.logging.CNName; +import org.junit.Before; +import org.junit.Rule; +import org.junit.Test; +import org.mockito.Mockito; +import org.powermock.core.classloader.annotations.PowerMockIgnore; +import org.powermock.core.classloader.annotations.PrepareForTest; +import org.powermock.modules.agent.PowerMockAgent; + +import javax.security.auth.x500.X500Principal; +import javax.servlet.http.HttpServletRequest; +import java.security.cert.X509Certificate; + +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.when; + +@PowerMockIgnore("javax.security.auth.x500.X500Principal") +@PrepareForTest({IAccessEvent.class, HttpServletRequest.class, X509Certificate.class}) +public class CNNameTest { + + static { + PowerMockAgent.initializeIfNeeded(); + } + + + IAccessEvent mockAccEvent; + HttpServletRequest mockHttpServletRequest; + CNName cnname; + X509Certificate cert; + + /** + * Initialize. + */ + @Before + public void initialize(){ + mockAccEvent = Mockito.mock(IAccessEvent.class); + mockHttpServletRequest = Mockito.mock(HttpServletRequest.class); + cert = Mockito.mock(X509Certificate.class); + } + + + /** + * Test 'convert' when there is no AccessConverter. + */ + @Test + public void testConvert_withoutAccessConverter(){ + cnname = getTestObj(false); + assertTrue("Conversion failed with no AccessConverter", "INACTIVE_HEADER_CONV".equals(cnname.convert(mockAccEvent))); + } + + /** + * Test 'convert' with no CipherSuite. + */ + @Test + public void testConvert_withNullCipherSuite(){ + setupForCipherSuite(null); + assertTrue("Conversion failed for a null CipherSuite", "-".equals(cnname.convert(mockAccEvent))); + } + + + /** + * Test 'convert' with a non-null CipherSuite. + */ + @Test + public void testConvert_withNotNullCipherSuite(){ + + setupForCipherSuite("StrRepOfAValidSuite"); + + final X500Principal principal = new X500Principal("CN=AAI, OU=DOX, O=BWS, C=CA"); + + Mockito.when(cert.getSubjectX500Principal()).thenReturn(principal); + + final X509Certificate[] certChain = {cert}; + + when(mockHttpServletRequest.getAttribute("javax.servlet.request.X509Certificate")).thenReturn(certChain); + + assertTrue("Conversion failed for a valid CipherSuite", principal.toString().equals(cnname.convert(mockAccEvent))); + } + + + /** + * Helper method to mock IAccessEvent and HttpServletRequest. + * + * @param suite CipherSuite to be used in current test + */ + private void setupForCipherSuite(String suite){ + cnname = getTestObj(true); + when(mockAccEvent.getRequest()).thenReturn(mockHttpServletRequest); + when(mockHttpServletRequest.getAttribute("javax.servlet.request.cipher_suite")).thenReturn(suite); + } + + + /** + * Helper method to create a CNName object with overridden 'start status' . + * + * @param instanceStarted Start status to be used + * @return CNName object to test + */ + private CNName getTestObj(final boolean instanceStarted){ + return new CNName(){ + @Override + public boolean isStarted(){ + return instanceStarted; + } + }; + } +} + + + diff --git a/aai-core/src/test/java/org/openecomp/aai/util/CustomLogPatternLayoutTest.java b/aai-core/src/test/java/org/openecomp/aai/util/CustomLogPatternLayoutTest.java new file mode 100644 index 00000000..9b42eb3d --- /dev/null +++ b/aai-core/src/test/java/org/openecomp/aai/util/CustomLogPatternLayoutTest.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * org.openecomp.aai + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); +you may not use this file except in compliance with the License. +You may obtain a copy of the License at + + http://www.apache.org/licenses/LICENSE-2.0 + +Unless required by applicable law or agreed to in writing, software +distributed under the License is distributed on an "AS IS" BASIS, +WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. +See the License for the specific language governing permissions and +limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.aai.util; + +import static org.junit.Assert.assertFalse; +import static org.junit.Assert.assertTrue; +import org.junit.Test; + +import org.openecomp.aai.logging.CNName; +import org.openecomp.aai.logging.CustomLogPatternLayout; + +public class CustomLogPatternLayoutTest { + + /** + * Test null when defaultConverterMap doesn't have corresponding entry. + */ + @Test + public void testNull(){ + String s = CustomLogPatternLayout.defaultConverterMap.get("z"); + assertFalse("Entry not found for key 'z'", CNName.class.getName().equals(s)); + } + + /** + * Test defaultConverterMap when valid entry exists. + */ + @Test + public void testEntryFor_Z(){ + CustomLogPatternLayout layout = new CustomLogPatternLayout(); + String s = CustomLogPatternLayout.defaultConverterMap.get("z"); + assertTrue("Entry not found for key 'z'", CNName.class.getName().equals(s)); + } + +} |