aboutsummaryrefslogtreecommitdiffstats
path: root/aai-resources/src/test/java/org/onap
diff options
context:
space:
mode:
Diffstat (limited to 'aai-resources/src/test/java/org/onap')
-rw-r--r--aai-resources/src/test/java/org/onap/aai/AAISetup.java68
-rw-r--r--aai-resources/src/test/java/org/onap/aai/HttpTestUtil.java377
-rw-r--r--aai-resources/src/test/java/org/onap/aai/IncreaseNodesToolTest.java88
-rw-r--r--aai-resources/src/test/java/org/onap/aai/PayloadUtil.java98
-rw-r--r--aai-resources/src/test/java/org/onap/aai/dbgen/DupeToolTest.java148
-rw-r--r--aai-resources/src/test/java/org/onap/aai/dbgen/ForceDeleteToolTest.java208
-rw-r--r--aai-resources/src/test/java/org/onap/aai/dbgen/tags/UpdateEdgeTagsTest.java228
-rw-r--r--aai-resources/src/test/java/org/onap/aai/migration/EdgeSwingMigratorTest.java258
-rw-r--r--aai-resources/src/test/java/org/onap/aai/migration/MigrationControllerInternalTest.java281
-rw-r--r--aai-resources/src/test/java/org/onap/aai/migration/PropertyMigratorTest.java126
-rw-r--r--aai-resources/src/test/java/org/onap/aai/migration/ValueMigratorTest.java154
-rw-r--r--aai-resources/src/test/java/org/onap/aai/migration/VertexMergeTest.java179
-rw-r--r--aai-resources/src/test/java/org/onap/aai/migration/v12/ContainmentDeleteOtherVPropertyMigrationTest.java112
-rw-r--r--aai-resources/src/test/java/org/onap/aai/migration/v12/MigrateDataFromASDCToConfigurationTest.java172
-rw-r--r--aai-resources/src/test/java/org/onap/aai/migration/v12/MigrateServiceInstanceToConfigurationTest.java410
-rw-r--r--aai-resources/src/test/java/org/onap/aai/migration/v12/MigrateServiceInstanceToConfigurationTestPreMigrationMock.java304
-rw-r--r--aai-resources/src/test/java/org/onap/aai/migration/v12/SDWANSpeedChangeMigrationTest.java379
-rw-r--r--aai-resources/src/test/java/org/onap/aai/migration/v12/ToscaMigrationTest.java181
-rw-r--r--aai-resources/src/test/java/org/onap/aai/migration/v13/MigrateInstanceGroupSubTypeTest.java112
-rw-r--r--aai-resources/src/test/java/org/onap/aai/migration/v13/MigrateInstanceGroupTypeTest.java112
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/AbstractSpringRestTest.java128
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/BulkAddConsumerTest.java4
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java583
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/BulkProcessorTestAbstraction.java13
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/ConfigurationTest.java51
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/CustomerFilterSearchTest.java66
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/DepthTest.java64
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/ExampleConsumerTest.java8
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/InvalidURITest.java (renamed from aai-resources/src/test/java/org/onap/aai/util/HbaseSaltPrefixerTest.java)33
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java138
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/PserverGenerateUrlTest.java77
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/PserverMissingTest.java87
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/PserverRelationshipTest.java97
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/PserverTest.java55
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/PserverWrongHeaderTest.java50
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java19
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java19
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/bulk/BulkSingleTransactionConsumerTest.java369
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerSpringTest.java143
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerTest.java127
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/retired/V7V8ModelsTest.java28
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/retired/V7V8NamedQueriesTest.java28
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/tools/ModelVersionTransformerTest.java135
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java (renamed from aai-resources/src/test/java/org/onap/aai/rest/retired/V3ThroughV7ConsumerTest.java)16
-rw-r--r--aai-resources/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java13
-rw-r--r--aai-resources/src/test/java/org/onap/aai/schema/db/ManageSchemaTest.java111
-rw-r--r--aai-resources/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java74
-rw-r--r--aai-resources/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatSpec.java59
-rw-r--r--aai-resources/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatTest.java77
-rw-r--r--aai-resources/src/test/java/org/onap/aai/transforms/JoltTestUtil.java59
-rw-r--r--aai-resources/src/test/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverterTest.java72
-rw-r--r--aai-resources/src/test/java/org/onap/aai/transforms/MapTraverserTest.java53
-rw-r--r--aai-resources/src/test/java/org/onap/aai/util/AAIRSyncUtilityTest.java211
-rw-r--r--aai-resources/src/test/java/org/onap/aai/util/DataConversionHelperTest.java87
-rw-r--r--aai-resources/src/test/java/org/onap/aai/util/DbTestConfig.java294
-rw-r--r--aai-resources/src/test/java/org/onap/aai/util/DbTestFileWatcher.java63
-rw-r--r--aai-resources/src/test/java/org/onap/aai/util/DbTestGetFileTime.java54
-rw-r--r--aai-resources/src/test/java/org/onap/aai/util/DbTestProcessBuilder.java213
-rw-r--r--aai-resources/src/test/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java71
59 files changed, 2203 insertions, 5641 deletions
diff --git a/aai-resources/src/test/java/org/onap/aai/AAISetup.java b/aai-resources/src/test/java/org/onap/aai/AAISetup.java
index 1ae7f51..a93127b 100644
--- a/aai-resources/src/test/java/org/onap/aai/AAISetup.java
+++ b/aai-resources/src/test/java/org/onap/aai/AAISetup.java
@@ -23,21 +23,81 @@ import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
+import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.junit.BeforeClass;
-import org.onap.aai.serialization.queryformats.QueryFormatTestHelper;
-import org.onap.aai.util.AAIConstants;
+import org.onap.aai.config.SpringContextAware;
+import org.onap.aai.config.IntrospectionConfig;
+import org.onap.aai.introspection.LoaderFactory;
+import org.onap.aai.logging.LoggingContext;
+import org.onap.aai.nodes.NodeIngestor;
+import org.onap.aai.config.RestBeanConfig;
+import org.onap.aai.rest.db.HttpEntry;
+import org.onap.aai.setup.SchemaLocationsBean;
+import org.onap.aai.setup.SchemaVersion;
+import org.onap.aai.setup.SchemaVersions;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.test.context.ContextConfiguration;
+import org.onap.aai.introspection.MoxyLoader;
+import org.junit.ClassRule;
+import org.junit.Rule;
+import org.onap.aai.edges.EdgeIngestor;
+import org.onap.aai.setup.AAIConfigTranslator;
+import org.onap.aai.serialization.db.EdgeSerializer;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.rules.SpringClassRule;
+import org.springframework.test.context.junit4.rules.SpringMethodRule;
+
+@ContextConfiguration(classes = {
+ SchemaLocationsBean.class,
+ SchemaVersions.class,
+ AAIConfigTranslator.class,
+ NodeIngestor.class,
+ EdgeIngestor.class,
+ EdgeSerializer.class,
+ SpringContextAware.class,
+ IntrospectionConfig.class,
+ RestBeanConfig.class
+})
+@TestPropertySource(properties = {
+ "schema.uri.base.path = /aai" ,
+ "schema.ingest.file = src/test/resources/application-test.properties"
+})
public abstract class AAISetup {
+ @Autowired
+ protected NodeIngestor nodeIngestor;
+
+ @Autowired
+ protected LoaderFactory loaderFactory;
+
+ @Autowired
+ protected Map<SchemaVersion, MoxyLoader> moxyLoaderInstance;
+
+ @Autowired
+ protected HttpEntry traversalHttpEntry;
+
+ @Autowired
+ protected HttpEntry traversalUriHttpEntry;
+
+ @Autowired
+ protected SchemaVersions schemaVersions;
+
+ @ClassRule
+ public static final SpringClassRule springClassRule = new SpringClassRule();
+
+ @Rule
+ public final SpringMethodRule springMethodRule = new SpringMethodRule();
+
@BeforeClass
public static void setupBundleconfig() throws Exception {
System.setProperty("AJSC_HOME", "./");
System.setProperty("BUNDLECONFIG_DIR", "src/main/resources/");
-// QueryFormatTestHelper.setFinalStatic(AAIConstants.class.getField("AAI_HOME_ETC_OXM"), "bundleconfig-local/etc/oxm/");
+ LoggingContext.init();
}
-
+
public String getPayload(String filename) throws IOException {
InputStream inputStream = getClass()
diff --git a/aai-resources/src/test/java/org/onap/aai/HttpTestUtil.java b/aai-resources/src/test/java/org/onap/aai/HttpTestUtil.java
new file mode 100644
index 0000000..6b49b78
--- /dev/null
+++ b/aai-resources/src/test/java/org/onap/aai/HttpTestUtil.java
@@ -0,0 +1,377 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 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.onap.aai;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import org.javatuples.Pair;
+import org.mockito.Mockito;
+import org.onap.aai.config.SpringContextAware;
+import org.onap.aai.dbmap.DBConnectionType;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.introspection.Introspector;
+import org.onap.aai.introspection.Loader;
+import org.onap.aai.setup.SchemaVersion;
+import org.onap.aai.setup.SchemaVersions;
+import org.onap.aai.parsers.query.QueryParser;
+import org.onap.aai.parsers.uri.URIToObject;
+import org.onap.aai.rest.db.DBRequest;
+import org.onap.aai.rest.db.HttpEntry;
+import org.onap.aai.restcore.HttpMethod;
+import org.onap.aai.restcore.RESTAPI;
+import org.onap.aai.serialization.engines.TransactionalGraphEngine;
+
+import javax.ws.rs.core.*;
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.when;
+
+public class HttpTestUtil extends RESTAPI {
+
+ private static final EELFLogger logger = EELFManager.getInstance().getLogger(HttpTestUtil.class);
+
+ protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
+
+ private static final String EMPTY = "";
+
+ protected HttpHeaders httpHeaders;
+ protected UriInfo uriInfo;
+
+ protected MultivaluedMap<String, String> headersMultiMap;
+ protected MultivaluedMap<String, String> queryParameters;
+
+ protected List<String> aaiRequestContextList;
+ protected List<MediaType> outputMediaTypes;
+ protected SchemaVersions schemaVersions;
+
+ public void init(){
+
+ httpHeaders = Mockito.mock(HttpHeaders.class);
+ uriInfo = Mockito.mock(UriInfo.class);
+
+ headersMultiMap = new MultivaluedHashMap<>();
+ queryParameters = Mockito.spy(new MultivaluedHashMap<>());
+
+ headersMultiMap.add("X-FromAppId", "JUNIT");
+ headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
+ headersMultiMap.add("Real-Time", "true");
+ headersMultiMap.add("Accept", "application/json");
+ headersMultiMap.add("aai-request-context", "");
+
+ outputMediaTypes = new ArrayList<>();
+ outputMediaTypes.add(APPLICATION_JSON);
+
+ aaiRequestContextList = new ArrayList<>();
+ aaiRequestContextList.add("");
+
+ when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
+ when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
+
+ when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);
+
+ when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
+ when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters);
+
+ doReturn(null).when(queryParameters).remove(anyObject());
+ when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
+ schemaVersions = SpringContextAware.getBean(SchemaVersions.class);
+ }
+
+ public Response doPut(String uri, String payload) throws AAIException {
+
+ this.init();
+ Response response = null;
+ boolean success = true;
+ TransactionalGraphEngine dbEngine = null;
+
+ try {
+
+ uri = uri.replaceAll("/aai/", "");
+ logger.info("Starting the put request for the uri {} with payload {}", uri, payload);
+
+ String [] arr = uri.split("/");
+
+ SchemaVersion version = null;
+
+ if(arr != null && arr.length > 1){
+ if(arr[0].matches("^v\\d+")){
+ version = new SchemaVersion(arr[0]);
+ uri = uri.replaceAll("^v\\d+", "");
+ }
+ }
+
+ if(version == null){
+ version = schemaVersions.getDefaultVersion();
+ }
+ Mockito.when(uriInfo.getPath()).thenReturn(uri);
+
+ DBConnectionType type = DBConnectionType.REALTIME;
+ //HttpEntry httpEntry = new HttpEntry(version, ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry resourceHttpEntry = SpringContextAware.getBean("traversalHttpEntry", HttpEntry.class);
+ resourceHttpEntry.setHttpEntryProperties(version, type);
+ Loader loader = resourceHttpEntry.getLoader();
+ dbEngine = resourceHttpEntry.getDbEngine();
+
+ URI uriObject = UriBuilder.fromPath(uri).build();
+ URIToObject uriToObject = new URIToObject(loader, uriObject);
+
+ String objType = uriToObject.getEntityName();
+ QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject);
+
+
+ logger.info("Unmarshalling the payload to this {}", objType);
+
+ Introspector obj;
+ HttpMethod httpMethod;
+ if(uri.contains("/relationship-list/relationship")){
+ obj = loader.unmarshal("relationship", payload, org.onap.aai.restcore.MediaType.getEnum("application/json"));
+ httpMethod = HttpMethod.PUT_EDGE;
+ } else {
+ obj = loader.unmarshal(objType, payload, org.onap.aai.restcore.MediaType.getEnum("application/json"));
+ httpMethod = HttpMethod.PUT;
+ this.validateIntrospector(obj, loader, uriObject, httpMethod);
+ }
+
+
+ DBRequest dbRequest =
+ new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo, "JUNIT-TRANSACTION")
+ .rawRequestContent(payload).build();
+
+ List<DBRequest> dbRequestList = new ArrayList<>();
+ dbRequestList.add(dbRequest);
+
+ Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = resourceHttpEntry.process(dbRequestList, "JUNIT");
+ response = responsesTuple.getValue1().get(0).getValue1();
+
+ } catch (AAIException e) {
+ response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
+ success = false;
+ } catch(Exception e){
+ AAIException ex = new AAIException("AAI_4000", e);
+ response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
+ success = false;
+ } finally {
+ if(success){
+ if(response != null){
+ if((response.getStatus() / 100) == 2){
+ logger.info("Successfully completed the PUT request with status {} and committing it to DB", response.getStatus());
+ } else {
+ logFailure(HttpMethod.PUT, response);
+ }
+ }
+ dbEngine.commit();
+ } else {
+ if(response != null) {
+ logFailure(HttpMethod.PUT, response);
+ }
+ dbEngine.rollback();
+ }
+ }
+
+ return response;
+ }
+
+ public Response doGet(String uri) throws UnsupportedEncodingException, AAIException {
+
+ this.init();
+ Response response = null;
+ boolean success = true;
+ TransactionalGraphEngine dbEngine = null;
+
+ try {
+
+ uri = uri.replaceAll("/aai/", "");
+ logger.info("Starting the GET request for the uri {} with depth {}", uri, "all");
+
+ String [] arr = uri.split("/");
+
+ SchemaVersion version = null;
+
+ if(arr != null && arr.length > 1){
+ if(arr[0].matches("^v\\d+")){
+ version = new SchemaVersion(arr[0]);
+ uri = uri.replaceAll("^v\\d+", "");
+ }
+ }
+
+ if(version == null){
+ version = schemaVersions.getDefaultVersion();
+ }
+
+ DBConnectionType type = DBConnectionType.REALTIME;
+ // HttpEntry httpEntry = new HttpEntry(version, ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry resourceHttpEntry = SpringContextAware.getBean("traversalHttpEntry", HttpEntry.class);
+ resourceHttpEntry.setHttpEntryProperties(version, type);
+ Loader loader = resourceHttpEntry.getLoader();
+ dbEngine = resourceHttpEntry.getDbEngine();
+
+ URI uriObject = UriBuilder.fromPath(uri).build();
+ URIToObject uriToObject = new URIToObject(loader, uriObject);
+
+ String objType = uriToObject.getEntityName();
+ queryParameters.add("depth", "all");
+ QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters);
+
+ Mockito.when(uriInfo.getPath()).thenReturn(uri);
+
+ logger.info("Unmarshalling the payload to this {}", objType);
+
+ Introspector obj = loader.introspectorFromName(objType);
+
+ DBRequest dbRequest =
+ new DBRequest.Builder(HttpMethod.GET, uriObject, uriQuery, obj, httpHeaders, uriInfo, "JUNIT-TRANSACTION")
+ .build();
+
+ List<DBRequest> dbRequestList = new ArrayList<>();
+ dbRequestList.add(dbRequest);
+
+ Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = resourceHttpEntry.process(dbRequestList, "JUNIT");
+ response = responsesTuple.getValue1().get(0).getValue1();
+
+ } catch (AAIException e) {
+ response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
+ success = false;
+ } catch(Exception e){
+ AAIException ex = new AAIException("AAI_4000", e);
+ response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
+ success = false;
+ } finally {
+ if(success){
+ if(response != null){
+ if((response.getStatus() / 100) == 2){
+ logger.info("Successfully completed the GET request with status {} and committing it to DB", response.getStatus());
+ } else {
+ logFailure(HttpMethod.GET, response);
+ }
+ }
+ dbEngine.commit();
+ } else {
+ logFailure(HttpMethod.GET, response);
+ dbEngine.rollback();
+ }
+ }
+
+ return response;
+ }
+
+ public Response doDelete(String uri, String resourceVersion) throws UnsupportedEncodingException, AAIException {
+
+ this.init();
+ Response response = null;
+ boolean success = true;
+ TransactionalGraphEngine dbEngine = null;
+
+ try {
+
+ uri = uri.replaceAll("/aai/", "");
+ logger.info("Starting the delete request for the uri {} with resource version {}", uri, resourceVersion);
+
+ String [] arr = uri.split("/");
+
+ SchemaVersion version = null;
+
+ if(arr != null && arr.length > 1){
+ if(arr[0].matches("^v\\d+")){
+ version = new SchemaVersion(arr[0]);
+ if(!uri.contains("relationship-list/relationship")){
+ uri = uri.replaceAll("^v\\d+", "");
+ }
+ }
+ }
+
+ if(version == null){
+ version = schemaVersions.getDefaultVersion();
+ }
+
+ Mockito.when(uriInfo.getPath()).thenReturn(uri);
+ DBConnectionType type = DBConnectionType.REALTIME;
+ // HttpEntry httpEntry = new HttpEntry(version, ModelType.MOXY, QueryStyle.TRAVERSAL, type);
+ HttpEntry resourceHttpEntry = SpringContextAware.getBean("traversalHttpEntry", HttpEntry.class);
+ resourceHttpEntry.setHttpEntryProperties(version, type);
+ Loader loader = resourceHttpEntry.getLoader();
+ dbEngine = resourceHttpEntry.getDbEngine();
+
+ URI uriObject = UriBuilder.fromPath(uri).build();
+ URIToObject uriToObject = new URIToObject(loader, uriObject);
+
+ String objType = uriToObject.getEntityName();
+ queryParameters.add("resource-version", resourceVersion);
+ QueryParser uriQuery = dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters);
+
+ logger.info("Unmarshalling the payload to this {}", objType);
+
+ Introspector obj;
+ HttpMethod httpMethod;
+ if(uri.contains("/relationship-list/relationship")){
+ obj = loader.introspectorFromName("relationship");
+ httpMethod = HttpMethod.DELETE_EDGE;
+ } else {
+ obj = loader.introspectorFromName(objType);
+ httpMethod = HttpMethod.DELETE;
+ }
+
+ DBRequest dbRequest =
+ new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo, "JUNIT-TRANSACTION")
+ .build();
+
+ List<DBRequest> dbRequestList = new ArrayList<>();
+ dbRequestList.add(dbRequest);
+
+ Pair<Boolean, List<Pair<URI, Response>>> responsesTuple = resourceHttpEntry.process(dbRequestList, "JUNIT");
+ response = responsesTuple.getValue1().get(0).getValue1();
+
+ } catch (AAIException e) {
+ response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
+ success = false;
+ } catch(Exception e){
+ AAIException ex = new AAIException("AAI_4000", e);
+ response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
+ success = false;
+ } finally {
+ if(success){
+ if(response != null){
+ if((response.getStatus() / 100) == 2){
+ logger.info("Successfully completed the DELETE request with status {} and committing it to DB", response.getStatus());
+ } else {
+ logFailure(HttpMethod.DELETE, response);
+ }
+ }
+ dbEngine.commit();
+ } else {
+ logFailure(HttpMethod.DELETE, response);
+ dbEngine.rollback();
+ }
+ }
+
+ return response;
+ }
+
+ public static void logFailure(HttpMethod httpMethod, Response response){
+ logger.info("Unable to complete the {} request with status {} and rolling back", httpMethod.toString(), response.getStatus());
+ logger.info("Response body of failed request {}", response.getEntity());
+
+ }
+}
diff --git a/aai-resources/src/test/java/org/onap/aai/IncreaseNodesToolTest.java b/aai-resources/src/test/java/org/onap/aai/IncreaseNodesToolTest.java
new file mode 100644
index 0000000..5d91fb3
--- /dev/null
+++ b/aai-resources/src/test/java/org/onap/aai/IncreaseNodesToolTest.java
@@ -0,0 +1,88 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 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.onap.aai;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.janusgraph.core.JanusGraph;
+import org.janusgraph.core.JanusGraphTransaction;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mock;
+import org.mockito.Mockito;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+
+import static org.mockito.Mockito.*;
+
+public class IncreaseNodesToolTest extends AAISetup {
+
+ @Mock
+ JanusGraphTransaction janusGraphtransaction;
+
+ @Mock
+ JanusGraph janusGraph;
+
+ @Mock
+ GraphTraversalSource graphTraversalSource;
+
+ @Mock
+ Vertex mockVertex;
+
+ @Mock
+ GraphTraversal<org.apache.tinkerpop.gremlin.structure.Vertex, org.apache.tinkerpop.gremlin.structure.Vertex> graphTraversalVertex;
+
+ private IncreaseNodesTool increaseNodesTool;
+
+
+ String [] args = {"-numberOfNodes", "5" ,"-nodeType", "pserver", "-uri", "/cloud-infrastructure/pservers/pserver/"};
+
+ @Before
+ public void setup(){
+ increaseNodesTool = new IncreaseNodesTool(loaderFactory, schemaVersions);
+ }
+
+ @Test
+ public void addVertex() throws Exception {
+
+ when(janusGraph.newTransaction()).thenReturn(janusGraphtransaction);
+ when(janusGraphtransaction.traversal()).thenReturn(graphTraversalSource);
+ when(graphTraversalSource.addV()).thenReturn(graphTraversalVertex);
+ when(graphTraversalVertex.next()).thenReturn(mockVertex);
+ increaseNodesTool.run(janusGraph,args);
+
+ Mockito.verify(janusGraph).newTransaction();
+
+ Mockito.verify(graphTraversalSource,times(5)).addV();
+ }
+
+ @Test
+ public void addVertexfFail() throws Exception {
+
+ when(janusGraph.newTransaction()).thenReturn(janusGraphtransaction);
+ when(janusGraphtransaction.traversal()).thenThrow(new RuntimeException());
+
+ increaseNodesTool.run(janusGraph,args);
+
+ Mockito.verify(janusGraphtransaction).rollback();
+ }
+
+}
+
diff --git a/aai-resources/src/test/java/org/onap/aai/PayloadUtil.java b/aai-resources/src/test/java/org/onap/aai/PayloadUtil.java
new file mode 100644
index 0000000..9c99163
--- /dev/null
+++ b/aai-resources/src/test/java/org/onap/aai/PayloadUtil.java
@@ -0,0 +1,98 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 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.onap.aai;
+
+import org.apache.commons.io.IOUtils;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import static org.junit.Assert.assertNotNull;
+
+public class PayloadUtil {
+
+ private static final Map<String, String> cache = new HashMap<>();
+ private static final Pattern TEMPLATE_PATTERN = Pattern.compile("\\$\\{[^}]+\\}");
+
+ public static String getResourcePayload(String fileName) throws IOException {
+
+ InputStream inputStream = PayloadUtil.class.getClassLoader().getResourceAsStream("payloads/resource/" + fileName);
+
+ String message = String.format("Unable to find the %s in src/test/resources", fileName);
+ assertNotNull(message, inputStream);
+
+ String resource = IOUtils.toString(inputStream);
+
+ inputStream.close();
+ return resource;
+ }
+
+ public static String getTemplatePayload(String fileName, Map<String, String> templateValueMap) throws Exception {
+
+ InputStream inputStream = PayloadUtil.class.getClassLoader().getResourceAsStream("payloads/templates/" + fileName);
+
+ String message = String.format("Unable to find the %s in src/test/resources", fileName);
+ assertNotNull(message, inputStream);
+
+ String resource;
+
+ if(cache.containsKey(fileName)){
+ resource = cache.get(fileName);
+ } else {
+ resource = IOUtils.toString(inputStream);
+ cache.put(fileName, resource);
+ }
+
+ Matcher matcher = TEMPLATE_PATTERN.matcher(resource);
+
+ String resourceWithTemplateValues = resource;
+
+ while(matcher.find()){
+ int start = matcher.start() + 2;
+ int end = matcher.end() - 1;
+ String key = resource.substring(start, end);
+ if(templateValueMap.containsKey(key)){
+ resourceWithTemplateValues = resourceWithTemplateValues.replaceAll("\\$\\{" + key +"\\}", templateValueMap.get(key));
+ } else {
+ throw new RuntimeException("Unable to find the key value pair in map for the template processing for key " + key);
+ }
+ }
+
+ inputStream.close();
+ return resourceWithTemplateValues;
+ }
+
+ public static String getPayload(String fileName) throws IOException {
+
+ InputStream inputStream = PayloadUtil.class.getClassLoader().getResourceAsStream("payloads/" + fileName);
+
+ String message = String.format("Unable to find the %s in src/test/resources/payloads/", fileName);
+ assertNotNull(message, inputStream);
+
+ String resource = IOUtils.toString(inputStream);
+
+ inputStream.close();
+ return resource;
+ }
+}
diff --git a/aai-resources/src/test/java/org/onap/aai/dbgen/DupeToolTest.java b/aai-resources/src/test/java/org/onap/aai/dbgen/DupeToolTest.java
deleted file mode 100644
index e9e95eb..0000000
--- a/aai-resources/src/test/java/org/onap/aai/dbgen/DupeToolTest.java
+++ /dev/null
@@ -1,148 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.dbgen;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import org.janusgraph.core.JanusGraphTransaction;
-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.onap.aai.AAISetup;
-import org.onap.aai.dbmap.AAIGraph;
-import org.onap.aai.serialization.db.EdgeRules;
-
-import static org.junit.Assert.*;
-
-
-public class DupeToolTest extends AAISetup {
-
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(DupeToolTest.class);
-
- private DupeTool dupeTool;
-
- @Before
- public void setup(){
- dupeTool = new DupeTool();
- dupeTool.SHOULD_EXIT_VM = false;
- createGraph();
- }
-
- private void createGraph() {
- JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
-
- EdgeRules edgeRules = EdgeRules.getInstance();
-
- boolean success = true;
-
- try {
-
- GraphTraversalSource g = transaction.traversal();
-
- Vertex cloudRegionVertex = g.addV()
- .property("aai-node-type", "cloud-region")
- .property("cloud-owner", "test-owner")
- .property("cloud-region-id", "test-region")
- .property("source-of-truth", "JUNIT")
- .next();
-
- Vertex tenantVertex = g.addV()
- .property("aai-node-type", "tenant")
- .property("tenant-id", "test-tenant")
- .property("source-of-truth", "JUNIT")
- .next();
-
- Vertex pserverVertex = g.addV()
- .property("aai-node-type", "pserver")
- .property("hostname", "test-pserver")
- .property("in-maint", false)
- .property("source-of-truth", "JUNIT")
- .next();
-
- for(int i = 0; i < 100; ++i){
- g.addV()
- .property("aai-node-type", "pserver")
- .property("hostname", "test-pserver")
- .property("in-maint", false)
- .property("source-of-truth", "JUNIT")
- .next();
- }
-
- edgeRules.addTreeEdge(g, cloudRegionVertex, tenantVertex);
- edgeRules.addEdge(g, cloudRegionVertex, pserverVertex);
-
- } catch(Exception ex){
- success = false;
- logger.error("Unable to create the vertexes", ex);
- } finally {
- if(success){
- transaction.commit();
- } else {
- transaction.rollback();
- fail("Unable to setup the graph");
- }
- }
- }
-
- @Test
- public void testDupeTool(){
-
- String[] args = {
- "-userId", "testuser",
- "-nodeType", "pserver",
- "-timeWindowMinutes", "30",
- "-autoFix",
- "-maxFix", "30",
- "-sleepMinutes", "0"
- };
-
- dupeTool.main(args);
- }
-
- @After
- public void tearDown(){
-
- JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
- boolean success = true;
-
- try {
-
- GraphTraversalSource g = transaction.traversal();
-
- g.V().has("source-of-truth", "JUNIT")
- .toList()
- .forEach(v -> v.remove());
-
- } catch(Exception ex){
- success = false;
- logger.error("Unable to remove the vertexes", ex);
- } finally {
- if(success){
- transaction.commit();
- } else {
- transaction.rollback();
- fail("Unable to teardown the graph");
- }
- }
-
- }
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/dbgen/ForceDeleteToolTest.java b/aai-resources/src/test/java/org/onap/aai/dbgen/ForceDeleteToolTest.java
deleted file mode 100644
index f5b1da4..0000000
--- a/aai-resources/src/test/java/org/onap/aai/dbgen/ForceDeleteToolTest.java
+++ /dev/null
@@ -1,208 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.dbgen;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import org.janusgraph.core.JanusGraphTransaction;
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.FixMethodOrder;
-import org.junit.Test;
-import org.junit.runners.MethodSorters;
-import org.onap.aai.AAISetup;
-import org.onap.aai.dbmap.AAIGraph;
-import org.onap.aai.serialization.db.EdgeRules;
-
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.util.List;
-
-import static org.junit.Assert.fail;
-
-@FixMethodOrder(MethodSorters.NAME_ASCENDING)
-public class ForceDeleteToolTest extends AAISetup {
-
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(ForceDeleteToolTest.class);
-
- private ForceDeleteTool deleteTool;
-
- private Vertex cloudRegionVertex;
- @Before
- public void setup(){
- deleteTool = new ForceDeleteTool();
- deleteTool.SHOULD_EXIT_VM = false;
- JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
-
- EdgeRules edgeRules = EdgeRules.getInstance();
-
- boolean success = true;
-
- try {
-
- GraphTraversalSource g = transaction.traversal();
-
- cloudRegionVertex = g.addV()
- .property("aai-node-type", "cloud-region")
- .property("cloud-owner", "test-owner")
- .property("cloud-region-id", "test-region")
- .property("source-of-truth", "JUNIT")
- .next();
-
- Vertex tenantVertex = g.addV()
- .property("aai-node-type", "tenant")
- .property("tenant-id", "test-tenant")
- .property("source-of-truth", "JUNIT")
- .next();
-
- Vertex pserverVertex = g.addV()
- .property("aai-node-type", "pserver")
- .property("hostname", "test-pserver")
- .property("in-maint", false)
- .property("source-of-truth", "JUNIT")
- .next();
-
- edgeRules.addTreeEdge(g, cloudRegionVertex, tenantVertex);
- edgeRules.addEdge(g, cloudRegionVertex, pserverVertex);
-
- } catch(Exception ex){
- success = false;
- logger.error("Unable to create the vertexes", ex);
- } finally {
- if(success){
- transaction.commit();
- } else {
- transaction.rollback();
- fail("Unable to setup the graph");
- }
- }
-
-
- }
-
- @Test
- public void testCollectDataForVertex(){
-
- String [] args = {
-
- "-action",
- "COLLECT_DATA",
- "-userId",
- "someuser",
- "-params4Collect",
- "cloud-owner|test-owner"
- };
-
- deleteTool.main(args);
- }
-
- @Test
- public void testDeleteNode(){
-
- String id = cloudRegionVertex.id().toString();
-
- String [] args = {
-
- "-action",
- "DELETE_NODE",
- "-userId",
- "someuser",
- "-vertexId",
- id
- };
-
- deleteTool.main(args);
- }
-
- @Test
- public void testCollectDataForEdge(){
-
- JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
- GraphTraversalSource g = transaction.traversal();
- List<Edge> edges = g.E().toList();
- String cloudRegionToPserverId = edges.get(0).id().toString();
-
- String [] args = {
-
- "-action",
- "COLLECT_DATA",
- "-userId",
- "someuser",
- "-edgeId",
- cloudRegionToPserverId
- };
-
- deleteTool.main(args);
- }
-
- @Test
- public void testDeleteForEdge(){
-
- InputStream systemInputStream = System.in;
- ByteArrayInputStream in = new ByteArrayInputStream("y".getBytes());
- System.setIn(in);
- JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
- GraphTraversalSource g = transaction.traversal();
- List<Edge> edges = g.E().toList();
- String cloudRegionToPserverId = edges.get(0).id().toString();
-
- String [] args = {
-
- "-action",
- "DELETE_EDGE",
- "-userId",
- "someuser",
- "-edgeId",
- cloudRegionToPserverId
- };
-
- deleteTool.main(args);
- System.setIn(systemInputStream);
- }
- @After
- public void tearDown(){
-
- JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
- boolean success = true;
-
- try {
-
- GraphTraversalSource g = transaction.traversal();
-
- g.V().has("source-of-truth", "JUNIT")
- .toList()
- .forEach(v -> v.remove());
-
- } catch(Exception ex){
- success = false;
- logger.error("Unable to remove the vertexes", ex);
- } finally {
- if(success){
- transaction.commit();
- } else {
- transaction.rollback();
- fail("Unable to teardown the graph");
- }
- }
- }
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/dbgen/tags/UpdateEdgeTagsTest.java b/aai-resources/src/test/java/org/onap/aai/dbgen/tags/UpdateEdgeTagsTest.java
deleted file mode 100644
index 89c4955..0000000
--- a/aai-resources/src/test/java/org/onap/aai/dbgen/tags/UpdateEdgeTagsTest.java
+++ /dev/null
@@ -1,228 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.dbgen.tags;
-
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.schema.JanusGraphManagement;
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
-import org.apache.tinkerpop.gremlin.structure.Direction;
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.apache.tinkerpop.gremlin.structure.Graph;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.junit.After;
-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.Mockito;
-import org.onap.aai.AAISetup;
-import org.onap.aai.db.props.AAIProperties;
-import org.onap.aai.dbmap.AAIGraph;
-import org.onap.aai.dbmap.DBConnectionType;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.introspection.Version;
-import org.onap.aai.serialization.db.AAIDirection;
-import org.onap.aai.serialization.db.EdgeProperty;
-import org.onap.aai.serialization.db.EdgeRules;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.JanusGraphDBEngine;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import org.onap.aai.exceptions.AAIException;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-import java.util.Iterator;
-
-public class UpdateEdgeTagsTest extends AAISetup {
-
- private final static Version version = Version.v12;
- private final static ModelType introspectorFactoryType = ModelType.MOXY;
- private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL;
- private final static DBConnectionType type = DBConnectionType.REALTIME;
- private Loader loader;
- private TransactionalGraphEngine dbEngine;
- private JanusGraph graph;
- private JanusGraph passedGraph;
- private UpdateEdgeTagsCmd edgeOp;
- private GraphTraversalSource g;
- private Graph tx;
- @Rule
- public ExpectedException thrown = ExpectedException.none();
-
- @Before
- public void setUp() throws Exception {
- graph = JanusGraphFactory.build().set("storage.backend","inmemory").open();
- JanusGraphManagement janusgraphManagement = graph.openManagement();
- tx = graph.newTransaction();
- g = tx.traversal();
- loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
-
- Vertex gvnf = g.addV().property(AAIProperties.NODE_TYPE, "generic-vnf")
- .property("vnf-id", "test-vnf")
- .next();
-
- Vertex lInterface = g.addV().property(AAIProperties.NODE_TYPE, "l-interface")
- .property("interface-name", "toscaMigration-test-lint")
- .next();
-
- Vertex logicalLink = g.addV().property(AAIProperties.NODE_TYPE, "logical-link")
- .property("link-name", "toscaMigration-logical-link")
- .next();
-
-
-
- gvnf.addEdge("hasLInterface", lInterface, EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString(),
- EdgeProperty.DELETE_OTHER_V.toString(), AAIDirection.NONE.toString());
-
- lInterface.addEdge("usesLogicalLink", logicalLink, EdgeProperty.CONTAINS.toString(), AAIDirection.NONE.toString(),
- EdgeProperty.DELETE_OTHER_V.toString(), AAIDirection.NONE.toString());
- lInterface.addEdge("sourceLInterface", logicalLink, EdgeProperty.CONTAINS.toString(), AAIDirection.NONE.toString(),
- EdgeProperty.DELETE_OTHER_V.toString(), AAIDirection.NONE.toString());
-
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
- Vertex vnfc = g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
- pserver.addEdge("tosca.relationships.HostedOn", vnfc, EdgeProperty.CONTAINS.toString(), AAIDirection.NONE.toString(),
- EdgeProperty.DELETE_OTHER_V.toString(), AAIDirection.NONE.toString());
- GraphTraversalSource traversal = g;
-
- passedGraph = spy(graph);
- when(passedGraph.traversal()).thenReturn(traversal);
-
- Iterator<Edge> edgeItr = traversal.E();
- while( edgeItr != null && edgeItr.hasNext() ){
- Edge tEdge = edgeItr.next();
- String edLab = tEdge.label().toString();
- System.out.println("key = " + tEdge.inVertex().<String>property("aai-node-type").orElse(null)+"|"+ tEdge.outVertex().<String>property("aai-node-type").orElse(null)+ ", label = " + tEdge.label()
- + ", for id = " + tEdge.id().toString() + ", set: "+tEdge.keys()+":"+tEdge.values());
- System.out.println("DEBUG - label = " + edLab);
- }
-
- }
-
- @After
- public void cleanUp() {
- tx.tx().rollback();
- graph.close();
- }
-
- @Test
- public void verifyDirectionWasReversed_OriginalGraph() {
-
- edgeOp = new UpdateEdgeTagsCmd("all", "/updateEdgeTestRules.json");
- edgeOp.setGraph(passedGraph);
- try {
- edgeOp.execute();
- } catch (AAIException e) {
- e.printStackTrace();
- }
- Iterator<Edge> edgeItr = g.E();
- while( edgeItr != null && edgeItr.hasNext() ){
- Edge tmpEd = edgeItr.next();
- System.out.println("Edge = " + tmpEd.inVertex().property("aai-node-type") + ", label = " + tmpEd.label()
- + ", for id = " + tmpEd.id().toString() +","+tmpEd.keys()+tmpEd.value("contains-other-v"));
- try {
- System.out.println("Edge prevent-delete = " +tmpEd.value("prevent-delete"));
- System.out.println("Edge description = " +tmpEd.value("description"));
- } catch (Exception e) {;} finally {;}
- }
- assertEquals("Graph should have four(4) Edges with contains-other-v=OUT"
- , Long.valueOf(4)
- , g.E().has("contains-other-v",AAIDirection.IN.toString()).count().next());
- assertEquals("Graph should have zero(0) Edges with contains-other-v=NONE"
- , Long.valueOf(0)
- , g.E().has("contains-other-v",AAIDirection.NONE.toString()).count().next());
- }
-
- @Test
- public void verifyDirectionWasReversed_withFilter() {
-
- edgeOp = new UpdateEdgeTagsCmd("vnfc|pserver", "/updateEdgeTestRules.json");
- edgeOp.setGraph(passedGraph);
- try {
- edgeOp.execute();
- } catch (AAIException e) {
- e.printStackTrace();
- }
- Iterator<Edge> edgeItr = g.E();
- while( edgeItr != null && edgeItr.hasNext() ){
- Edge tmpEd = edgeItr.next();
- System.out.println("Edge = " + tmpEd.inVertex().property("aai-node-type") + ", label = " + tmpEd.label()
- + ", for id = " + tmpEd.id().toString() +","+tmpEd.keys()+tmpEd.value("contains-other-v"));
- }
- assertEquals("Graph should have one(1) Edges with contains-other-v=OUT"
- , Long.valueOf(1)
- , g.E().has("contains-other-v",AAIDirection.OUT.toString()).count().next());
- assertEquals("Graph should have one(1) Edges with contains-other-v=IN"
- , Long.valueOf(1)
- , g.E().has("contains-other-v",AAIDirection.IN.toString()).count().next());
- assertEquals("Graph should have two(2) Edges with contains-other-v=NONE"
- , Long.valueOf(2)
- , g.E().has("contains-other-v",AAIDirection.NONE.toString()).count().next());
- }
-
- @Test
- public void verifyFaultyRuleFile_MissingEdgeSpec() throws AAIException {
-
- thrown.expect(AAIException.class);
- thrown.expectMessage("No EdgeRule found for nodeTypes: pserver|vnfc|blah");
-
- Vertex pserver = g.V().has(AAIProperties.NODE_TYPE, "pserver").has("hostname", "a-name").next();
- Vertex vnfc = g.V().has(AAIProperties.NODE_TYPE,"vnfc").has("vnfc-name","a-name").next();
- pserver.addEdge("blah", vnfc, EdgeProperty.CONTAINS.toString(), AAIDirection.NONE.toString(),
- EdgeProperty.DELETE_OTHER_V.toString(), AAIDirection.NONE.toString());
- //Edge "blah" is not found in updateEdgeTestRules.json
- edgeOp = new UpdateEdgeTagsCmd("all", "/updateEdgeTestRules.json");
- edgeOp.setGraph(passedGraph);
- edgeOp.execute();
- }
-
- @Test
- public void verifyNewPropertyWasNOTAdded() {
- //Edge rules in updateEdgeTestRules.json have "description" and "newProperty"
- // but they don't transfer
- edgeOp = new UpdateEdgeTagsCmd("all", "/updateEdgeTestRules.json");
- edgeOp.setGraph(passedGraph);
- try {
- edgeOp.execute();
- } catch (AAIException e) {
- e.printStackTrace();
- }
- assertEquals("Graph could have zero(4) Edges with newProperty=newValue"
- , Long.valueOf(0)
- , g.E().has("newProperty","newValue").count().next());
- assertEquals("Graph should have one(1) Edge with description=A l-interface/logical-link(1) edge description"
- , Long.valueOf(0)
- , g.E().has("description","A l-interface/logical-link(0) edge description").count().next());
- }
-}
-
- \ No newline at end of file
diff --git a/aai-resources/src/test/java/org/onap/aai/migration/EdgeSwingMigratorTest.java b/aai-resources/src/test/java/org/onap/aai/migration/EdgeSwingMigratorTest.java
deleted file mode 100644
index 89da7fa..0000000
--- a/aai-resources/src/test/java/org/onap/aai/migration/EdgeSwingMigratorTest.java
+++ /dev/null
@@ -1,258 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.migration;
-
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.Iterator;
-import java.util.List;
-import java.util.Optional;
-
-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.structure.Direction;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.apache.tinkerpop.gremlin.structure.Property;
-import org.javatuples.Pair;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.onap.aai.AAISetup;
-import org.onap.aai.db.props.AAIProperties;
-import org.onap.aai.dbmap.AAIGraph;
-import org.onap.aai.dbmap.DBConnectionType;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.introspection.Version;
-import org.onap.aai.serialization.db.EdgeRules;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.JanusGraphDBEngine;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.JanusGraphTransaction;
-import org.janusgraph.core.schema.JanusGraphManagement;
-
-public class EdgeSwingMigratorTest extends AAISetup {
-
- private final static Version version = Version.getLatest();
- private final static ModelType introspectorFactoryType = ModelType.MOXY;
- private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL;
- private final static DBConnectionType type = DBConnectionType.REALTIME;
- private Loader loader;
- private TransactionalGraphEngine dbEngine;
- private JanusGraph graph;
- private GraphTraversalSource g;
- private JanusGraphTransaction tx;
- private MockEdgeSwingMigrator migration;
- private EdgeRules rules;
- private Vertex modelVer1 = null;
- private Vertex modelVer3 = null;
-
-
- @Before
- public void setUp() throws Exception {
- graph = JanusGraphFactory.build().set("storage.backend","inmemory").open();
- JanusGraphManagement janusgraphManagement = graph.openManagement();
- tx = graph.newTransaction();
- g = graph.traversal();
- loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
- rules = EdgeRules.getInstance();
- createFirstVertexAndRelatedVertexes();
- TransactionalGraphEngine spy = spy(dbEngine);
- TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
- GraphTraversalSource traversal = g;
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- Mockito.doReturn(janusgraphManagement).when(adminSpy).getManagementSystem();
-
-
- migration = new MockEdgeSwingMigrator(spy);
- migration.run();
- }
-
- private void createFirstVertexAndRelatedVertexes() throws AAIException {
- Vertex model1 = g.addV().property("aai-node-type", "model")
- .property("model-invariant-id", "model-invariant-id-1")
- .property("model-type", "widget")
- .next();
- modelVer1 = g.addV().property("aai-node-type", "model-ver")
- .property("model-version-id", "model-version-id-1")
- .property("model-name", "connector")
- .property("model-version", "v1.0")
- .next();
- rules.addTreeEdge(g, model1, modelVer1);
-
- //Create the cousin vertex - modelElement2 which will point to modelVer1
- Vertex model2 = g.addV().property("aai-node-type", "model")
- .property("model-invariant-id", "model-invariant-id-2")
- .property("model-type", "resource")
- .next();
- Vertex modelVer2 = g.addV().property("aai-node-type", "model-ver")
- .property("model-version-id", "model-version-id-2")
- .property("model-name", "resourceModTestVer")
- .property("model-version", "v1.0")
- .next();
- rules.addTreeEdge(g, model2, modelVer2);
- Vertex modelElement2 = g.addV().property("aai-node-type", "model-element")
- .property("model-element-uuid", "model-element-uuid-2")
- .property("new-data-del-flag", "T")
- .property("cardinality", "unbounded")
- .next();
- rules.addTreeEdge(g, modelVer2, modelElement2);
- rules.addEdge(g, modelVer1, modelElement2);
-
- Vertex model3 = g.addV().property("aai-node-type", "model")
- .property("model-invariant-id", "model-invariant-id-3")
- .property("model-type", "widget")
- .next();
- modelVer3 = g.addV().property("aai-node-type", "model-ver")
- .property("model-version-id", "model-version-id-3")
- .property("model-name", "connector")
- .property("model-version", "v1.0")
- .next();
- rules.addTreeEdge(g, model3, modelVer3);
- }
-
- class MockEdgeSwingMigrator extends EdgeSwingMigrator {
-
- public MockEdgeSwingMigrator(TransactionalGraphEngine engine) {
- super(engine);
- }
-
- @Override
- public List<Pair<Vertex, Vertex>> getAffectedNodePairs() {
- List<Pair<Vertex, Vertex>> fromToVertPairList = new ArrayList<Pair<Vertex, Vertex>>();
- Vertex fromVert = modelVer1;
- Vertex toVert = modelVer3;
- fromToVertPairList.add(new Pair<>(fromVert, toVert));
- return fromToVertPairList;
- }
-
- public String getNodeTypeRestriction(){
- return "model-element";
- }
-
- public String getEdgeLabelRestriction(){
- return "org.onap.relationships.inventory.IsA";
- }
-
- public String getEdgeDirRestriction(){
- return "IN";
- }
-
- @Override
- public void cleanupAsAppropriate(List<Pair<Vertex, Vertex>> nodePairL) {
- // For the scenario we're testing, we would define this to remove the model-ver that
- // we moved off of, and also remove its parent model since it was a widget model and
- // these are currently one-to-one (model-ver to model).
- //
- // But what gets cleaned up (if anything) after a node's edges are migrated will vary depending
- // on what the edgeSwingMigration is being used for.
-
-
- }
-
- @Override
- public Optional<String[]> getAffectedNodeTypes() {
- return Optional.of(new String[]{"model", "model-element", "model-ver"});
- }
-
- @Override
- public String getMigrationName() {
- return "MockEdgeSwingMigrator";
- }
- }
-
- @After
- public void cleanUp() {
- tx.rollback();
- graph.close();
- }
-
-
-
- @Test
- public void testBelongsToEdgesStillThere() {
- assertEquals(true, g.V().has("aai-node-type", "model-ver").has("model-version-id", "model-version-id-1")
- .out("org.onap.relationships.inventory.BelongsTo").has("model-invariant-id", "model-invariant-id-1").hasNext());
- assertEquals(true, g.V().has("aai-node-type", "model-ver").has("model-version-id", "model-version-id-3")
- .out("org.onap.relationships.inventory.BelongsTo").has("model-invariant-id", "model-invariant-id-3").hasNext());
- assertEquals(true, g.V().has("aai-node-type", "model-element").has("model-element-uuid", "model-element-uuid-2")
- .out("org.onap.relationships.inventory.BelongsTo").has("model-version-id", "model-version-id-2").hasNext());
- }
-
- @Test
- public void testThatNewEdgeAdded() {
- assertEquals(true, g.V().has("aai-node-type", "model-ver").has("model-version-id", "model-version-id-3")
- .in("org.onap.relationships.inventory.IsA").has("model-element-uuid", "model-element-uuid-2").hasNext());
- }
-
- @Test
- public void testThatNewEdgeHasAaiUuidAndDelProperties() {
- boolean haveUuidProp = false;
- boolean haveDelOtherVProp = false;
- GraphTraversal<Vertex, Vertex> modVerTrav = g.V().has("aai-node-type", "model-ver").has("model-version-id", "model-version-id-3");
- while (modVerTrav.hasNext()) {
- Vertex modVerVtx = modVerTrav.next();
- Iterator <Edge> edgeIter = modVerVtx.edges(Direction.IN, "org.onap.relationships.inventory.IsA");
- while( edgeIter.hasNext() ){
- Edge oldOutE = edgeIter.next();
-
- Iterator <Property<Object>> propsIter2 = oldOutE.properties();
- HashMap<String, String> propMap2 = new HashMap<String,String>();
- while( propsIter2.hasNext() ){
- Property <Object> ep2 = propsIter2.next();
- if( ep2.key().equals("aai-uuid") ){
- haveUuidProp = true;
- }
- else if( ep2.key().equals("delete-other-v") ){
- haveDelOtherVProp = true;
- }
- }
- }
- }
-
- assertTrue("New IsA edge has aai-uuid property ", haveUuidProp );
- assertTrue("New IsA edge has delete-other-v property ", haveDelOtherVProp );
- }
-
-
- @Test
- public void testThatOldEdgeGone() {
- assertEquals(false, g.V().has("aai-node-type", "model-ver").has("model-version-id", "model-version-id-1")
- .in("org.onap.relationships.inventory.IsA").has("model-element-uuid", "model-element-uuid-2").hasNext());
- }
-
-
-} \ No newline at end of file
diff --git a/aai-resources/src/test/java/org/onap/aai/migration/MigrationControllerInternalTest.java b/aai-resources/src/test/java/org/onap/aai/migration/MigrationControllerInternalTest.java
deleted file mode 100644
index 4ba200a..0000000
--- a/aai-resources/src/test/java/org/onap/aai/migration/MigrationControllerInternalTest.java
+++ /dev/null
@@ -1,281 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.migration;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import org.janusgraph.core.JanusGraphTransaction;
-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.onap.aai.AAISetup;
-import org.onap.aai.dbmap.AAIGraph;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.serialization.db.EdgeRules;
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.StringContains.containsString;
-
-public class MigrationControllerInternalTest extends AAISetup {
-
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(MigrationControllerInternalTest.class);
-
- private MigrationControllerInternal migrationControllerInternal;
-
- @Before
- public void setup() throws AAIException {
- migrationControllerInternal = new MigrationControllerInternal();
- clearGraph();
- createGraph();
- }
-
- private void createGraph(){
-
- JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
- boolean success = true;
-
- try {
- GraphTraversalSource g = transaction.traversal();
-
- Vertex servSub1 = g.addV().property("aai-node-type", "service-subscription")
- .property("service-type", "DHV")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex servinst1 = g.addV().property( "aai-node-type", "service-instance")
- .property("service-type", "DHV")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex allotedRsrc1 = g.addV().property( "aai-node-type", "allotted-resource")
- .property("id","rsrc1")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex servinst2 = g.addV().property( "aai-node-type", "service-instance")
- .property("service-type", "VVIG")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex servSub2 = g.addV().property("aai-node-type", "service-subscription")
- .property("service-type", "VVIG")
- .property("source-of-truth", "JUNIT")
- .next();
-
- Vertex genericvnf1 = g.addV().property("aai-node-type", "generic-vnf")
- .property("vnf-id", "vnfId1")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex vServer1 = g.addV().property("aai-node-type", "vserver")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex pServer1 = g.addV().property("aai-node-type", "pserver")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex pInterfaceWan1 = g.addV().property("aai-node-type", "p-interface")
- .property("interface-name","ge-0/0/10")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex tunnelXConnectAll_Wan1 = g.addV().property( "aai-node-type", "tunnel-xconnect")
- .property("id", "tunnelXConnectWan1")
- .property("bandwidth-up-wan1", "300")
- .property("bandwidth-down-wan1", "400")
- .property("bandwidth-up-wan2", "500")
- .property("bandwidth-down-wan2", "600")
- .property("source-of-truth", "JUNIT")
- .next();
-
- Vertex pLinkWan1 = g.addV().property("aai-node-type", "physical-link")
- .property("link-name", "pLinkWan1")
- .property("service-provider-bandwidth-up-units", "empty")
- .property("service-provider-bandwidth-down-units", "empty")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex servSub3 = g.addV().property("aai-node-type", "service-subscription")
- .property("service-type", "DHV")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex servinst3 = g.addV().property( "aai-node-type", "service-instance")
- .property("service-type", "DHV")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex allotedRsrc3 = g.addV().property( "aai-node-type", "allotted-resource")
- .property("id","rsrc3")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex servinst4 = g.addV().property( "aai-node-type", "service-instance")
- .property("service-type", "VVIG")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex servSub4 = g.addV().property("aai-node-type", "service-subscription")
- .property("service-type", "VVIG")
- .property("source-of-truth", "JUNIT")
- .next();
-
- Vertex genericvnf3 = g.addV().property("aai-node-type", "generic-vnf")
- .property("vnf-id", "vnfId3")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex vServer3 = g.addV().property("aai-node-type", "vserver")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex pServer3 = g.addV().property("aai-node-type", "pserver")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex pInterfaceWan3 = g.addV().property("aai-node-type", "p-interface")
- .property("interface-name","ge-0/0/11")
- .property("source-of-truth", "JUNIT")
- .next();
- Vertex tunnelXConnectAll_Wan3 = g.addV().property( "aai-node-type", "tunnel-xconnect")
- .property("id", "tunnelXConnectWan3")
- .property("bandwidth-up-wan1", "300")
- .property("bandwidth-down-wan1", "400")
- .property("bandwidth-up-wan2", "500")
- .property("bandwidth-down-wan2", "600")
- .property("source-of-truth", "JUNIT")
- .next();
-
- Vertex pLinkWan3 = g.addV().property("aai-node-type", "physical-link")
- .property("link-name", "pLinkWan3")
- .property("service-provider-bandwidth-up-units", "empty")
- .property("service-provider-bandwidth-down-units", "empty")
- .property("source-of-truth", "JUNIT")
- .next();
-
- EdgeRules rules = EdgeRules.getInstance();
-
- rules.addTreeEdge(g,servSub1,servinst1);
- rules.addEdge(g,servinst1,allotedRsrc1);
- rules.addTreeEdge(g,servinst2,servSub2);
- rules.addTreeEdge(g,allotedRsrc1,servinst2);
-
- rules.addTreeEdge(g,allotedRsrc1,tunnelXConnectAll_Wan1);
-
-
- rules.addEdge(g,servinst1,genericvnf1);
- rules.addEdge(g,genericvnf1,vServer1);
- rules.addEdge(g,vServer1,pServer1);
- rules.addTreeEdge(g,pServer1,pInterfaceWan1);
- rules.addEdge(g,pInterfaceWan1,pLinkWan1);
-
- rules.addTreeEdge(g,servSub3,servinst3);
- rules.addEdge(g,servinst3,allotedRsrc3);
- rules.addTreeEdge(g,servinst4,servSub4);
- rules.addTreeEdge(g,allotedRsrc3,servinst4);
-
- rules.addTreeEdge(g,allotedRsrc3,tunnelXConnectAll_Wan3);
-
-
- rules.addEdge(g,servinst3,genericvnf3);
- rules.addEdge(g,genericvnf3,vServer3);
- rules.addEdge(g,vServer3,pServer3);
- rules.addTreeEdge(g,pServer3,pInterfaceWan3);
- rules.addEdge(g,pInterfaceWan3,pLinkWan3);
-
- } catch(Exception ex){
- success = false;
- logger.error("Unable to create the graph {}", ex);
- } finally {
- if(success){
- transaction.commit();
- } else {
- transaction.rollback();
- }
-
- }
- }
-
- @Test
- public void testListAllOfMigrations() throws Exception {
- PrintStream oldOutputStream = System.out;
- final ByteArrayOutputStream myOut = new ByteArrayOutputStream();
- System.setOut(new PrintStream(myOut));
-
- String [] args = {
- "-c", "./bundleconfig-local/etc/appprops/janusgraph-realtime.properties",
- "-l"
- };
-
- migrationControllerInternal.run(args);
-
- String content = myOut.toString();
- assertThat(content, containsString("List of all migrations"));
- System.setOut(oldOutputStream);
- }
-
- @Test
- public void testRunSpecificMigration() throws Exception {
- String [] args = "-c ./bundleconfig-local/etc/appprops/janusgraph-realtime.properties -m SDWANSpeedChangeMigration".split(" ");
- migrationControllerInternal.run(args);
- }
-
- @Test
- public void testRunSpecificMigrationAndCommit() throws Exception {
- String [] args = {
- "-c", "./bundleconfig-local/etc/appprops/janusgraph-realtime.properties",
- "-m", "SDWANSpeedChangeMigration",
- "--commit"
- };
- migrationControllerInternal.run(args);
- }
-
- @Test
- public void testRunSpecificMigrationFromLoadingSnapshotAndCommit() throws Exception{
- clearGraph();
- String [] args = {
- "-d", "./snapshots/sdwan_test_migration.graphson",
- "-c", "./bundleconfig-local/etc/appprops/janusgraph-realtime.properties",
- "-m", "SDWANSpeedChangeMigration"
- };
- migrationControllerInternal.run(args);
- }
-
- @After
- public void tearDown(){
- clearGraph();
- }
-
- public void clearGraph(){
-
- JanusGraphTransaction janusgraphTransaction = AAIGraph.getInstance().getGraph().newTransaction();
-
- boolean success = true;
-
- try {
- GraphTraversalSource g = janusgraphTransaction.traversal();
-
- g.V().has("source-of-truth", "JUNIT")
- .toList()
- .forEach((v) -> v.remove());
-
- } catch(Exception ex) {
- success = false;
- logger.error("Unable to remove all of the vertexes", ex);
- } finally {
- if(success){
- janusgraphTransaction.commit();
- } else {
- janusgraphTransaction.rollback();
- }
- }
-
- }
-} \ No newline at end of file
diff --git a/aai-resources/src/test/java/org/onap/aai/migration/PropertyMigratorTest.java b/aai-resources/src/test/java/org/onap/aai/migration/PropertyMigratorTest.java
deleted file mode 100644
index 2b7d58d..0000000
--- a/aai-resources/src/test/java/org/onap/aai/migration/PropertyMigratorTest.java
+++ /dev/null
@@ -1,126 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.migration;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import org.janusgraph.core.Cardinality;
-import org.janusgraph.core.JanusGraphTransaction;
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.aai.AAISetup;
-import org.onap.aai.dbmap.AAIGraph;
-import org.onap.aai.dbmap.DBConnectionType;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.introspection.Version;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.JanusGraphDBEngine;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import java.util.List;
-import java.util.Optional;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
-public class PropertyMigratorTest extends AAISetup {
-
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(PropertyMigratorTest.class);
-
- public static class PserverPropMigrator extends PropertyMigrator {
-
- public PserverPropMigrator(TransactionalGraphEngine engine, String oldName, String newName, Class<?> type, Cardinality cardinality) {
- super(engine, oldName, newName, type, cardinality);
- }
-
- @Override
- public boolean isIndexed() {
- return true;
- }
-
- @Override
- public Optional<String[]> getAffectedNodeTypes() {
- return Optional.of(new String[]{ "pserver" });
- }
-
- @Override
- public String getMigrationName() {
- return "PserverPropMigrator";
- }
- }
-
- @Before
- public void setup(){
- AAIGraph.getInstance();
- JanusGraphTransaction janusgraphTransaction = AAIGraph.getInstance().getGraph().newTransaction();
- boolean success = true;
-
- try {
- GraphTraversalSource g = janusgraphTransaction.traversal();
- g.addV()
- .property("aai-node-type", "pserver")
- .property("hostname", "fake-hostname")
- .property("inv-status", "some status")
- .property("source-of-truth", "JUNIT")
- .next();
- } catch(Exception ex){
- success = false;
- logger.error("Unable to commit the transaction {}", ex);
-
- } finally {
- if(success){
- janusgraphTransaction.commit();
- } else {
- janusgraphTransaction.rollback();
- }
-
- }
- }
-
- @Test
- public void testAfterPropertyMigration(){
-
- String oldPropName = "inv-status";
- String newPropName = "inventory-status";
-
- Loader loader = LoaderFactory.createLoaderForVersion(ModelType.MOXY, Version.v11);
- JanusGraphDBEngine dbEngine = new JanusGraphDBEngine(QueryStyle.TRAVERSAL, DBConnectionType.REALTIME, loader);
- dbEngine.startTransaction();
-
- PropertyMigrator propertyMigrator = new PserverPropMigrator(dbEngine, oldPropName, newPropName, String.class, Cardinality.SINGLE);
- propertyMigrator.run();
- assertEquals("Expecting the property to be success", Status.SUCCESS, propertyMigrator.getStatus());
- dbEngine.commit();
-
- JanusGraphTransaction janusgraphTransaction = AAIGraph.getInstance().getGraph().newTransaction();
- GraphTraversalSource g = janusgraphTransaction.traversal();
-
- List<Vertex> oldVList = g.V().has("aai-node-type", "pserver").has(oldPropName).toList();
- List<Vertex> newVList = g.V().has("aai-node-type", "pserver").has(newPropName).toList();
-
- assertEquals("Expecting the vertex list with old property to be zero", 0, oldVList.size());
- assertEquals("Expecting the vertex list with new property to be 1", 1, newVList.size());
- assertEquals("Expecting the equipment type to be some equipment", "some status", newVList.get(0).property(newPropName).value());
- }
-} \ No newline at end of file
diff --git a/aai-resources/src/test/java/org/onap/aai/migration/ValueMigratorTest.java b/aai-resources/src/test/java/org/onap/aai/migration/ValueMigratorTest.java
deleted file mode 100644
index 7850fd2..0000000
--- a/aai-resources/src/test/java/org/onap/aai/migration/ValueMigratorTest.java
+++ /dev/null
@@ -1,154 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.migration;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.JanusGraphTransaction;
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.aai.AAISetup;
-import org.onap.aai.dbmap.DBConnectionType;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.introspection.Version;
-import org.onap.aai.serialization.db.EdgeRules;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.JanusGraphDBEngine;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-import java.util.HashMap;
-import java.util.Map;
-import java.util.Optional;
-
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertEquals;
-
-public class ValueMigratorTest extends AAISetup{
-
- public static class SampleValueMigrator extends ValueMigrator {
- public SampleValueMigrator(TransactionalGraphEngine engine, Map map, Boolean updateExistingValues){
- super(engine, map, updateExistingValues);
- }
- @Override
- public Status getStatus() {
- return Status.SUCCESS;
- }
- @Override
- public Optional<String[]> getAffectedNodeTypes() {
- return null;
- }
- @Override
- public String getMigrationName() {
- return "SampleValueMigrator";
- }
- }
-
- private final static Version version = Version.v10;
- private final static ModelType introspectorFactoryType = ModelType.MOXY;
- private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL;
- private final static DBConnectionType type = DBConnectionType.REALTIME;
- private Loader loader;
- private TransactionalGraphEngine dbEngine;
- private JanusGraph graph;
- private SampleValueMigrator migration;
- private EdgeRules rules;
- private GraphTraversalSource g;
- private JanusGraphTransaction tx;
- private SampleValueMigrator existingValuesMigration;
-
- @Before
- public void setup() throws Exception{
- graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
- tx = graph.newTransaction();
- g = tx.traversal();
- loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
- rules = EdgeRules.getInstance();
- Map<String, Map> map = new HashMap<>();
- Map<String, Boolean> pair = new HashMap<>();
- pair.put("in-maint", true);
- map.put("pserver", pair);
- map.put("pnf", pair);
- g.addV().property("aai-node-type", "pserver")
- .property("pserver-id", "pserver0")
- .next();
- g.addV().property("aai-node-type", "pserver")
- .property("pserver-id", "pserver1")
- .property("in-maint", "")
- .next();
- g.addV().property("aai-node-type", "pserver")
- .property("pserver-id", "pserver2")
- .property("in-maint", false)
- .next();
- g.addV().property("aai-node-type", "pnf")
- .property("pnf-name","pnf1" )
- .property("in-maint", false)
- .next();
- TransactionalGraphEngine spy = spy(dbEngine);
- TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
- GraphTraversalSource traversal = g;
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- migration = new SampleValueMigrator(spy, map, false);
- migration.run();
-
- map = new HashMap<>();
- pair = new HashMap<>();
- pair.put("in-maint", true);
- map.put("pnf", pair);
- existingValuesMigration = new SampleValueMigrator(spy, map, true);
- existingValuesMigration.run();
- }
-
- @Test
- public void testMissingProperty(){
- assertTrue("Value of pnf should be updated since the property doesn't exist",
- g.V().has("aai-node-type", "pserver").has("pserver-id", "pserver0").has("in-maint", true).hasNext());
- }
-
- @Test
- public void testExistingValue() {
- assertTrue("Value of pserver shouldn't be updated since it already exists",
- g.V().has("aai-node-type", "pserver").has("pserver-id", "pserver2").has("in-maint", false).hasNext());
- }
-
- @Test
- public void testEmptyValue() {
- assertTrue("Value of pserver should be updated since the value is an empty string",
- g.V().has("aai-node-type", "pserver").has("pserver-id", "pserver1").has("in-maint", true).hasNext());
- }
-
- @Test
- public void testUpdateExistingValues() {
- assertTrue("Value of pnf should be updated even though it already exists",
- g.V().has("aai-node-type", "pnf").has("pnf-name", "pnf1").has("in-maint", true).hasNext());
- }
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/migration/VertexMergeTest.java b/aai-resources/src/test/java/org/onap/aai/migration/VertexMergeTest.java
deleted file mode 100644
index 90cd921..0000000
--- a/aai-resources/src/test/java/org/onap/aai/migration/VertexMergeTest.java
+++ /dev/null
@@ -1,179 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.migration;
-
-import org.janusgraph.core.Cardinality;
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.schema.JanusGraphManagement;
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
-import org.apache.tinkerpop.gremlin.structure.Graph;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.junit.*;
-import org.onap.aai.AAISetup;
-import org.onap.aai.db.props.AAIProperties;
-import org.onap.aai.dbmap.DBConnectionType;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.introspection.Version;
-import org.onap.aai.serialization.db.DBSerializer;
-import org.onap.aai.serialization.db.EdgeRules;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.JanusGraphDBEngine;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import java.io.UnsupportedEncodingException;
-import java.util.*;
-
-import static org.hamcrest.collection.IsIterableContainingInAnyOrder.containsInAnyOrder;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-@Ignore
-public class VertexMergeTest extends AAISetup {
-
-
- private final static Version version = Version.v10;
- private final static ModelType introspectorFactoryType = ModelType.MOXY;
- private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL;
- private final static DBConnectionType type = DBConnectionType.REALTIME;
- private Loader loader;
- private TransactionalGraphEngine dbEngine;
- private JanusGraph graph;
- private EdgeRules rules;
- private GraphTraversalSource g;
- private Graph tx;
-
- @Before
- public void setUp() throws Exception {
- graph = JanusGraphFactory.build().set("storage.backend","inmemory").open();
- tx = graph.newTransaction();
- g = tx.traversal();
- loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
- rules = EdgeRules.getInstance();
-
- JanusGraphManagement mgmt = graph.openManagement();
- mgmt.makePropertyKey("test-list").dataType(String.class).cardinality(Cardinality.SET).make();
- mgmt.commit();
- Vertex pserverSkeleton = g.addV().property("aai-node-type", "pserver").property("hostname", "TEST1")
- .property("source-of-truth", "AAI-EXTENSIONS").property("fqdn", "test1.com").property("test-list", "value1").next();
-
- Vertex pInterface1 = g.addV().property("aai-node-type", "p-interface").property("interface-name", "p-interface1")
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/TEST1/p-interfaces/p-interface/p-interface1").next();
-
- Vertex pInterface2 = g.addV().property("aai-node-type", "p-interface").property("interface-name", "p-interface2")
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/TEST1/p-interfaces/p-interface/p-interface2").next();
-
- Vertex pInterface2Secondary = g.addV().property("aai-node-type", "p-interface").property("interface-name", "p-interface2").property("special-prop", "value")
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/TEST1/p-interfaces/p-interface/p-interface2").next();
-
- Vertex lInterface1 = g.addV().property("aai-node-type", "l-interface").property("interface-name", "l-interface1").property("special-prop", "value")
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/TEST1/p-interfaces/p-interface/p-interface2/l-interfaces/l-interface/l-interface1").next();
-
- Vertex lInterface1Canopi = g.addV().property("aai-node-type", "l-interface").property("interface-name", "l-interface1")
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/TEST1/p-interfaces/p-interface/p-interface2/l-interfaces/l-interface/l-interface1").next();
-
- Vertex logicalLink = g.addV().property("aai-node-type", "logical-link").property("link-name", "logical-link1")
- .property(AAIProperties.AAI_URI, "/network/logical-links/logical-link/logical-link1").next();
- Vertex pserverCanopi = g.addV().property("aai-node-type", "pserver").property("hostname", "TEST1")
- .property("source-of-truth", "CANOPI-WS").property("fqdn", "test2.com").property("test-list", "value2").next();
-
- Vertex complex1 = g.addV().property("aai-node-type", "complex").property("physical-location-id", "complex1")
- .property("source-of-truth", "RO").next();
-
- Vertex complex2 = g.addV().property("aai-node-type", "complex").property("physical-location-id", "complex2")
- .property("source-of-truth", "RCT").next();
-
- Vertex vserver1 = g.addV().property("aai-node-type", "vserver").property("vserver-id", "vserver1")
- .property("source-of-truth", "RO").next();
-
- Vertex vserver2 = g.addV().property("aai-node-type", "vserver").property("vserver-id", "vserver2")
- .property("source-of-truth", "RCT").next();
- Vertex vserver3 = g.addV().property("aai-node-type", "vserver").property("vserver-id", "vserver3")
- .property("source-of-truth", "RCT").next();
- Vertex vserver4 = g.addV().property("aai-node-type", "vserver").property("vserver-id", "vserver4")
- .property("source-of-truth", "RCT").next();
- Vertex vserver5 = g.addV().property("aai-node-type", "vserver").property("vserver-id", "vserver5")
- .property("source-of-truth", "RCT").next();
-
-
- rules.addEdge(g, pserverSkeleton, complex1);
- rules.addEdge(g, pserverSkeleton, vserver1);
- rules.addEdge(g, pserverSkeleton, vserver2);
- rules.addTreeEdge(g, pserverSkeleton, pInterface1);
- rules.addTreeEdge(g, pserverSkeleton, pInterface2Secondary);
- rules.addTreeEdge(g, pInterface2Secondary, lInterface1);
- rules.addEdge(g, lInterface1, logicalLink);
- rules.addEdge(g, pserverCanopi, complex2);
- rules.addEdge(g, pserverCanopi, vserver3);
- rules.addEdge(g, pserverCanopi, vserver4);
- rules.addEdge(g, pserverCanopi, vserver5);
- rules.addTreeEdge(g, pserverCanopi, pInterface2);
- rules.addTreeEdge(g, pInterface2, lInterface1Canopi);
-
- Map<String, Set<String>> forceCopy = new HashMap<>();
- Set<String> forceSet = new HashSet<>();
- forceSet.add("fqdn");
- forceCopy.put("pserver", forceSet);
-
- TransactionalGraphEngine spy = spy(dbEngine);
- TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
- GraphTraversalSource traversal = g;
- GraphTraversalSource readOnly = g;
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- when(adminSpy.getReadOnlyTraversalSource()).thenReturn(readOnly);
- DBSerializer serializer = new DBSerializer(version, spy, introspectorFactoryType, "Merge test");
-
- VertexMerge merge = new VertexMerge.Builder(loader, spy, serializer).build();
- merge.performMerge(pserverCanopi, pserverSkeleton, forceCopy);
- }
-
- @After
- public void cleanUp() {
- tx.tx().rollback();
- graph.close();
- }
-
- @Test
- public void run() throws UnsupportedEncodingException {
-
- assertEquals("pserver merged", false, g.V().has("hostname", "TEST1").has("source-of-truth", "AAI-EXTENSIONS").hasNext());
- assertThat("pserver list merge", Arrays.asList("value1", "value2"), containsInAnyOrder(g.V().has("hostname", "TEST1").values("test-list").toList().toArray()));
- assertEquals("canopi pserver has one edge to vserver2", 1, g.V().has("hostname", "TEST1").both().has("vserver-id", "vserver2").toList().size());
- assertEquals("canopi pserver has one edge to vserver1", 1, g.V().has("hostname", "TEST1").both().has("vserver-id", "vserver1").toList().size());
- assertEquals("canopi pserver retained edge to complex2", true, g.V().has("hostname", "TEST1").both().has("physical-location-id", "complex2").hasNext());
- assertEquals("canopi pserver received forced prop", "test1.com", g.V().has("hostname", "TEST1").values("fqdn").next());
- assertEquals("pserver skeleton child copied", true, g.V().has("hostname", "TEST1").both().has("interface-name", "p-interface1").hasNext());
- assertEquals("pserver skeleton child merged", true, g.V().has("hostname", "TEST1").both().has("interface-name", "p-interface2").has("special-prop", "value").hasNext());
- assertEquals("l-interface child merged", true, g.V().has("hostname", "TEST1").both().has("interface-name", "p-interface2").both().has("interface-name", "l-interface1").has("special-prop", "value").hasNext());
- assertEquals("l-interface child cousin edge merged", true, g.V().has("hostname", "TEST1").both().has("interface-name", "p-interface2").both().has("interface-name", "l-interface1").both().has("link-name", "logical-link1").hasNext());
- assertEquals("one l-interface1 found", new Long(1), g.V().has("interface-name", "l-interface1").count().next());
- assertEquals("one p-interface2 found", new Long(1), g.V().has("interface-name", "p-interface2").count().next());
-
- }
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/migration/v12/ContainmentDeleteOtherVPropertyMigrationTest.java b/aai-resources/src/test/java/org/onap/aai/migration/v12/ContainmentDeleteOtherVPropertyMigrationTest.java
deleted file mode 100644
index f80229c..0000000
--- a/aai-resources/src/test/java/org/onap/aai/migration/v12/ContainmentDeleteOtherVPropertyMigrationTest.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.migration.v12;
-
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.schema.JanusGraphManagement;
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
-import org.apache.tinkerpop.gremlin.structure.Edge;
-import org.apache.tinkerpop.gremlin.structure.Graph;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.onap.aai.AAISetup;
-import org.onap.aai.dbmap.DBConnectionType;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.introspection.Version;
-import org.onap.aai.serialization.db.AAIDirection;
-import org.onap.aai.serialization.db.EdgeProperty;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.JanusGraphDBEngine;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-public class ContainmentDeleteOtherVPropertyMigrationTest extends AAISetup {
-
- private final static Version version = Version.v12;
- private final static ModelType introspectorFactoryType = ModelType.MOXY;
- private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL;
- private final static DBConnectionType type = DBConnectionType.REALTIME;
- private Loader loader;
- private TransactionalGraphEngine dbEngine;
- private JanusGraph graph;
- private ContainmentDeleteOtherVPropertyMigration migration;
- private GraphTraversalSource g;
- private Graph tx;
-
- @Before
- public void setUp() throws Exception {
- graph = JanusGraphFactory.build().set("storage.backend","inmemory").open();
- JanusGraphManagement janusgraphManagement = graph.openManagement();
- tx = graph.newTransaction();
- g = tx.traversal();
- loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
- Vertex v = g.addV().property("aai-node-type", "generic-vnf")
- .property("vnf-id", "delcontains-test-vnf")
- .next();
- Vertex v2 = g.addV().property("aai-node-type", "l-interface")
- .property("interface-name", "delcontains-test-lint")
- .next();
- Edge e = v.addEdge("hasLInterface", v2, EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString(),
- EdgeProperty.DELETE_OTHER_V.toString(), AAIDirection.NONE.toString());
-
- Vertex v3 = g.addV().property("aai-node-type", "allotted-resource").next();
-
- Edge e2 = v2.addEdge("uses", v3, EdgeProperty.CONTAINS.toString(), AAIDirection.NONE.toString(),
- EdgeProperty.DELETE_OTHER_V.toString(), AAIDirection.NONE.toString());
- TransactionalGraphEngine spy = spy(dbEngine);
- TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
- GraphTraversalSource traversal = g;
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- Mockito.doReturn(janusgraphManagement).when(adminSpy).getManagementSystem();
- migration = new ContainmentDeleteOtherVPropertyMigration(spy, "/edgeMigrationTestRules.json");
- migration.run();
- }
-
- @After
- public void cleanUp() {
- tx.tx().rollback();
- graph.close();
- }
-
- @Test
- public void run() {
- assertEquals("del other now OUT", true,
- g.E().hasLabel("hasLInterface").has(EdgeProperty.DELETE_OTHER_V.toString(), AAIDirection.OUT.toString()).hasNext());
- assertEquals("contains val still same", true,
- g.E().hasLabel("hasLInterface").has(EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString()).hasNext());
- assertEquals("non-containment unchanged", true,
- g.E().hasLabel("uses").has(EdgeProperty.DELETE_OTHER_V.toString(), AAIDirection.NONE.toString()).hasNext());
- }
-
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/migration/v12/MigrateDataFromASDCToConfigurationTest.java b/aai-resources/src/test/java/org/onap/aai/migration/v12/MigrateDataFromASDCToConfigurationTest.java
deleted file mode 100644
index 4fbed4c..0000000
--- a/aai-resources/src/test/java/org/onap/aai/migration/v12/MigrateDataFromASDCToConfigurationTest.java
+++ /dev/null
@@ -1,172 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.migration.v12;
-
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.JanusGraphTransaction;
-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.onap.aai.AAISetup;
-import org.onap.aai.dbmap.DBConnectionType;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.introspection.Version;
-import org.onap.aai.serialization.db.EdgeRules;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.JanusGraphDBEngine;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotEquals;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-public class MigrateDataFromASDCToConfigurationTest extends AAISetup {
-
- private final static Version version = Version.v12;
- private final static ModelType introspectorFactoryType = ModelType.MOXY;
- private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL;
- private final static DBConnectionType type = DBConnectionType.REALTIME;
- private Loader loader;
- private TransactionalGraphEngine dbEngine;
- private JanusGraph graph;
- private MigrateDataFromASDCToConfiguration migration;
- private EdgeRules rules;
- private GraphTraversalSource g;
- private JanusGraphTransaction tx;
- Vertex configuration;
- Vertex configuration2;
- Vertex configuration3;
- Vertex configuration4;
-
- private boolean success = true;
- private String entitlementPoolUuid = "";
- private final String PARENT_NODE_TYPE = "generic-vnf";
- private String VNT = "";
-
- @Before
- public void setUp() throws Exception {
- graph = JanusGraphFactory.build().set("storage.backend","inmemory").open();
- tx = graph.newTransaction();
- g = tx.traversal();
- loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
- rules = EdgeRules.getInstance();
- Vertex genericvnf1 = g.addV().property("aai-node-type", "generic-vnf")
- .property("vnf-id", "vnfId1")
- .property("vnf-type","vHNF")
- .next();
-
- Vertex genericvnf2 = g.addV().property("aai-node-type", "generic-vnf")
- .property("vnf-id", "vnfId2")
- .property("vnf-type","vHNF")
- .next();
-
- Vertex entitlement1 = g.addV().property("aai-node-type", "entitlement")
- .property("group-uuid", "some-uuid")
- .next();
-
- Vertex serviceInstance1 = g.addV().property("aai-node-type", "service-instance")
- .property("service-instance-id", "servinstanceTestId1")
- .next();
-
- configuration = g.addV().property("aai-node-type", "configuration")
- .property("configuration-id", "configurationIdGraph")
- .property("vendor-allowed-max-bandwidth", "20")
- .next();
- configuration3 = g.addV().property("aai-node-type", "configuration")
- .property("configuration-id", "configurationIdGraph3")
- .property("vendor-allowed-max-bandwidth", "15")
- .next();
- configuration2 = g.addV().property("aai-node-type", "configuration")
- .property("configuration-id", "configurationIdGraph2")
- .property("vendor-allowed-max-bandwidth", "25")
- .next();
- configuration4 = g.addV().property("aai-node-type", "configuration")
- .property("configuration-id", "configurationIdGraph4")
- .property("vendor-allowed-max-bandwidth", "50")
- .next();
-
- rules.addTreeEdge(g, genericvnf1, entitlement1);
- rules.addEdge(g, genericvnf1, serviceInstance1);
- rules.addEdge(g, serviceInstance1, configuration);
- rules.addEdge(g, serviceInstance1, configuration3);
-
-
- rules.addEdge(g, genericvnf2, configuration2);
-
-
- TransactionalGraphEngine spy = spy(dbEngine);
- TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
- GraphTraversalSource traversal = g;
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- migration = new MigrateDataFromASDCToConfiguration(spy);
- migration.run();
- }
-
-
- @After
- public void cleanUp() {
- tx.rollback();
- graph.close();
- }
-
-
- /***
- * checks if the VNt value was updated and if theres a second configuration object it is also to be modified
- */
-
- @Test
- public void confirmVNtValueChanged() {
-
- assertEquals("1000",configuration.property("vendor-allowed-max-bandwidth").value());
- assertEquals("1000",configuration3.property("vendor-allowed-max-bandwidth").value());
-
- }
-
- /***
- * checks to see if the entitlement object is missing the configuration objects should not be modified at all
- */
- @Test
- public void missingEntitlementObject() {
- assertEquals("25",configuration2.property("vendor-allowed-max-bandwidth").value());
- }
- /***
- * checks to see if there's a configuration object not connected to anything it should not be modified at all
- */
-
- @Test
- public void confirmConfiguration4notchanged() {
- assertEquals("50",configuration4.property("vendor-allowed-max-bandwidth").value());
- }
-
-
-
-
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/migration/v12/MigrateServiceInstanceToConfigurationTest.java b/aai-resources/src/test/java/org/onap/aai/migration/v12/MigrateServiceInstanceToConfigurationTest.java
deleted file mode 100644
index b07c728..0000000
--- a/aai-resources/src/test/java/org/onap/aai/migration/v12/MigrateServiceInstanceToConfigurationTest.java
+++ /dev/null
@@ -1,410 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.migration.v12;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-import java.util.Optional;
-
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
-import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.onap.aai.AAISetup;
-import org.onap.aai.dbmap.DBConnectionType;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.introspection.Version;
-import org.onap.aai.serialization.db.EdgeRules;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.JanusGraphDBEngine;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.JanusGraphTransaction;
-
-public class MigrateServiceInstanceToConfigurationTest extends AAISetup {
-
- private final static Version version = Version.v12;
- 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;
- private static JanusGraph graph;
- private static MigrateServiceInstanceToConfiguration migration;
- private static JanusGraphTransaction tx;
- private static GraphTraversalSource g;
- private static EdgeRules rules;
-
- @BeforeClass
- public static void setUp() throws Exception {
- graph = JanusGraphFactory.build().set("storage.backend","inmemory").open();
- tx = graph.newTransaction();
- g = tx.traversal();
- loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
- rules = EdgeRules.getInstance();
-
- Vertex customer1 = g.addV()
- .property("aai-node-type", "customer")
- .property("global-customer-id", "customer-id-1")
- .property("subscriber-type", "CUST")
- .next();
-
- Vertex customer2 = g.addV()
- .property("aai-node-type", "customer")
- .property("global-customer-id", "customer-id-2")
- .property("subscriber-type", "CUST")
- .next();
-
- Vertex customer3 = g.addV()
- .property("aai-node-type", "customer")
- .property("global-customer-id", "customer-id-3")
- .property("subscriber-type", "CUST")
- .next();
-
- Vertex customer4 = g.addV()
- .property("aai-node-type", "customer")
- .property("global-customer-id", "customer-id-4")
- .property("subscriber-type", "CUST")
- .next();
-
- Vertex servSub1 = g.addV()
- .property("aai-node-type", "service-subscription")
- .property("service-type", "DHV")
- .next();
-
- Vertex servSub2 = g.addV()
- .property("aai-node-type", "service-subscription")
- .property("service-type", "OTHER")
- .next();
-
- Vertex servSub3 = g.addV()
- .property("aai-node-type", "service-subscription")
- .property("service-type", "DHV")
- .next();
-
- Vertex servSub4 = g.addV()
- .property("aai-node-type", "service-subscription")
- .property("service-type", "DHV")
- .next();
-
- Vertex servSub5 = g.addV()
- .property("aai-node-type", "service-subscription")
- .property("service-type", "DHV")
- .next();
-
- Vertex servInstance1 = g.addV()
- .property("aai-node-type", "service-instance")
- .property("service-instance-id", "service-inst-1")
- .property("operational-status", "activated")
- .property("bandwidth-total", "5")
- .next();
-
- Vertex servInstance2 = g.addV()
- .property("aai-node-type", "service-instance")
- .property("service-instance-id", "service-inst-2")
- .property("operational-status", "activated")
- .property("bandwidth-total", "8")
- .next();
-
- Vertex servInstance3 = g.addV()
- .property("aai-node-type", "service-instance")
- .property("service-instance-id", "service-inst-3")
- .property("operational-status", "activated")
- .property("bandwidth-total", "10")
- .next();
-
- Vertex servInstance4 = g.addV()
- .property("aai-node-type", "service-instance")
- .property("service-instance-id", "service-inst-4")
- .property("operational-status", "activated")
- .property("bandwidth-total", "15")
- .next();
-
- Vertex config1 = g.addV()
- .property("aai-node-type", "configuration")
- .property("configuration-id", "configuration-1")
- .property("configuration-type", "DHV")
- .property("tunnel-bandwidth", "7")
- .next();
-
- Vertex config2 = g.addV()
- .property("aai-node-type", "configuration")
- .property("configuration-id", "configuration-2")
- .property("configuration-type", "OTHER")
- .property("tunnel-bandwidth", "3")
- .next();
-
- Vertex config3 = g.addV()
- .property("aai-node-type", "configuration")
- .property("configuration-id", "configuration-3")
- .property("configuration-type", "OTHER")
- .property("tunnel-bandwidth", "2")
- .next();
-
- Vertex config4 = g.addV()
- .property("aai-node-type", "configuration")
- .property("configuration-id", "configuration-4")
- .property("configuration-type", "OTHER")
- .property("tunnel-bandwidth", "4")
- .next();
-
- // graph 1
- rules.addTreeEdge(g, customer1, servSub1);
- rules.addTreeEdge(g, customer1, servSub2);
- rules.addTreeEdge(g, servSub1, servInstance1);
- rules.addTreeEdge(g, servSub2, servInstance2);
-
- // graph 2
- rules.addTreeEdge(g, customer2, servSub3);
-
- // graph 3
- rules.addTreeEdge(g, customer3, servSub4);
- rules.addTreeEdge(g, servSub4, servInstance3);
- rules.addEdge(g, servInstance3, config1);
- rules.addEdge(g, servInstance3, config2);
-
- // graph 4
- rules.addTreeEdge(g, customer4, servSub5);
- rules.addTreeEdge(g, servSub5, servInstance4);
- rules.addEdge(g, servInstance4, config3);
- rules.addEdge(g, servInstance4, config4);
-
- TransactionalGraphEngine spy = spy(dbEngine);
- TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
-
- GraphTraversalSource traversal = g;
- GraphTraversalSource readOnly = tx.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance()));
- when (spy.tx()).thenReturn(tx);
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- when(adminSpy.getReadOnlyTraversalSource()).thenReturn(readOnly);
-
- migration = new MigrateServiceInstanceToConfiguration(spy);
- migration.run();
- }
-
- @AfterClass
- public static void cleanUp() {
- tx.tx().rollback();
- graph.close();
- }
-
- @Test
- public void testRun_createConfigNode() throws Exception {
- // check if graph nodes exist
- assertEquals("customer node exists", true,
- g.V().has("global-customer-id", "customer-id-1")
- .hasNext());
-
- assertEquals("service subscription node, service-type=DHV", true,
- g.V().has("global-customer-id", "customer-id-1")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .hasNext());
-
- assertEquals("service instance node, bandwidth-total=5", true,
- g.V().has("global-customer-id", "customer-id-1")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "service-inst-1").has("bandwidth-total", "5")
- .hasNext());
-
- // check if configuration node gets created
- assertEquals("configuration node exists", true,
- g.V().has("global-customer-id", "customer-id-1")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "service-inst-1")
- .out("org.onap.relationships.inventory.Uses").has("aai-node-type", "configuration")
- .hasNext());
-
- // check configuration type
- assertEquals("configuration node, configuration-type=DHV", true,
- g.V().has("global-customer-id", "customer-id-1")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "service-inst-1")
- .out("org.onap.relationships.inventory.Uses").has("aai-node-type", "configuration").has("configuration-type", "DHV")
- .hasNext());
-
- // check configuration tunnel-bandwidth
- assertEquals("configuration node, tunnel-bandwidth=5", true,
- g.V().has("global-customer-id", "customer-id-1")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "service-inst-1")
- .out("org.onap.relationships.inventory.Uses").has("aai-node-type", "configuration").has("tunnel-bandwidth", "5")
- .hasNext());
- }
-
- @Test
- public void testRun_configNodeNotCreated() throws Exception {
- // check if graph nodes exist
- assertEquals("customer node exists", true,
- g.V().has("global-customer-id", "customer-id-1")
- .hasNext());
-
- assertEquals("service subscription node, service-type=OTHER", true,
- g.V().has("global-customer-id", "customer-id-1")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "OTHER")
- .hasNext());
-
- assertEquals("service instance node, bandwidth-total=8", true,
- g.V().has("global-customer-id", "customer-id-1")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "OTHER")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "service-inst-2").has("bandwidth-total", "8")
- .hasNext());
-
- // configuration node should not be created
- assertEquals("configuration node does not exist", false,
- g.V().has("global-customer-id", "customer-id-1")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "OTHER")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "service-inst-2")
- .out("org.onap.relationships.inventory.Uses").has("aai-node-type", "configuration")
- .hasNext());
-
- // edge between service instance and configuration should not be created
- assertEquals("configuration node does not exist", false,
- g.V().has("global-customer-id", "customer-id-1")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "OTHER")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "service-inst-2")
- .out("org.onap.relationships.inventory.Uses").hasNext());
- }
-
- @Test
- public void testRun_noServiceInstance() throws Exception {
- // check if graph nodes exist
- assertEquals("customer node exists", true,
- g.V().has("global-customer-id", "customer-id-2")
- .hasNext());
-
- assertEquals("service subscription node, service-type=DHV", true,
- g.V().has("global-customer-id", "customer-id-2")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .hasNext());
-
- // no service instance nodes
- assertEquals("no service instance nodes", false,
- g.V().has("global-customer-id", "customer-id-2")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("aai-node-type", "service-instance")
- .hasNext());
- }
-
- @Test
- public void testRun_existingConfig() throws Exception {
- // check if graph nodes exist
- assertEquals("customer node exists", true,
- g.V().has("global-customer-id", "customer-id-3")
- .hasNext());
-
- assertEquals("service subscription node, service-type=DHV", true,
- g.V().has("global-customer-id", "customer-id-3")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .hasNext());
-
- assertEquals("service instance node, bandwidth-total=10", true,
- g.V().has("global-customer-id", "customer-id-3")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "service-inst-3").has("bandwidth-total", "10")
- .hasNext());
-
- assertEquals("configuration node with type DHV, tunnel-bandwidth changed to 10", true,
- g.V().has("global-customer-id", "customer-id-3")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "service-inst-3")
- .out("org.onap.relationships.inventory.Uses").has("aai-node-type", "configuration").has("tunnel-bandwidth", "10")
- .hasNext());
-
- assertEquals("configuration node with type OTHER, tunnel-bandwidth remains same", true,
- g.V().has("global-customer-id", "customer-id-3")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "service-inst-3")
- .out("org.onap.relationships.inventory.Uses").has("aai-node-type", "configuration").has("tunnel-bandwidth", "3")
- .hasNext());
- }
-
- @Test
- public void testRun_existingConfigNotDHV() throws Exception {
- // check if graph nodes exist
- assertEquals("customer node exists", true,
- g.V().has("global-customer-id", "customer-id-4")
- .hasNext());
-
- assertEquals("service subscription node, service-type=DHV", true,
- g.V().has("global-customer-id", "customer-id-4")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .hasNext());
-
- assertEquals("service instance node, bandwidth-total=15", true,
- g.V().has("global-customer-id", "customer-id-4")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "service-inst-4").has("bandwidth-total", "15")
- .hasNext());
-
- assertEquals("first configuration node with type OTHER, tunnel-bandwidth remains same", true,
- g.V().has("global-customer-id", "customer-id-4")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "service-inst-4")
- .out("org.onap.relationships.inventory.Uses").has("aai-node-type", "configuration").has("tunnel-bandwidth", "2")
- .hasNext());
-
- assertEquals("second configuration node with type OTHER, tunnel-bandwidth remains same", true,
- g.V().has("global-customer-id", "customer-id-4")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "service-inst-4")
- .out("org.onap.relationships.inventory.Uses").has("aai-node-type", "configuration").has("tunnel-bandwidth", "4")
- .hasNext());
-
- assertEquals("new configuration node created with type DHV, tunnel-bandwidth=15", true,
- g.V().has("global-customer-id", "customer-id-4")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "service-inst-4")
- .out("org.onap.relationships.inventory.Uses").has("aai-node-type", "configuration").has("tunnel-bandwidth", "15")
- .hasNext());
- }
-
- @Test
- public void testGetAffectedNodeTypes() {
- Optional<String[]> types = migration.getAffectedNodeTypes();
- Optional<String[]> expected = Optional.of(new String[]{"service-instance"});
-
- assertNotNull(types);
- assertArrayEquals(expected.get(), types.get());
- }
-
- @Test
- public void testGetMigrationName() {
- String migrationName = migration.getMigrationName();
-
- assertNotNull(migrationName);
- assertEquals("service-instance-to-configuration", migrationName);
- }
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/migration/v12/MigrateServiceInstanceToConfigurationTestPreMigrationMock.java b/aai-resources/src/test/java/org/onap/aai/migration/v12/MigrateServiceInstanceToConfigurationTestPreMigrationMock.java
deleted file mode 100644
index 498fd0c..0000000
--- a/aai-resources/src/test/java/org/onap/aai/migration/v12/MigrateServiceInstanceToConfigurationTestPreMigrationMock.java
+++ /dev/null
@@ -1,304 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.migration.v12;
-
-import static org.junit.Assert.assertArrayEquals;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-import java.util.Optional;
-
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
-import org.apache.tinkerpop.gremlin.process.traversal.strategy.verification.ReadOnlyStrategy;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.junit.AfterClass;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.onap.aai.AAISetup;
-import org.onap.aai.dbmap.DBConnectionType;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.introspection.Version;
-import org.onap.aai.serialization.db.EdgeRules;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.JanusGraphDBEngine;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.JanusGraphTransaction;
-
-public class MigrateServiceInstanceToConfigurationTestPreMigrationMock extends AAISetup {
-
- private final static Version version = Version.v12;
- 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;
- private static JanusGraph graph;
- private static MigrateServiceInstanceToConfiguration migration;
- private static JanusGraphTransaction tx;
- private static GraphTraversalSource g;
- private static EdgeRules rules;
-
- @BeforeClass
- public static void setUp() throws Exception {
- graph = JanusGraphFactory.build().set("storage.backend","inmemory").open();
- tx = graph.newTransaction();
- g = tx.traversal();
- loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
- rules = EdgeRules.getInstance();
-
- Vertex customer = g.addV()
- .property("aai-node-type", "customer")
- .property("global-customer-id", "customer-9972-BandwidthMigration")
- .property("subscriber-type", "CUST")
- .next();
-
- Vertex servSubSDNEI = g.addV()
- .property("aai-node-type", "service-subscription")
- .property("service-type", "SDN-ETHERNET-INTERNET")
- .next();
-
- Vertex servInstance22 = g.addV()
- .property("aai-node-type", "service-instance")
- .property("service-instance-id", "servInstance-9972-22-BandwidthMigration")
- .property("operational-status", "activated")
- .property("bandwidth-total", "bandwidth-total-22-BandwidthMigration")
- .next();
-
- Vertex servInstance11 = g.addV()
- .property("aai-node-type", "service-instance")
- .property("service-instance-id", "servInstance-9972-11-BandwidthMigration")
- .property("operational-status", "activated")
- .property("bandwidth-total", "bandwidth-total-11-BandwidthMigration")
- .next();
-
- Vertex servSubDHV = g.addV()
- .property("aai-node-type", "service-subscription")
- .property("service-type", "DHV")
- .next();
-
- Vertex servInstance4 = g.addV()
- .property("aai-node-type", "service-instance")
- .property("service-instance-id", "servInstance-9972-4-BandwidthMigration")
- .property("operational-status", "activated")
- .property("bandwidth-total", "bandwidth-total-4-BandwidthMigration")
- .next();
-
- Vertex servInstance1 = g.addV()
- .property("aai-node-type", "service-instance")
- .property("service-instance-id", "ServInstance-9972-1-BandwidthMigration")
- .property("operational-status", "activated")
- .property("bandwidth-total", "2380")
- .next();
-
- Vertex servInstance3 = g.addV()
- .property("aai-node-type", "service-instance")
- .property("service-instance-id", "servInstance-9972-3-BandwidthMigration")
- .property("operational-status", "activated")
- .property("bandwidth-total", "bandwidth-total-3-BandwidthMigration")
- .next();
-
- Vertex servInstance2 = g.addV()
- .property("aai-node-type", "service-instance")
- .property("service-instance-id", "servInstance-9972-2-BandwidthMigration")
- .property("operational-status", "activated")
- .property("bandwidth-total", "bandwidth-total-2-BandwidthMigration")
- .next();
-
- Vertex config1 = g.addV()
- .property("aai-node-type", "configuration")
- .property("configuration-id", "9972-config-LB1113")
- .property("configuration-type", "DHV")
- .property("tunnel-bandwidth", "12")
- .next();
-
- Vertex config2 = g.addV()
- .property("aai-node-type", "configuration")
- .property("configuration-id", "9972-1config-LB1113")
- .property("configuration-type", "configuration-type1-9972")
- .next();
-
- Vertex allottedResource = g.addV()
- .property("aai-node-type", "allotted-resource")
- .property("id", "allResource-9972-BandwidthMigration")
- .next();
-
- rules.addTreeEdge(g, customer, servSubSDNEI);
- rules.addTreeEdge(g, customer, servSubDHV);
- rules.addTreeEdge(g, servSubSDNEI, servInstance22);
- rules.addTreeEdge(g, servSubSDNEI, servInstance11);
- rules.addTreeEdge(g, servSubDHV, servInstance4);
- rules.addTreeEdge(g, servSubDHV, servInstance1);
- rules.addTreeEdge(g, servSubDHV, servInstance3);
- rules.addTreeEdge(g, servSubDHV, servInstance2);
- rules.addEdge(g, servInstance1, allottedResource);
- rules.addEdge(g, servInstance1, config1);
- rules.addEdge(g, servInstance2, config2);
-
- TransactionalGraphEngine spy = spy(dbEngine);
- TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
-
- GraphTraversalSource traversal = g;
- GraphTraversalSource readOnly = tx.traversal(GraphTraversalSource.build().with(ReadOnlyStrategy.instance()));
- when (spy.tx()).thenReturn(tx);
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- when(adminSpy.getReadOnlyTraversalSource()).thenReturn(readOnly);
-
- migration = new MigrateServiceInstanceToConfiguration(spy);
- migration.run();
- }
-
- @AfterClass
- public static void cleanUp() {
- tx.tx().rollback();
- graph.close();
- }
-
- @Test
- public void testRun() throws Exception {
- // check if graph nodes exist
- assertEquals("customer node exists", true,
- g.V().has("global-customer-id", "customer-9972-BandwidthMigration")
- .hasNext());
-
- assertEquals("service subscription node, service-type=SDN-ETHERNET-INTERNET", true,
- g.V().has("global-customer-id", "customer-9972-BandwidthMigration")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "SDN-ETHERNET-INTERNET")
- .hasNext());
-
- assertEquals("service instance node, bandwidth-total=bandwidth-total-22-BandwidthMigration", true,
- g.V().has("global-customer-id", "customer-9972-BandwidthMigration")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "SDN-ETHERNET-INTERNET")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "servInstance-9972-22-BandwidthMigration")
- .has("bandwidth-total", "bandwidth-total-22-BandwidthMigration")
- .hasNext());
-
- assertEquals("service instance node, bandwidth-total=bandwidth-total-11-BandwidthMigration", true,
- g.V().has("global-customer-id", "customer-9972-BandwidthMigration")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "SDN-ETHERNET-INTERNET")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "servInstance-9972-11-BandwidthMigration")
- .has("bandwidth-total", "bandwidth-total-11-BandwidthMigration")
- .hasNext());
-
- assertEquals("service subscription node, service-type=DHV", true,
- g.V().has("global-customer-id", "customer-9972-BandwidthMigration")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .hasNext());
-
- assertEquals("service instance node, bandwidth-total=servInstance-9972-4-BandwidthMigration", true,
- g.V().has("global-customer-id", "customer-9972-BandwidthMigration")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "servInstance-9972-4-BandwidthMigration")
- .has("bandwidth-total", "bandwidth-total-4-BandwidthMigration")
- .hasNext());
-
- assertEquals("service instance node, bandwidth-total=ServInstance-9972-1-BandwidthMigration", true,
- g.V().has("global-customer-id", "customer-9972-BandwidthMigration")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "ServInstance-9972-1-BandwidthMigration")
- .has("bandwidth-total", "2380")
- .hasNext());
-
- assertEquals("service instance node, bandwidth-total=servInstance-9972-3-BandwidthMigration", true,
- g.V().has("global-customer-id", "customer-9972-BandwidthMigration")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "servInstance-9972-3-BandwidthMigration")
- .has("bandwidth-total", "bandwidth-total-3-BandwidthMigration")
- .hasNext());
-
- assertEquals("service instance node, bandwidth-total=servInstance-9972-2-BandwidthMigration", true,
- g.V().has("global-customer-id", "customer-9972-BandwidthMigration")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "servInstance-9972-2-BandwidthMigration")
- .has("bandwidth-total", "bandwidth-total-2-BandwidthMigration")
- .hasNext());
-
- assertEquals("configuration node with type=configuration-type1-9972, tunnel-bandwidth does not exist", true,
- g.V().has("global-customer-id", "customer-9972-BandwidthMigration")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "servInstance-9972-2-BandwidthMigration")
- .out("org.onap.relationships.inventory.Uses").has("aai-node-type", "configuration")
- .has("configuration-type", "configuration-type1-9972")
- .hasNext());
-
- // check if configuration node gets created for 2, 3, 4
- assertEquals("configuration node created with type=DHV, tunnel-bandwidth=servInstance-9972-4-BandwidthMigration", true,
- g.V().has("global-customer-id", "customer-9972-BandwidthMigration")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "servInstance-9972-4-BandwidthMigration")
- .out("org.onap.relationships.inventory.Uses").has("aai-node-type", "configuration")
- .has("configuration-type", "DHV").has("tunnel-bandwidth", "bandwidth-total-4-BandwidthMigration")
- .hasNext());
-
- assertEquals("configuration node created with type=DHV, tunnel-bandwidth=servInstance-9972-3-BandwidthMigration", true,
- g.V().has("global-customer-id", "customer-9972-BandwidthMigration")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "servInstance-9972-3-BandwidthMigration")
- .out("org.onap.relationships.inventory.Uses").has("aai-node-type", "configuration")
- .has("configuration-type", "DHV").has("tunnel-bandwidth", "bandwidth-total-3-BandwidthMigration")
- .hasNext());
-
- assertEquals("configuration node created with type=DHV, tunnel-bandwidth=servInstance-9972-2-BandwidthMigration", true,
- g.V().has("global-customer-id", "customer-9972-BandwidthMigration")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "servInstance-9972-2-BandwidthMigration")
- .out("org.onap.relationships.inventory.Uses").has("aai-node-type", "configuration")
- .has("configuration-type", "DHV").has("tunnel-bandwidth", "bandwidth-total-2-BandwidthMigration")
- .hasNext());
-
- // configuration modified for ServInstance-9972-1-BandwidthMigration
- assertEquals("configuration node modified for ServInstance-9972-1-BandwidthMigration, tunnel-bandwidth=2380", true,
- g.V().has("global-customer-id", "customer-9972-BandwidthMigration")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-type", "DHV")
- .in("org.onap.relationships.inventory.BelongsTo").has("service-instance-id", "ServInstance-9972-1-BandwidthMigration")
- .out("org.onap.relationships.inventory.Uses").has("aai-node-type", "configuration")
- .has("configuration-type", "DHV").has("tunnel-bandwidth", "2380")
- .hasNext());
- }
-
- @Test
- public void testGetAffectedNodeTypes() {
- Optional<String[]> types = migration.getAffectedNodeTypes();
- Optional<String[]> expected = Optional.of(new String[]{"service-instance"});
-
- assertNotNull(types);
- assertArrayEquals(expected.get(), types.get());
- }
-
- @Test
- public void testGetMigrationName() {
- String migrationName = migration.getMigrationName();
-
- assertNotNull(migrationName);
- assertEquals("service-instance-to-configuration", migrationName);
- }
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/migration/v12/SDWANSpeedChangeMigrationTest.java b/aai-resources/src/test/java/org/onap/aai/migration/v12/SDWANSpeedChangeMigrationTest.java
deleted file mode 100644
index 677050a..0000000
--- a/aai-resources/src/test/java/org/onap/aai/migration/v12/SDWANSpeedChangeMigrationTest.java
+++ /dev/null
@@ -1,379 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.migration.v12;
-
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.JanusGraphTransaction;
-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.onap.aai.AAISetup;
-import org.onap.aai.dbmap.DBConnectionType;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.introspection.Version;
-import org.onap.aai.serialization.db.EdgeRules;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.JanusGraphDBEngine;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-public class SDWANSpeedChangeMigrationTest extends AAISetup {
-
- private final static Version version = Version.v12;
- private final static ModelType introspectorFactoryType = ModelType.MOXY;
- private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL;
- private final static DBConnectionType type = DBConnectionType.REALTIME;
- private Loader loader;
- private TransactionalGraphEngine dbEngine;
- private JanusGraph graph;
- private SDWANSpeedChangeMigration migration;
- private EdgeRules rules;
- private GraphTraversalSource g;
- private JanusGraphTransaction tx;
- Vertex pLinkWan1;
- Vertex pLinkWan3;
- Vertex pLinkWan5;
- Vertex pLinkWan7;
-
-
-
- @Before
- public void setUp() throws Exception {
- graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
- tx = graph.newTransaction();
- g = tx.traversal();
- loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
- rules = EdgeRules.getInstance();
-
- Vertex servSub1 = g.addV().property("aai-node-type", "service-subscription")
- .property("service-type", "DHV")
- .next();
- Vertex servinst1 = g.addV().property("aai-node-type", "service-instance")
- .property("service-type", "DHV")
- .next();
- Vertex allotedRsrc1 = g.addV().property("aai-node-type", "allotted-resource")
- .property("id", "rsrc1")
- .next();
- Vertex servinst2 = g.addV().property("aai-node-type", "service-instance")
- .property("service-type", "VVIG")
- .next();
- Vertex servSub2 = g.addV().property("aai-node-type", "service-subscription")
- .property("service-type", "VVIG")
- .next();
-
- Vertex genericvnf1 = g.addV().property("aai-node-type", "generic-vnf")
- .property("vnf-id", "vnfId1")
- .next();
- Vertex vServer1 = g.addV().property("aai-node-type", "vserver")
- .next();
- Vertex pServer1 = g.addV().property("aai-node-type", "pserver")
- .next();
- Vertex pInterfaceWan1 = g.addV().property("aai-node-type", "p-interface")
- .property("interface-name", "ge-0/0/10")
- .next();
- Vertex tunnelXConnectAll_Wan1 = g.addV().property("aai-node-type", "tunnel-xconnect")
- .property("id", "txc1")
- .property("bandwidth-up-wan1", "300 Mbps")
- .property("bandwidth-down-wan1", "400 Mbps")
- .property("bandwidth-up-wan2", "500 Mbps")
- .property("bandwidth-down-wan2", "600 Mbps")
- .next();
-
- pLinkWan1 = g.addV().property("aai-node-type", "physical-link")
- .property("link-name", "pLinkWan1")
- .property("service-provider-bandwidth-up-value", "empty")
- .property("service-provider-bandwidth-up-units", "empty")
- .property("service-provider-bandwidth-down-value", "empty")
- .property("service-provider-bandwidth-down-units", "empty")
- .next();
- Vertex servSub3 = g.addV().property("aai-node-type", "service-subscription")
- .property("service-type", "DHV")
- .next();
- Vertex servinst3 = g.addV().property("aai-node-type", "service-instance")
- .property("service-type", "DHV")
- .next();
- Vertex allotedRsrc3 = g.addV().property("aai-node-type", "allotted-resource")
- .property("id", "rsrc1")
- .next();
- Vertex servinst4 = g.addV().property("aai-node-type", "service-instance")
- .property("service-type", "VVIG")
- .next();
- Vertex servSub4 = g.addV().property("aai-node-type", "service-subscription")
- .property("service-type", "VVIG")
- .next();
-
- Vertex genericvnf3 = g.addV().property("aai-node-type", "generic-vnf")
- .property("vnf-id", "vnfId1")
- .next();
- Vertex vServer3 = g.addV().property("aai-node-type", "vserver")
- .next();
- Vertex pServer3 = g.addV().property("aai-node-type", "pserver")
- .next();
- Vertex pInterfaceWan3 = g.addV().property("aai-node-type", "p-interface")
- .property("interface-name", "ge-0/0/11")
- .next();
- Vertex tunnelXConnectAll_Wan3 = g.addV().property("aai-node-type", "tunnel-xconnect")
- .property("id", "txc3")
- .property("bandwidth-up-wan1", "300 Mbps")
- .property("bandwidth-down-wan1", "400 Mbps")
- .property("bandwidth-up-wan2", "500 Mbps")
- .property("bandwidth-down-wan2", "600 Mbps")
- .next();
-
- pLinkWan3 = g.addV().property("aai-node-type", "physical-link")
- .property("link-name", "pLinkWan3")
- .property("service-provider-bandwidth-up-value", "empty")
- .property("service-provider-bandwidth-up-units", "empty")
- .property("service-provider-bandwidth-down-value", "empty")
- .property("service-provider-bandwidth-down-units", "empty")
- .next();
-
-
- Vertex servSub5 = g.addV().property("aai-node-type", "service-subscription")
- .property("service-type", "DHV")
- .next();
- Vertex servinst5 = g.addV().property("aai-node-type", "service-instance")
- .property("service-type", "DHV")
- .next();
- Vertex allotedRsrc5 = g.addV().property("aai-node-type", "allotted-resource")
- .property("id", "rsrc1")
- .next();
- Vertex servinst6 = g.addV().property("aai-node-type", "service-instance")
- .property("service-type", "VVIG")
- .next();
- Vertex servSub6 = g.addV().property("aai-node-type", "service-subscription")
- .property("service-type", "VVIG")
- .next();
-
- Vertex genericvnf5 = g.addV().property("aai-node-type", "generic-vnf")
- .property("vnf-id", "vnfId1")
- .next();
- Vertex vServer5 = g.addV().property("aai-node-type", "vserver")
- .next();
- Vertex pServer5 = g.addV().property("aai-node-type", "pserver")
- .next();
- Vertex pInterfaceWan5 = g.addV().property("aai-node-type", "p-interface")
- .property("interface-name", "ge-0/0/10")
- .next();
- Vertex tunnelXConnectAll_Wan5 = g.addV().property("aai-node-type", "tunnel-xconnect")
- .property("id", "txc5")
- .property("bandwidth-up-wan1", "")
- .property("bandwidth-down-wan1", "")
- .property("bandwidth-up-wan2", "500 Mbps")
- .property("bandwidth-down-wan2", "600 Mbps")
- .next();
-
- pLinkWan5 = g.addV().property("aai-node-type", "physical-link")
- .property("link-name", "pLinkWan5")
- .property("service-provider-bandwidth-up-value", "")
- .property("service-provider-bandwidth-up-units", "")
- .property("service-provider-bandwidth-down-value", "")
- .property("service-provider-bandwidth-down-units", "")
- .next();
-
-
- Vertex servSub7 = g.addV().property("aai-node-type", "service-subscription")
- .property("service-type", "DHV")
- .next();
- Vertex servinst7 = g.addV().property("aai-node-type", "service-instance")
- .property("service-type", "DHV")
- .next();
- Vertex allotedRsrc7 = g.addV().property("aai-node-type", "allotted-resource")
- .property("id", "rsrc1")
- .next();
- Vertex servinst9 = g.addV().property("aai-node-type", "service-instance")
- .property("service-type", "VVIG")
- .next();
- Vertex servSub9 = g.addV().property("aai-node-type", "service-subscription")
- .property("service-type", "VVIG")
- .next();
-
- Vertex genericvnf7 = g.addV().property("aai-node-type", "generic-vnf")
- .property("vnf-id", "vnfId1")
- .next();
- Vertex vServer7 = g.addV().property("aai-node-type", "vserver")
- .next();
- Vertex pServer7 = g.addV().property("aai-node-type", "pserver")
- .next();
- Vertex pInterfaceWan7 = g.addV().property("aai-node-type", "p-interface")
- .property("interface-name", "ge-0/0/11")
- .next();
- Vertex tunnelXConnectAll_Wan7 = g.addV().property("aai-node-type", "tunnel-xconnect")
- .property("id", "txc7")
- .property("bandwidth-up-wan1", "300 Mbps")
- .property("bandwidth-down-wan1", "400 Mbps")
- .property("bandwidth-up-wan2", "")
- .property("bandwidth-down-wan2", "")
- .next();
-
- pLinkWan7 = g.addV().property("aai-node-type", "physical-link")
- .property("link-name", "pLinkWan5")
- .property("service-provider-bandwidth-up-value", "")
- .property("service-provider-bandwidth-up-units", "")
- .property("service-provider-bandwidth-down-value", "")
- .property("service-provider-bandwidth-down-units", "")
- .next();
-
-
-
- rules.addTreeEdge(g, servSub1, servinst1);
- rules.addEdge(g, servinst1, allotedRsrc1);
- rules.addTreeEdge(g, servinst2, servSub2);
- rules.addTreeEdge(g, allotedRsrc1, servinst2);
-
- rules.addTreeEdge(g, allotedRsrc1, tunnelXConnectAll_Wan1);
-
-
- rules.addEdge(g, servinst1, genericvnf1);
- rules.addEdge(g, genericvnf1, vServer1);
- rules.addEdge(g, vServer1, pServer1);
- rules.addTreeEdge(g, pServer1, pInterfaceWan1);
- rules.addEdge(g, pInterfaceWan1, pLinkWan1);
-
- rules.addTreeEdge(g, servSub3, servinst3);
- rules.addEdge(g, servinst3, allotedRsrc3);
- rules.addTreeEdge(g, servinst4, servSub4);
- rules.addTreeEdge(g, allotedRsrc3, servinst4);
-
- rules.addTreeEdge(g, allotedRsrc3, tunnelXConnectAll_Wan3);
-
-
- rules.addEdge(g, servinst3, genericvnf3);
- rules.addEdge(g, genericvnf3, vServer3);
- rules.addEdge(g, vServer3, pServer3);
- rules.addTreeEdge(g, pServer3, pInterfaceWan3);
- rules.addEdge(g, pInterfaceWan3, pLinkWan3);
-
-
- rules.addTreeEdge(g, servSub5, servinst5);
- rules.addEdge(g, servinst5, allotedRsrc5);
- rules.addTreeEdge(g, servinst6, servSub6);
- rules.addTreeEdge(g, allotedRsrc5, servinst6);
-
- rules.addTreeEdge(g, allotedRsrc5, tunnelXConnectAll_Wan5);
-
-
- rules.addEdge(g, servinst5, genericvnf5);
- rules.addEdge(g, genericvnf5, vServer5);
- rules.addEdge(g, vServer5, pServer5);
- rules.addTreeEdge(g, pServer5, pInterfaceWan5);
- rules.addEdge(g, pInterfaceWan5, pLinkWan5);
-
- rules.addTreeEdge(g, servSub7, servinst7);
- rules.addEdge(g, servinst7, allotedRsrc7);
- rules.addTreeEdge(g, servinst9, servSub9);
- rules.addTreeEdge(g, allotedRsrc7, servinst9);
-
- rules.addTreeEdge(g, allotedRsrc7, tunnelXConnectAll_Wan7);
-
-
- rules.addEdge(g, servinst7, genericvnf7);
- rules.addEdge(g, genericvnf7, vServer7);
- rules.addEdge(g, vServer7, pServer7);
- rules.addTreeEdge(g, pServer7, pInterfaceWan7);
- rules.addEdge(g, pInterfaceWan7, pLinkWan7);
-
-
- TransactionalGraphEngine spy = spy(dbEngine);
- TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
- GraphTraversalSource traversal = g;
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- migration = new SDWANSpeedChangeMigration(spy);
- migration.run();
- }
-
-
- @After
- public void cleanUp() {
- tx.rollback();
- graph.close();
- }
-
-
- /***
- * Checks to see if the Wan1 properties were updated in the physical link
- */
-
- @Test
- public void ConfirmWan1Changes() {
-
- assertEquals("300", pLinkWan1.property("service-provider-bandwidth-up-value").value().toString());
- assertEquals("Mbps", pLinkWan1.property("service-provider-bandwidth-up-units").value().toString());
- assertEquals("400", pLinkWan1.property("service-provider-bandwidth-down-value").value().toString());
- assertEquals("Mbps", pLinkWan1.property("service-provider-bandwidth-down-units").value().toString());
-
- }
-
- /***
- * Checks to see if the Wan2 properties were updated in the physical link
- */
- @Test
- public void ConfirmWan2Changes() {
-
- assertEquals("500", pLinkWan3.property("service-provider-bandwidth-up-value").value().toString());
- assertEquals("Mbps", pLinkWan3.property("service-provider-bandwidth-up-units").value().toString());
- assertEquals("600", pLinkWan3.property("service-provider-bandwidth-down-value").value().toString());
- assertEquals("Mbps", pLinkWan3.property("service-provider-bandwidth-down-units").value().toString());
-
- }
-
- /***
- * if tunnel xconncets missing bandwidth up 1 value the plink should not be updated
- */
-
- @Test
- public void Wan1EmptyNoChanges() {
-
- assertEquals("", pLinkWan5.property("service-provider-bandwidth-up-value").value().toString());
- assertEquals("", pLinkWan5.property("service-provider-bandwidth-up-units").value().toString());
- assertEquals("", pLinkWan5.property("service-provider-bandwidth-down-value").value().toString());
- assertEquals("", pLinkWan5.property("service-provider-bandwidth-down-units").value().toString());
-
- }
-
- /***
- * if tunnel xconncets missing bandwidth up 2 value the plink should not be updated
- */
-
- @Test
- public void Wan2EmptyNoChanges() {
-
- assertEquals("", pLinkWan7.property("service-provider-bandwidth-up-value").value().toString());
- assertEquals("", pLinkWan7.property("service-provider-bandwidth-up-units").value().toString());
- assertEquals("", pLinkWan7.property("service-provider-bandwidth-down-value").value().toString());
- assertEquals("", pLinkWan7.property("service-provider-bandwidth-down-units").value().toString());
-
- }
-
-
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/migration/v12/ToscaMigrationTest.java b/aai-resources/src/test/java/org/onap/aai/migration/v12/ToscaMigrationTest.java
deleted file mode 100644
index 9e21947..0000000
--- a/aai-resources/src/test/java/org/onap/aai/migration/v12/ToscaMigrationTest.java
+++ /dev/null
@@ -1,181 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.migration.v12;
-
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.schema.JanusGraphManagement;
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
-import org.apache.tinkerpop.gremlin.structure.Graph;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.onap.aai.AAISetup;
-import org.onap.aai.db.props.AAIProperties;
-import org.onap.aai.dbmap.DBConnectionType;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.introspection.Version;
-import org.onap.aai.serialization.db.AAIDirection;
-import org.onap.aai.serialization.db.EdgeProperty;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.JanusGraphDBEngine;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-public class ToscaMigrationTest extends AAISetup {
-
- private final static Version version = Version.v12;
- private final static ModelType introspectorFactoryType = ModelType.MOXY;
- private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL;
- private final static DBConnectionType type = DBConnectionType.REALTIME;
- private Loader loader;
- private TransactionalGraphEngine dbEngine;
- private JanusGraph graph;
- private ToscaMigration migration;
- private GraphTraversalSource g;
- private Graph tx;
-
- @Before
- public void setUp() throws Exception {
- graph = JanusGraphFactory.build().set("storage.backend","inmemory").open();
- JanusGraphManagement janusgraphManagement = graph.openManagement();
- tx = graph.newTransaction();
- g = tx.traversal();
- loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
-
- Vertex gvnf = g.addV().property(AAIProperties.NODE_TYPE, "generic-vnf")
- .property("vnf-id", "toscaMigration-test-vnf")
- .next();
-
- Vertex lInterface = g.addV().property(AAIProperties.NODE_TYPE, "l-interface")
- .property("interface-name", "toscaMigration-test-lint")
- .next();
-
- Vertex logicalLink = g.addV().property(AAIProperties.NODE_TYPE, "logical-link")
- .property("link-name", "toscaMigration-logical-link")
- .next();
-
-
-
- gvnf.addEdge("hasLInterface", lInterface, EdgeProperty.CONTAINS.toString(), AAIDirection.OUT.toString(),
- EdgeProperty.DELETE_OTHER_V.toString(), AAIDirection.NONE.toString());
-
- lInterface.addEdge("usesLogicalLink", logicalLink, EdgeProperty.CONTAINS.toString(), AAIDirection.NONE.toString(),
- EdgeProperty.DELETE_OTHER_V.toString(), AAIDirection.NONE.toString());
- lInterface.addEdge("sourceLInterface", logicalLink, EdgeProperty.CONTAINS.toString(), AAIDirection.NONE.toString(),
- EdgeProperty.DELETE_OTHER_V.toString(), AAIDirection.NONE.toString());
-
- Vertex pserver = g.addV("aai-node-type","pserver","hostname","a-name").next();
- Vertex vnfc = g.addV("aai-node-type","vnfc","vnfc-name","a-name").next();
- pserver.addEdge("blah", vnfc, EdgeProperty.CONTAINS.toString(), AAIDirection.NONE.toString(),
- EdgeProperty.DELETE_OTHER_V.toString(), AAIDirection.NONE.toString());
-
- TransactionalGraphEngine spy = spy(dbEngine);
- TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
- GraphTraversalSource traversal = g;
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- Mockito.doReturn(janusgraphManagement).when(adminSpy).getManagementSystem();
- migration = new ToscaMigration(spy);
- migration.run();
-
-
- }
-
- @After
- public void cleanUp() {
- tx.tx().rollback();
- graph.close();
- }
-
- @Test
- public void verifyVnfHasOnlyNewEdgeTest() {
-
- // We want to check that this edge has the expected new label and reversed direction from
- // what it was created with. NOTE - if the csv file changes what the new label is supposed
- // to be, then this test will need to be updated.
-
- assertEquals("edge direction and label were migrated", true,
- g.V().has(AAIProperties.NODE_TYPE, "generic-vnf").has("vnf-id", "toscaMigration-test-vnf").inE()
- .hasLabel("org.onap.relationships.inventory.BelongsTo").hasNext());
-
-
- assertEquals("if we look for old edge, it should be gone", false,
- g.V().has(AAIProperties.NODE_TYPE, "generic-vnf").has("vnf-id", "toscaMigration-test-vnf").outE()
- .hasLabel("hasLInterface").hasNext());
- }
-
- @Test
- public void verifyGraphHasNoOldEdgeLabelsTest() {
- assertEquals("Graph should have none of the old edge label"
- , Long.valueOf(0)
- , g.E().hasLabel("hasLInterface","usesLogicalLink").count().next());
- assertEquals("Graph should have none of the old edge label"
- , Long.valueOf(2)
- , g.E().hasLabel("org.onap.relationships.inventory.BelongsTo","tosca.relationships.network.LinksTo")
- .count().next());
- }
-
- @Test
- public void verifyGenericVnfHas1EdgeTest() {
- assertEquals("Generic vnf should have 1 edge"
- , Long.valueOf(1)
- , g.V().has(AAIProperties.NODE_TYPE, "generic-vnf")
- .both()
- .count().next());
-
- }
-
- @Test
- public void verifyLogicalLinkHas2EdgesTest() {
- assertEquals("Logical Link should have 2 edges"
- , Long.valueOf(2)
- , g.V().has(AAIProperties.NODE_TYPE, "logical-link")
- .both()
- .count().next());
-
- assertTrue("Logical Link has source edge"
- , g.V().has(AAIProperties.NODE_TYPE, "logical-link").bothE("org.onap.relationships.inventory.Source").hasNext());
-
- assertTrue("Logical Link has default edge"
- , g.V().has(AAIProperties.NODE_TYPE, "logical-link").bothE("tosca.relationships.network.LinksTo").hasNext());
-
- }
-
- @Test
- public void checkThatEdgeWithNoRulesDoesNotGetMigratedTest() {
- assertTrue("Edge with no rule did not get migrated ", g.E().hasLabel("blah").hasNext());
- }
-
-}
-
- \ No newline at end of file
diff --git a/aai-resources/src/test/java/org/onap/aai/migration/v13/MigrateInstanceGroupSubTypeTest.java b/aai-resources/src/test/java/org/onap/aai/migration/v13/MigrateInstanceGroupSubTypeTest.java
deleted file mode 100644
index a29fb6b..0000000
--- a/aai-resources/src/test/java/org/onap/aai/migration/v13/MigrateInstanceGroupSubTypeTest.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.migration.v13;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-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.onap.aai.AAISetup;
-import org.onap.aai.dbmap.DBConnectionType;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.introspection.Version;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.JanusGraphDBEngine;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.JanusGraphTransaction;
-
-
-public class MigrateInstanceGroupSubTypeTest extends AAISetup{
-
- private static final String SUB_TYPE_VALUE = "SubTypeValue";
- private final static Version version = Version.v13;
- private final static ModelType introspectorFactoryType = ModelType.MOXY;
- private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL;
- private final static DBConnectionType type = DBConnectionType.REALTIME;
- private Loader loader;
- private TransactionalGraphEngine dbEngine;
- private JanusGraph graph;
- private MigrateInstanceGroupSubType migration;
- private GraphTraversalSource g;
- private JanusGraphTransaction tx;
- Vertex instanceGroup;
- Vertex instanceGroupWithoutTSubType;
-
-
- @Before
- public void setUp() throws Exception {
- graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
- tx = graph.newTransaction();
- g = tx.traversal();
- loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
- instanceGroup = g.addV().property("aai-node-type", MigrateInstanceGroupSubType.INSTANCE_GROUP_NODE_TYPE)
- .property( MigrateInstanceGroupSubType.SUB_TYPE_PROPERTY, SUB_TYPE_VALUE)
- .next();
-
- instanceGroupWithoutTSubType = g.addV().property("aai-node-type", MigrateInstanceGroupSubType.INSTANCE_GROUP_NODE_TYPE)
- .next();
-
- TransactionalGraphEngine spy = spy(dbEngine);
- TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
- GraphTraversalSource traversal = g;
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- migration = new MigrateInstanceGroupSubType(spy);
- }
-
- @After
- public void cleanUp() {
- tx.rollback();
- graph.close();
- }
-
-
- /***
- * checks if the type/subtype property were renamed
- */
-
- @Test
- public void confirmTypeAndSubTypeWereRenamed() {
- migration.run();
-
- //instance group with sub-type
- assertEquals(SUB_TYPE_VALUE, instanceGroup.property(MigrateInstanceGroupSubType.INSTANCE_GROUP_ROLE_PROPERTY).value());
- assertFalse(instanceGroup.property(MigrateInstanceGroupSubType.SUB_TYPE_PROPERTY).isPresent());
-
- //instance group without subtype
- assertFalse(instanceGroupWithoutTSubType.property(MigrateInstanceGroupSubType.INSTANCE_GROUP_ROLE_PROPERTY).isPresent());
- assertFalse(instanceGroupWithoutTSubType.property(MigrateInstanceGroupSubType.SUB_TYPE_PROPERTY).isPresent());
- }
-} \ No newline at end of file
diff --git a/aai-resources/src/test/java/org/onap/aai/migration/v13/MigrateInstanceGroupTypeTest.java b/aai-resources/src/test/java/org/onap/aai/migration/v13/MigrateInstanceGroupTypeTest.java
deleted file mode 100644
index 11e5157..0000000
--- a/aai-resources/src/test/java/org/onap/aai/migration/v13/MigrateInstanceGroupTypeTest.java
+++ /dev/null
@@ -1,112 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.migration.v13;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertFalse;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
-
-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.onap.aai.AAISetup;
-import org.onap.aai.dbmap.DBConnectionType;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.introspection.LoaderFactory;
-import org.onap.aai.introspection.ModelType;
-import org.onap.aai.introspection.Version;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.JanusGraphDBEngine;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.JanusGraphTransaction;
-
-
-public class MigrateInstanceGroupTypeTest extends AAISetup{
-
- private static final String TYPE_VALUE = "TypeValue";
- private final static Version version = Version.v13;
- private final static ModelType introspectorFactoryType = ModelType.MOXY;
- private final static QueryStyle queryStyle = QueryStyle.TRAVERSAL;
- private final static DBConnectionType type = DBConnectionType.REALTIME;
- private Loader loader;
- private TransactionalGraphEngine dbEngine;
- private JanusGraph graph;
- private MigrateInstanceGroupType migration;
- private GraphTraversalSource g;
- private JanusGraphTransaction tx;
- Vertex instanceGroup;
- Vertex instanceGroupWithoutType;
-
-
- @Before
- public void setUp() throws Exception {
- graph = JanusGraphFactory.build().set("storage.backend", "inmemory").open();
- tx = graph.newTransaction();
- g = tx.traversal();
- loader = LoaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- type,
- loader);
- instanceGroup = g.addV().property("aai-node-type", MigrateInstanceGroupType.INSTANCE_GROUP_NODE_TYPE)
- .property( MigrateInstanceGroupType.TYPE_PROPERTY, TYPE_VALUE)
- .next();
-
- instanceGroupWithoutType = g.addV().property("aai-node-type", MigrateInstanceGroupType.INSTANCE_GROUP_NODE_TYPE)
- .next();
-
- TransactionalGraphEngine spy = spy(dbEngine);
- TransactionalGraphEngine.Admin adminSpy = spy(dbEngine.asAdmin());
- GraphTraversalSource traversal = g;
- when(spy.asAdmin()).thenReturn(adminSpy);
- when(adminSpy.getTraversalSource()).thenReturn(traversal);
- migration = new MigrateInstanceGroupType(spy);
- }
-
- @After
- public void cleanUp() {
- tx.rollback();
- graph.close();
- }
-
-
- /***
- * checks if the type/subtype property were renamed
- */
-
- @Test
- public void confirmTypeAndSubTypeWereRenamed() {
- migration.run();
-
- //instance group with type
- assertEquals(TYPE_VALUE, instanceGroup.property(MigrateInstanceGroupType.INSTANCE_GROUP_TYPE_PROPERTY).value());
- assertFalse(instanceGroup.property(MigrateInstanceGroupType.TYPE_PROPERTY).isPresent());
-
- //instance group without type
- assertFalse(instanceGroupWithoutType.property(MigrateInstanceGroupType.INSTANCE_GROUP_TYPE_PROPERTY).isPresent());
- assertFalse(instanceGroupWithoutType.property(MigrateInstanceGroupType.TYPE_PROPERTY).isPresent());
- }
-} \ No newline at end of file
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/AbstractSpringRestTest.java b/aai-resources/src/test/java/org/onap/aai/rest/AbstractSpringRestTest.java
new file mode 100644
index 0000000..ab9fdd1
--- /dev/null
+++ b/aai-resources/src/test/java/org/onap/aai/rest/AbstractSpringRestTest.java
@@ -0,0 +1,128 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 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.onap.aai.rest;
+
+import org.apache.tinkerpop.gremlin.process.traversal.P;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
+import org.janusgraph.core.JanusGraph;
+import org.janusgraph.core.JanusGraphTransaction;
+import org.junit.*;
+import org.onap.aai.ResourcesApp;
+import org.onap.aai.ResourcesTestConfiguration;
+import org.onap.aai.config.PropertyPasswordConfiguration;
+import org.onap.aai.dbmap.AAIGraph;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.nodes.NodeIngestor;
+import org.onap.aai.util.AAIConfig;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.boot.context.embedded.LocalServerPort;
+import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.context.annotation.Import;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpHeaders;
+import org.springframework.http.MediaType;
+import org.springframework.test.context.ContextConfiguration;
+import org.springframework.test.context.TestPropertySource;
+import org.springframework.test.context.junit4.rules.SpringClassRule;
+import org.springframework.test.context.junit4.rules.SpringMethodRule;
+import org.springframework.web.client.RestTemplate;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Base64;
+import java.util.Collections;
+
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = ResourcesApp.class)
+@TestPropertySource(locations = "classpath:application-test.properties")
+@ContextConfiguration(initializers = PropertyPasswordConfiguration.class)
+@Import(ResourcesTestConfiguration.class)
+public abstract class AbstractSpringRestTest {
+
+ @ClassRule
+ public static final SpringClassRule springClassRule = new SpringClassRule();
+
+ @Rule
+ public final SpringMethodRule springMethodRule = new SpringMethodRule();
+
+ @Autowired
+ protected RestTemplate restTemplate;
+
+ @Autowired
+ protected NodeIngestor nodeIngestor;
+
+ @LocalServerPort
+ protected int randomPort;
+
+ protected HttpEntity httpEntity;
+
+ protected String baseUrl;
+ protected HttpHeaders headers ;
+
+ @BeforeClass
+ public static void setupConfig() throws AAIException {
+ System.setProperty("AJSC_HOME", "./");
+ System.setProperty("BUNDLECONFIG_DIR", "src/main/resources/");
+ }
+
+ @Before
+ public void setup() throws AAIException, UnsupportedEncodingException {
+
+ AAIConfig.init();
+ AAIGraph.getInstance();
+
+ headers = new HttpHeaders();
+
+ String authorization = Base64.getEncoder().encodeToString("AAI:AAI".getBytes("UTF-8"));
+
+ headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
+ headers.setContentType(MediaType.APPLICATION_JSON);
+ headers.add("Real-Time", "true");
+ headers.add("X-FromAppId", "JUNIT");
+ headers.add("X-TransactionId", "JUNIT");
+
+ headers.add("Authorization", "Basic " + authorization);
+ httpEntity = new HttpEntity(headers);
+ baseUrl = "https://localhost:" + randomPort;
+ }
+
+ @After
+ public void tearDown(){
+
+ JanusGraph janusGraph = AAIGraph.getInstance().getGraph();
+ JanusGraphTransaction transaction = janusGraph.newTransaction();
+
+ boolean success = true;
+
+ try {
+ GraphTraversalSource g = transaction.traversal();
+ g.V().has("source-of-truth", P.within("JUNIT", "AAI-EXTENSIONS"))
+ .toList()
+ .stream()
+ .forEach(v -> v.remove());
+ } catch(Exception ex){
+ success = false;
+ } finally {
+ if(success){
+ transaction.commit();
+ } else {
+ transaction.rollback();
+ }
+ }
+ }
+}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/BulkAddConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/BulkAddConsumerTest.java
index 350a011..6e98a39 100644
--- a/aai-resources/src/test/java/org/onap/aai/rest/BulkAddConsumerTest.java
+++ b/aai-resources/src/test/java/org/onap/aai/rest/BulkAddConsumerTest.java
@@ -28,11 +28,9 @@ import javax.ws.rs.core.Response;
import org.apache.commons.lang3.StringUtils;
import org.junit.Test;
-import org.onap.aai.introspection.Version;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
-
public class BulkAddConsumerTest extends BulkProcessorTestAbstraction {
private static final EELFLogger logger = EELFManager.getInstance().getLogger(BulkAddConsumerTest.class.getName());
@@ -137,6 +135,6 @@ public class BulkAddConsumerTest extends BulkProcessorTestAbstraction {
@Override
protected String getUri() {
- return "/aai/" + Version.getLatest().toString() + "/bulkadd";
+ return "/aai/" + schemaVersions.getDefaultVersion().toString() + "/bulkadd";
}
}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java
index b6ec0ae..1d8702a 100644
--- a/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java
+++ b/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessConsumerTest.java
@@ -1,285 +1,298 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.rest;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Mockito.when;
-
-import java.io.IOException;
-
-import javax.ws.rs.core.Response;
-
-import org.apache.commons.lang3.StringUtils;
-import org.json.JSONException;
-import org.junit.Test;
-import org.onap.aai.introspection.Version;
-import org.skyscreamer.jsonassert.JSONAssert;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import org.springframework.mock.web.MockHttpServletRequest;
-
-public class BulkProcessConsumerTest extends BulkProcessorTestAbstraction {
-
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(BulkProcessConsumerTest.class.getName());
- private LegacyMoxyConsumer legacyMoxyConsumer;
-
- @Test
- public void bulkAddPayloadInBulkProcessTest() throws IOException {
-
- when(uriInfo.getPath()).thenReturn(uri);
- when(uriInfo.getPath(false)).thenReturn(uri);
-
- String payload = getBulkPayload("pserver-transactions");
- Response response = executeRequest(payload);
-
- assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus());
- assertEquals("Contains 3 {\"201\":null}", 3, StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}"));
- }
-
- @Test
- public void bulkProcessPayloadTest() throws IOException {
-
- when(uriInfo.getPath()).thenReturn(uri);
- when(uriInfo.getPath(false)).thenReturn(uri);
-
- String payload = getBulkPayload("pserver-bulk-process-transactions");
- Response response = executeRequest(payload);
-
- assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus());
- assertEquals("Contains 1 {\"201\":null}", 1, StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}"));
- assertEquals("Contains 1 {\"404\":\"{", 1, StringUtils.countMatches(response.getEntity().toString(), "{\"404\":\"{"));
- assertEquals("Contains 1 ERR.5.4.6114", 1, StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6114"));
- }
-
- @Test
- public void bulkProcessComplexDeletePayloadTest() throws IOException {
-
- when(uriInfo.getPath()).thenReturn(uri);
- when(uriInfo.getPath(false)).thenReturn(uri);
-
- String payload = getBulkPayload("complex-bulk-process-transactions");
- Response response = executeRequest(payload);
-
- System.out.println(response.getEntity().toString());
- assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus());
- assertEquals("Contains 0 {\"201\":null}", 0, StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}"));
- assertEquals("Contains 1 {\"404\":\"{", 1, StringUtils.countMatches(response.getEntity().toString(), "{\"404\":\"{"));
- assertEquals("Contains 1 ERR.5.4.6114", 1, StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6114"));
- }
-
- @Test
- public void testBulkDeletePserverAndComplexRelationship() throws IOException, JSONException {
-
- legacyMoxyConsumer = new LegacyMoxyConsumer();
-
- String pserverData = getPayload("payloads/relationship/pserver-bugfix.json");
- String complexData = getPayload("payloads/relationship/complex-bugfix.json");
-
- String hostname = "pserver-9876543210-77-jenkins";
- String physicalLocationId ="complex-987654321-77-jenkins";
-
- String pserverUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname);
- String complexUri = String.format("cloud-infrastructure/complexes/complex/%s", physicalLocationId);
-
- doSetupResource(pserverUri, pserverData);
- doSetupResource(complexUri, complexData);
-
- String complexToPserverRelationshipData = getPayload("payloads/relationship/pserver-complex-relationship-for-bulk.json");
- String complexToPserverRelationshipUri = String.format(
- "cloud-infrastructure/pservers/pserver/%s/relationship-list/relationship", hostname);
-
- Response response = legacyMoxyConsumer.updateRelationship(
- complexToPserverRelationshipData,
- Version.getLatest().toString(),
- complexToPserverRelationshipUri,
- httpHeaders,
- uriInfo,
- new MockHttpServletRequest("DELETE", "http://www.test.com")
- );
-
- assertNotNull("Response from the legacy moxy consumer returned null", response);
- int code = response.getStatus();
- if(!VALID_HTTP_STATUS_CODES.contains(code)){
- System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity());
- }
-
- assertEquals("Expected to return status created from the response",
- Response.Status.OK.getStatusCode(), response.getStatus());
- logger.info("Response Code: " + code + "\tEntity: " + response.getEntity());
-
- // TODO - Need to actually verify the relationship between pserver and cloud-region
-
- String payload = getBulkPayload("complex-bulk-process-delete-transactions");
- Response responseBulkDelete = executeRequest(payload);
-
- System.out.println(responseBulkDelete.getEntity().toString());
-
- code = responseBulkDelete.getStatus();
-
- if(!VALID_HTTP_STATUS_CODES.contains(code)){
- System.out.println("Response Code: " + code + "\tEntity: " + responseBulkDelete.getEntity());
- System.out.println("Response Code: " + code + "\tEntity: " + responseBulkDelete.getEntity());
- }
- assertEquals("Expected to return status created from the response",
- Response.Status.CREATED.getStatusCode(), responseBulkDelete.getStatus());
- assertEquals("Contains 0 {\"204\":null}", 1, StringUtils.countMatches(responseBulkDelete.getEntity().toString(), "{\"204\":null}"));
-
- }
-
- protected void doSetupResource(String uri, String payload) throws JSONException {
-
- when(uriInfo.getPath()).thenReturn(uri);
- when(uriInfo.getPath(false)).thenReturn(uri);
-
- Response response = legacyMoxyConsumer.getLegacy(
- "",
- "-1",
- "-1",
- Version.getLatest().toString(),
- uri,
- "all",
- "false",
- httpHeaders,
- uriInfo,
- new MockHttpServletRequest("GET", "http://www.test.com")
- );
-
- assertNotNull("Response from the legacy moxy consumer returned null", response);
- assertEquals("Expected to not have the data already in memory",
- Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
-
- response = legacyMoxyConsumer.update(
- payload,
- Version.getLatest().toString(),
- uri,
- httpHeaders,
- uriInfo,
- new MockHttpServletRequest("PUT", "http://www.test.com")
- );
-
- assertNotNull("Response from the legacy moxy consumer returned null", response);
- int code = response.getStatus();
- if(!VALID_HTTP_STATUS_CODES.contains(code)){
- System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity());
- }
- assertEquals("Expected to return status created from the response",
- Response.Status.CREATED.getStatusCode(), response.getStatus());
-
- queryParameters.add("depth", "10000");
- response = legacyMoxyConsumer.getLegacy(
- "",
- "-1",
- "-1",
- Version.getLatest().toString(),
- uri,
- "all",
- "false",
- httpHeaders,
- uriInfo,
- new MockHttpServletRequest("GET", "http://www.test.com")
- );
-
- assertNotNull("Response from the legacy moxy consumer returned null", response);
- assertEquals("Expected to return the pserver data that was just put in memory",
- Response.Status.OK.getStatusCode(), response.getStatus());
-
- if("".equalsIgnoreCase(payload)){
- payload = "{}";
- }
-
- JSONAssert.assertEquals(payload, response.getEntity().toString(), false);
- }
-
-
- @Test
- public void bulkAddInvalidMethodTest() throws IOException {
-
- when(uriInfo.getPath()).thenReturn(uri);
- when(uriInfo.getPath(false)).thenReturn(uri);
-
- String payload = getBulkPayload("pserver-transactions-invalid-method");
- Response response = executeRequest(payload);
-
- assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus());
- assertEquals("Contains 1 {\"400\":\"{", 1, StringUtils.countMatches(response.getEntity().toString(), "{\"400\":\"{"));
- assertEquals("Contains 1 ERR.5.4.6118", 1, StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6118"));
- }
-
- @Test
- public void bulkAddThrowExceptionWhenPayloadContainsNoTransactionsTest(){
-
- when(uriInfo.getPath()).thenReturn(uri);
- when(uriInfo.getPath(false)).thenReturn(uri);
-
- String payload = "{\"transactions\":[]}";
- Response response = executeRequest(payload);
-
- assertEquals("Bad Request", Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertEquals("Contains error code", true, response.getEntity().toString().contains("ERR.5.4.6118"));
- }
-
- @Test
- public void bulkAddThrowExceptionWhenInvalidJsonTest() throws IOException {
-
- when(uriInfo.getPath()).thenReturn(uri);
- when(uriInfo.getPath(false)).thenReturn(uri);
-
- String payload = "{";
- Response response = executeRequest(payload);
-
- assertEquals("Bad Request", Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertEquals("Contains error code", true, response.getEntity().toString().contains("ERR.5.4.6111"));
- }
- @Test
- public void bulkProcessCheckMeetsLimit() throws IOException{
- when(uriInfo.getPath()).thenReturn(uri);
- when(uriInfo.getPath(false)).thenReturn(uri);
-
- String payload = getBulkPayload("pserver-bulk-limit-meet");
- Response response = executeRequest(payload);
-
- assertEquals("Created", Response.Status.CREATED.getStatusCode(), response.getStatus());
- assertEquals("Contains 30 {\"201\":null}", 30, StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}"));
- }
-
- @Test
- public void bulkProcessCheckExceedsLimit() throws IOException{
- when(uriInfo.getPath()).thenReturn(uri);
- when(uriInfo.getPath(false)).thenReturn(uri);
-
- String payload = getBulkPayload("pserver-bulk-limit-exceed");
- Response response = executeRequest(payload);
-
- assertEquals("Bad Request", Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
- assertEquals("Contains error code", true, response.getEntity().toString().contains("ERR.5.4.6147"));
- }
-
- @Override
- protected BulkConsumer getConsumer(){
- return new BulkProcessConsumer();
- }
-
- @Override
- protected String getUri() {
- return "/aai/" + Version.getLatest().toString() + "/bulkprocess";
- }
-}
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 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.onap.aai.rest;
+
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+
+import javax.ws.rs.core.Response;
+
+import org.apache.commons.lang3.StringUtils;
+import org.json.JSONException;
+import org.junit.Test;
+import org.onap.aai.dbmap.AAIGraph;
+import org.skyscreamer.jsonassert.JSONAssert;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import org.springframework.mock.web.MockHttpServletRequest;
+
+public class BulkProcessConsumerTest extends BulkProcessorTestAbstraction {
+
+ private static final EELFLogger logger = EELFManager.getInstance().getLogger(BulkProcessConsumerTest.class.getName());
+ private LegacyMoxyConsumer legacyMoxyConsumer;
+
+ @Test
+ public void bulkAddPayloadInBulkProcessTest() throws IOException {
+
+ when(uriInfo.getPath()).thenReturn(uri);
+ when(uriInfo.getPath(false)).thenReturn(uri);
+
+ String payload = getBulkPayload("pserver-transactions");
+ Response response = executeRequest(payload);
+
+ assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus());
+ assertEquals("Contains 3 {\"201\":null}", 3, StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}"));
+ }
+
+ @Test
+ public void bulkProcessPayloadTest() throws IOException {
+
+ when(uriInfo.getPath()).thenReturn(uri);
+ when(uriInfo.getPath(false)).thenReturn(uri);
+
+ String payload = getBulkPayload("pserver-bulk-process-transactions");
+ Response response = executeRequest(payload);
+
+ assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus());
+ assertEquals("Contains 1 {\"201\":null}", 1, StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}"));
+ assertEquals("Contains 1 {\"404\":\"{", 1, StringUtils.countMatches(response.getEntity().toString(), "{\"404\":\"{"));
+ assertEquals("Contains 1 ERR.5.4.6114", 1, StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6114"));
+ }
+
+ @Test
+ public void bulkProcessPayloadWithPatchTest() throws IOException {
+
+ when(uriInfo.getPath()).thenReturn(uri);
+ when(uriInfo.getPath(false)).thenReturn(uri);
+
+ String payload = getBulkPayload("pserver-bulk-process-transactions-with-patch");
+ Response response = executeRequest(payload);
+ System.out.println(response.getEntity());
+ System.out.println(AAIGraph.getInstance().getGraph().newTransaction().traversal().V().has("fqdn", "NEW").count().next());
+ assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus());
+ }
+
+ @Test
+ public void bulkProcessComplexDeletePayloadTest() throws IOException {
+
+ when(uriInfo.getPath()).thenReturn(uri);
+ when(uriInfo.getPath(false)).thenReturn(uri);
+
+ String payload = getBulkPayload("complex-bulk-process-transactions");
+ Response response = executeRequest(payload);
+
+ System.out.println(response.getEntity().toString());
+ assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus());
+ assertEquals("Contains 0 {\"201\":null}", 0, StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}"));
+ assertEquals("Contains 1 {\"404\":\"{", 1, StringUtils.countMatches(response.getEntity().toString(), "{\"404\":\"{"));
+ assertEquals("Contains 1 ERR.5.4.6114", 1, StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6114"));
+ }
+
+ @Test
+ public void testBulkDeletePserverAndComplexRelationship() throws IOException, JSONException {
+
+ legacyMoxyConsumer = new LegacyMoxyConsumer();
+
+ String pserverData = getPayload("payloads/relationship/pserver-bugfix.json");
+ String complexData = getPayload("payloads/relationship/complex-bugfix.json");
+
+ String hostname = "pserver-9876543210-77-jenkins";
+ String physicalLocationId ="complex-987654321-77-jenkins";
+
+ String pserverUri = String.format("cloud-infrastructure/pservers/pserver/%s", hostname);
+ String complexUri = String.format("cloud-infrastructure/complexes/complex/%s", physicalLocationId);
+
+ doSetupResource(pserverUri, pserverData);
+ doSetupResource(complexUri, complexData);
+
+ String complexToPserverRelationshipData = getPayload("payloads/relationship/pserver-complex-relationship-for-bulk.json");
+ String complexToPserverRelationshipUri = String.format(
+ "cloud-infrastructure/pservers/pserver/%s/relationship-list/relationship", hostname);
+
+ Response response = legacyMoxyConsumer.updateRelationship(
+ complexToPserverRelationshipData,
+ schemaVersions.getDefaultVersion().toString(),
+ complexToPserverRelationshipUri,
+ httpHeaders,
+ uriInfo,
+ new MockHttpServletRequest("DELETE", "http://www.test.com")
+ );
+
+ assertNotNull("Response from the legacy moxy consumer returned null", response);
+ int code = response.getStatus();
+ if(!VALID_HTTP_STATUS_CODES.contains(code)){
+ System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity());
+ }
+
+ assertEquals("Expected to return status created from the response",
+ Response.Status.OK.getStatusCode(), response.getStatus());
+ logger.info("Response Code: " + code + "\tEntity: " + response.getEntity());
+
+ // TODO - Need to actually verify the relationship between pserver and cloud-region
+
+ String payload = getBulkPayload("complex-bulk-process-delete-transactions");
+ Response responseBulkDelete = executeRequest(payload);
+
+ System.out.println(responseBulkDelete.getEntity().toString());
+
+ code = responseBulkDelete.getStatus();
+
+ if(!VALID_HTTP_STATUS_CODES.contains(code)){
+ System.out.println("Response Code: " + code + "\tEntity: " + responseBulkDelete.getEntity());
+ System.out.println("Response Code: " + code + "\tEntity: " + responseBulkDelete.getEntity());
+ }
+ assertEquals("Expected to return status created from the response",
+ Response.Status.CREATED.getStatusCode(), responseBulkDelete.getStatus());
+ assertEquals("Contains 0 {\"204\":null}", 1, StringUtils.countMatches(responseBulkDelete.getEntity().toString(), "{\"204\":null}"));
+
+ }
+
+ protected void doSetupResource(String uri, String payload) throws JSONException {
+
+ when(uriInfo.getPath()).thenReturn(uri);
+ when(uriInfo.getPath(false)).thenReturn(uri);
+
+ Response response = legacyMoxyConsumer.getLegacy(
+ "",
+ "-1",
+ "-1",
+ schemaVersions.getDefaultVersion().toString(),
+ uri,
+ "all",
+ "false",
+ httpHeaders,
+ uriInfo,
+ new MockHttpServletRequest("GET", "http://www.test.com")
+ );
+
+ assertNotNull("Response from the legacy moxy consumer returned null", response);
+ assertEquals("Expected to not have the data already in memory",
+ Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
+
+ response = legacyMoxyConsumer.update(
+ payload,
+ schemaVersions.getDefaultVersion().toString(),
+ uri,
+ httpHeaders,
+ uriInfo,
+ new MockHttpServletRequest("PUT", "http://www.test.com")
+ );
+
+ assertNotNull("Response from the legacy moxy consumer returned null", response);
+ int code = response.getStatus();
+ if(!VALID_HTTP_STATUS_CODES.contains(code)){
+ System.out.println("Response Code: " + code + "\tEntity: " + response.getEntity());
+ }
+ assertEquals("Expected to return status created from the response",
+ Response.Status.CREATED.getStatusCode(), response.getStatus());
+
+ queryParameters.add("depth", "10000");
+ response = legacyMoxyConsumer.getLegacy(
+ "",
+ "-1",
+ "-1",
+ schemaVersions.getDefaultVersion().toString(),
+ uri,
+ "all",
+ "false",
+ httpHeaders,
+ uriInfo,
+ new MockHttpServletRequest("GET", "http://www.test.com")
+ );
+
+ assertNotNull("Response from the legacy moxy consumer returned null", response);
+ assertEquals("Expected to return the pserver data that was just put in memory",
+ Response.Status.OK.getStatusCode(), response.getStatus());
+
+ if("".equalsIgnoreCase(payload)){
+ payload = "{}";
+ }
+
+ JSONAssert.assertEquals(payload, response.getEntity().toString(), false);
+ }
+
+
+ @Test
+ public void bulkAddInvalidMethodTest() throws IOException {
+
+ when(uriInfo.getPath()).thenReturn(uri);
+ when(uriInfo.getPath(false)).thenReturn(uri);
+
+ String payload = getBulkPayload("pserver-transactions-invalid-method");
+ Response response = executeRequest(payload);
+
+ assertEquals("Valid Response Code", Response.Status.CREATED.getStatusCode(), response.getStatus());
+ assertEquals("Contains 1 {\"400\":\"{", 1, StringUtils.countMatches(response.getEntity().toString(), "{\"400\":\"{"));
+ assertEquals("Contains 1 ERR.5.4.6118", 1, StringUtils.countMatches(response.getEntity().toString(), "ERR.5.4.6118"));
+ }
+
+ @Test
+ public void bulkAddThrowExceptionWhenPayloadContainsNoTransactionsTest(){
+
+ when(uriInfo.getPath()).thenReturn(uri);
+ when(uriInfo.getPath(false)).thenReturn(uri);
+
+ String payload = "{\"transactions\":[]}";
+ Response response = executeRequest(payload);
+
+ assertEquals("Bad Request", Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+ assertEquals("Contains error code", true, response.getEntity().toString().contains("ERR.5.4.6118"));
+ }
+
+ @Test
+ public void bulkAddThrowExceptionWhenInvalidJsonTest() throws IOException {
+
+ when(uriInfo.getPath()).thenReturn(uri);
+ when(uriInfo.getPath(false)).thenReturn(uri);
+
+ String payload = "{";
+ Response response = executeRequest(payload);
+
+ assertEquals("Bad Request", Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+ assertEquals("Contains error code", true, response.getEntity().toString().contains("ERR.5.4.6111"));
+ }
+ @Test
+ public void bulkProcessCheckMeetsLimit() throws IOException{
+ when(uriInfo.getPath()).thenReturn(uri);
+ when(uriInfo.getPath(false)).thenReturn(uri);
+
+ String payload = getBulkPayload("pserver-bulk-limit-meet");
+ Response response = executeRequest(payload);
+
+ assertEquals("Created", Response.Status.CREATED.getStatusCode(), response.getStatus());
+ assertEquals("Contains 30 {\"201\":null}", 30, StringUtils.countMatches(response.getEntity().toString(), "{\"201\":null}"));
+ }
+
+ @Test
+ public void bulkProcessCheckExceedsLimit() throws IOException{
+ when(uriInfo.getPath()).thenReturn(uri);
+ when(uriInfo.getPath(false)).thenReturn(uri);
+
+ String payload = getBulkPayload("pserver-bulk-limit-exceed");
+ Response response = executeRequest(payload);
+
+ assertEquals("Bad Request", Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+ assertEquals("Contains error code", true, response.getEntity().toString().contains("ERR.5.4.6147"));
+ }
+
+ @Override
+ protected BulkConsumer getConsumer(){
+ return new BulkProcessConsumer();
+ }
+
+ @Override
+ protected String getUri() {
+ return "/aai/" + schemaVersions.getDefaultVersion().toString() + "/bulkprocess";
+ }
+}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessorTestAbstraction.java b/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessorTestAbstraction.java
index 40e8f05..e735041 100644
--- a/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessorTestAbstraction.java
+++ b/aai-resources/src/test/java/org/onap/aai/rest/BulkProcessorTestAbstraction.java
@@ -41,8 +41,6 @@ import org.junit.BeforeClass;
import org.mockito.Mockito;
import org.onap.aai.AAISetup;
import org.onap.aai.dbmap.AAIGraph;
-import org.onap.aai.introspection.ModelInjestor;
-import org.onap.aai.introspection.Version;
import com.att.eelf.configuration.EELFLogger;
import com.att.eelf.configuration.EELFManager;
@@ -74,16 +72,21 @@ public abstract class BulkProcessorTestAbstraction extends AAISetup {
protected String uri;
+ private boolean initialized = false;
private static final EELFLogger logger = EELFManager.getInstance().getLogger(BulkProcessorTestAbstraction.class.getName());
@BeforeClass
public static void setupRest(){
- AAIGraph.getInstance();
- ModelInjestor.getInstance();
+ // AAIGraph.getInstance();
+
}
@Before
public void setup(){
+ if(!initialized){
+ initialized = true;
+ AAIGraph.getInstance();
+ }
logger.info("Starting the setup for the integration tests of Rest Endpoints");
bulkConsumer = getConsumer();
@@ -126,7 +129,7 @@ public abstract class BulkProcessorTestAbstraction extends AAISetup {
return bulkConsumer.bulkProcessor(
payload.replaceAll("<UUID>", UUID.randomUUID().toString()),
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
httpHeaders,
uriInfo,
mockReq
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/ConfigurationTest.java b/aai-resources/src/test/java/org/onap/aai/rest/ConfigurationTest.java
index b6d8872..f030f20 100644
--- a/aai-resources/src/test/java/org/onap/aai/rest/ConfigurationTest.java
+++ b/aai-resources/src/test/java/org/onap/aai/rest/ConfigurationTest.java
@@ -22,10 +22,10 @@ package org.onap.aai.rest;
import com.jayway.jsonpath.JsonPath;
import org.junit.Before;
import org.junit.Test;
-import org.junit.runner.RunWith;
import org.onap.aai.ResourcesApp;
import org.onap.aai.ResourcesTestConfiguration;
import org.onap.aai.config.PropertyPasswordConfiguration;
+import org.onap.aai.config.SpringContextAware;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.embedded.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
@@ -33,7 +33,6 @@ import org.springframework.context.annotation.Import;
import org.springframework.http.*;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
import java.io.UnsupportedEncodingException;
@@ -47,13 +46,12 @@ import static org.junit.Assert.assertEquals;
/**
* Test REST requests against configuration resource
*/
-@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = ResourcesApp.class)
+
@TestPropertySource(locations = "classpath:application-test.properties")
-@ContextConfiguration(initializers = PropertyPasswordConfiguration.class)
+@ContextConfiguration(initializers = PropertyPasswordConfiguration.class, classes = {SpringContextAware.class})
@Import(ResourcesTestConfiguration.class)
-public class ConfigurationTest {
-
+@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {SpringContextAware.class, ResourcesApp.class})
+public class ConfigurationTest extends AbstractSpringRestTest {
@Autowired
RestTemplate restTemplate;
@@ -85,18 +83,23 @@ public class ConfigurationTest {
@Test
public void testGetPutPatchConfiguration() {
- String hostname = "pservertest" + UUID.randomUUID().toString();
- String endpoint = "/aai/v13/cloud-infrastructure/pservers/pserver/" + hostname;
+ String cid = "configtest" + UUID.randomUUID().toString();
+ String endpoint = "/aai/v12/network/configurations/configuration/" + cid;
ResponseEntity responseEntity = null;
responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class);
assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode());
+ //String putBody = " configuration-id, configuration-type configuration-sub-type";
String putBody = "{" +
- "\"hostname\": \"" + hostname + "\"," +
- "\"ptnii-equip-name\": \"type1\"," +
- "\"equip-type\": \"subtype1\" " +
+ "\"configuration-id\": \"" + cid + "\"," +
+ "\"configuration-type\": \"type1\"," +
+ "\"configuration-sub-type\": \"subtype1\", " +
+ "\"operational-status\": \"example1\", " +
+ "\"orchestration-status\": \"example1\", " +
+ "\"configuration-selflink\": \"example1\", " +
+ "\"model-customization-id\": \"example1\" " +
"}";
httpEntityPut = new HttpEntity<String>(putBody, headers);
responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntityPut, String.class);
@@ -110,9 +113,13 @@ public class ConfigurationTest {
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
String patchBody = "{" +
- "\"hostname\": \"" + hostname + "\"," +
- "\"ptnii-equip-name\": \"type2\"," +
- "\"equip-type\": \"subtype2\" " +
+ "\"configuration-id\": \"" + cid + "\"," +
+ "\"configuration-type\": \"type2\"," +
+ "\"configuration-sub-type\": \"subtype2\", " +
+ "\"operational-status\": \"example1\", " +
+ "\"orchestration-status\": \"example1\", " +
+ "\"configuration-selflink\": \"example1\", " +
+ "\"model-customization-id\": \"example1\" " +
"}";
headers.put("Content-Type", Arrays.asList("application/merge-patch+json"));
headers.add("X-HTTP-Method-Override", "PATCH");
@@ -126,14 +133,14 @@ public class ConfigurationTest {
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
String body = responseEntity.getBody().toString();
- String ptniiEquipName = JsonPath.read(body, "$.ptnii-equip-name");
+ String configurationType = JsonPath.read(body, "$.configuration-type");
- assertEquals("type2", ptniiEquipName);
+ assertEquals("type2", configurationType);
patchBody = "{" +
- "\"hostname\": \"" + hostname + "\"," +
- "\"ptnii-equip-name\": \"type3\"," +
- "\"equip-type\": \"subtype3\" " +
+ "\"configuration-id\": \"" + cid + "\"," +
+ "\"configuration-type\": \"type3\"," +
+ "\"configuration-sub-type\": \"subtype3\" " +
"}";
httpEntityPatch = new HttpEntity<String>(patchBody, headers);
@@ -144,9 +151,9 @@ public class ConfigurationTest {
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
body = responseEntity.getBody().toString();
- ptniiEquipName = JsonPath.read(body, "$.ptnii-equip-name");
+ configurationType = JsonPath.read(body, "$.configuration-type");
- assertEquals("type3", ptniiEquipName);
+ assertEquals("type3", configurationType);
}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/CustomerFilterSearchTest.java b/aai-resources/src/test/java/org/onap/aai/rest/CustomerFilterSearchTest.java
new file mode 100644
index 0000000..f22c915
--- /dev/null
+++ b/aai-resources/src/test/java/org/onap/aai/rest/CustomerFilterSearchTest.java
@@ -0,0 +1,66 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 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.onap.aai.rest;
+
+import org.junit.Test;
+import org.onap.aai.PayloadUtil;
+import org.springframework.http.*;
+
+import java.util.Base64;
+import java.util.Collections;
+
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
+public class CustomerFilterSearchTest extends AbstractSpringRestTest {
+
+ @Test
+ public void testWhenContentTypeMissingItWillFunctionalAndCreateObjectWithPayloadInJson() throws Exception {
+
+ String id = "customer-987654321-91";
+ String endpoint = "/aai/v11/business/customers/customer/"+ id;
+ HttpHeaders headers = new HttpHeaders();
+
+ headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
+ headers.add("Real-Time", "true");
+ headers.add("X-FromAppId", "JUNIT");
+ headers.add("X-TransactionId", "JUNIT");
+
+ String authorization = Base64.getEncoder().encodeToString("AAI:AAI".getBytes("UTF-8"));
+ headers.add("Authorization", "Basic " + authorization);
+ String body = PayloadUtil.getResourcePayload("customer.json");
+
+ httpEntity = new HttpEntity(body, headers);
+ baseUrl = "https://localhost:" + randomPort;
+
+ ResponseEntity responseEntity;
+ responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+
+ assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode());
+
+ String searchUrl = baseUrl + "/aai/v11/business/customers?subscriber-name=subscriber-name-987654321-91&depth=0";
+ httpEntity = new HttpEntity(headers);
+ responseEntity = restTemplate.exchange(searchUrl, HttpMethod.GET, httpEntity, String.class);
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertThat(responseEntity.getBody().toString(), containsString("global-customer-id"));
+ }
+
+}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/DepthTest.java b/aai-resources/src/test/java/org/onap/aai/rest/DepthTest.java
new file mode 100644
index 0000000..c664c22
--- /dev/null
+++ b/aai-resources/src/test/java/org/onap/aai/rest/DepthTest.java
@@ -0,0 +1,64 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 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.onap.aai.rest;
+
+import org.hamcrest.MatcherAssert;
+import org.junit.Test;
+import org.onap.aai.PayloadUtil;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+
+import java.io.IOException;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.Matchers.not;
+
+public class DepthTest extends AbstractSpringRestTest {
+
+ @Test
+ public void testOldVersionReturnAllChildrenAndNewVersionReturnDepthZero() throws IOException {
+
+ String id = "customer-987654321-91";
+ String endpoint = "/aai/v9/business/customers/customer/"+ id;
+
+ String body = PayloadUtil.getResourcePayload("customer.json");
+
+ httpEntity = new HttpEntity(body, headers);
+
+ ResponseEntity responseEntity;
+ responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ assertThat(responseEntity.getStatusCode(), is(HttpStatus.CREATED));
+
+ responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class);
+ assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));
+ String responseBody = responseEntity.getBody().toString();
+ assertThat(responseBody, not(containsString("service-instance-id")));
+ endpoint = "/aai/v8/business/customers/customer/"+ id;
+
+ responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class);
+ assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));
+ responseBody = responseEntity.getBody().toString();
+ assertThat(responseBody, containsString("service-instance-id"));
+ }
+}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/ExampleConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/ExampleConsumerTest.java
index 22980ad..3f50ba3 100644
--- a/aai-resources/src/test/java/org/onap/aai/rest/ExampleConsumerTest.java
+++ b/aai-resources/src/test/java/org/onap/aai/rest/ExampleConsumerTest.java
@@ -27,8 +27,6 @@ import org.junit.Test;
import org.mockito.Mockito;
import org.onap.aai.AAISetup;
import org.onap.aai.dbmap.AAIGraph;
-import org.onap.aai.introspection.ModelInjestor;
-import org.onap.aai.introspection.Version;
import javax.ws.rs.core.*;
@@ -69,7 +67,7 @@ public class ExampleConsumerTest extends AAISetup {
@BeforeClass
public static void setupRest(){
AAIGraph.getInstance();
- ModelInjestor.getInstance();
+
}
@Before
@@ -114,7 +112,7 @@ public class ExampleConsumerTest extends AAISetup {
public void testGetExampleRespondsWithOkStatusForValidObject(){
Response response = exampleConsumer.getExample(
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
"pserver",
httpHeaders,
uriInfo,
@@ -134,7 +132,7 @@ public class ExampleConsumerTest extends AAISetup {
when(uriInfo.getPath(false)).thenReturn("examples/fakeObject");
Response response = exampleConsumer.getExample(
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
"testRandomCrazyObject",
httpHeaders,
uriInfo,
diff --git a/aai-resources/src/test/java/org/onap/aai/util/HbaseSaltPrefixerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/InvalidURITest.java
index 6379240..ea41872 100644
--- a/aai-resources/src/test/java/org/onap/aai/util/HbaseSaltPrefixerTest.java
+++ b/aai-resources/src/test/java/org/onap/aai/rest/InvalidURITest.java
@@ -17,22 +17,31 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.util;
+package org.onap.aai.rest;
import org.junit.Test;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
-import static org.junit.Assert.assertTrue;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
+import static org.junit.Assert.assertEquals;
-public class HbaseSaltPrefixerTest {
+public class InvalidURITest extends AbstractSpringRestTest {
- /**
- * Test.
- */
- @Test
- public void test() {
- String key = "imakey";
- String saltedKey = HbaseSaltPrefixer.getInstance().prependSalt(key);
- assertTrue(saltedKey.equals("0-imakey"));
- }
+ @Test
+ public void testWhenUriNotStartsWithAAIItReturnsProperNotFound(){
+ String endpoint = "/aai1/v11/cloud-infrastructure/pservers/pserver/test";
+
+ ResponseEntity responseEntity;
+ responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class);
+
+ String body = responseEntity.getBody().toString();
+ System.out.println(body);
+
+ assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
+ assertThat(body, containsString("Unrecognized AAI function "));
+ }
}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java
index 660d663..3845fb0 100644
--- a/aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java
+++ b/aai-resources/src/test/java/org/onap/aai/rest/LegacyMoxyConsumerTest.java
@@ -31,13 +31,12 @@ import org.mockito.Mockito;
import org.onap.aai.AAISetup;
import org.onap.aai.dbmap.AAIGraph;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.ModelInjestor;
-import org.onap.aai.introspection.Version;
import org.onap.aai.util.AAIConfig;
import org.onap.aai.util.AAIConstants;
import org.skyscreamer.jsonassert.JSONAssert;
import org.springframework.mock.web.MockHttpServletRequest;
+import org.springframework.test.annotation.DirtiesContext;
import javax.ws.rs.core.*;
import java.io.IOException;
@@ -72,17 +71,22 @@ public class LegacyMoxyConsumerTest extends AAISetup {
private List<String> aaiRequestContextList;
private List<MediaType> outputMediaTypes;
+ private boolean initialized = false;
+
private static final EELFLogger logger = EELFManager.getInstance().getLogger(LegacyMoxyConsumerTest.class.getName());
@BeforeClass
public static void setupRest(){
- AAIGraph.getInstance();
- ModelInjestor.getInstance();
+ // AAIGraph.getInstance();
}
@Before
public void setup(){
+ if(!initialized){
+ initialized = true;
+ AAIGraph.getInstance();
+ }
logger.info("Starting the setup for the integration tests of Rest Endpoints");
legacyMoxyConsumer = new LegacyMoxyConsumer();
@@ -138,9 +142,9 @@ public class LegacyMoxyConsumerTest extends AAISetup {
MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri);
Response response = legacyMoxyConsumer.getLegacy(
"",
- "-1",
- "-1",
- Version.getLatest().toString(),
+ null,
+ null,
+ schemaVersions.getDefaultVersion().toString(),
uri,
"all",
"false",
@@ -154,7 +158,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri);
response = legacyMoxyConsumer.update(
payload,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -172,9 +176,9 @@ public class LegacyMoxyConsumerTest extends AAISetup {
response = legacyMoxyConsumer.getLegacy(
"",
- "-1",
- "-1",
- Version.getLatest().toString(),
+ null,
+ null,
+ schemaVersions.getDefaultVersion().toString(),
uri,
"10000",
"false",
@@ -201,7 +205,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
mockReq = new MockHttpServletRequest("DELETE", uri);
response = legacyMoxyConsumer.delete(
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -218,9 +222,9 @@ public class LegacyMoxyConsumerTest extends AAISetup {
response = legacyMoxyConsumer.getLegacy(
"",
- "-1",
- "-1",
- Version.getLatest().toString(),
+ null,
+ null,
+ schemaVersions.getDefaultVersion().toString(),
uri,
"all",
"false",
@@ -233,6 +237,34 @@ public class LegacyMoxyConsumerTest extends AAISetup {
}
@Test
+ public void testResponseGetOnResourcePaginated() throws JSONException, IOException, AAIException {
+
+ String uri = getGetAllPserversURI();
+
+ if(uri.length() != 0 && uri.charAt(0) == '/'){
+ uri = uri.substring(1);
+ }
+
+ when(uriInfo.getPath()).thenReturn(uri);
+ when(uriInfo.getPath(false)).thenReturn(uri);
+
+ MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri);
+ Response response = legacyMoxyConsumer.getLegacy(
+ "",
+ "1",
+ "10",
+ schemaVersions.getDefaultVersion().toString(),
+ uri,
+ "all",
+ "false",
+ httpHeaders,
+ uriInfo,
+ mockReqGet
+ );
+ assertEquals(Response.Status.OK.getStatusCode(), response.getStatus());
+ }
+
+ @Test
public void testPutPserverAndCloudRegionRelationship() throws IOException, JSONException {
String pserverData = getRelationshipPayload("pserver");
@@ -253,7 +285,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", cloudToPserverRelationshipUri);
Response response = legacyMoxyConsumer.updateRelationship(
cloudToPserverRelationshipData,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
cloudToPserverRelationshipUri,
httpHeaders,
uriInfo,
@@ -274,7 +306,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
mockReq = new MockHttpServletRequest("DELETE", cloudToPserverRelationshipUri);
response = legacyMoxyConsumer.deleteRelationship(
cloudToPserverRelationshipData,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
cloudToPserverRelationshipUri,
httpHeaders,
uriInfo,
@@ -314,7 +346,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri);
Response response = legacyMoxyConsumer.update(
payload,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -337,7 +369,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri);
Response response = legacyMoxyConsumer.update(
payload,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -351,7 +383,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
response = legacyMoxyConsumer.updateRelationship(
payload,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -365,9 +397,9 @@ public class LegacyMoxyConsumerTest extends AAISetup {
mockReq = new MockHttpServletRequest("GET", uri);
response = legacyMoxyConsumer.getLegacy(
"",
- "-1",
- "-1",
- Version.getLatest().toString(),
+ null,
+ null,
+ schemaVersions.getDefaultVersion().toString(),
uri,
"all",
"false",
@@ -380,7 +412,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), code);
mockReq = new MockHttpServletRequest("DELETE", uri);
response = legacyMoxyConsumer.delete(
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -393,7 +425,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
response = legacyMoxyConsumer.deleteRelationship(
payload,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -414,7 +446,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri);
Response response = legacyMoxyConsumer.update(
payload,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -427,7 +459,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
response = legacyMoxyConsumer.updateRelationship(
payload,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -441,9 +473,9 @@ public class LegacyMoxyConsumerTest extends AAISetup {
mockReq = new MockHttpServletRequest("GET", uri);
response = legacyMoxyConsumer.getLegacy(
"",
- "-1",
- "-1",
- Version.getLatest().toString(),
+ null,
+ null,
+ schemaVersions.getDefaultVersion().toString(),
uri,
"all",
"false",
@@ -458,7 +490,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
mockReq = new MockHttpServletRequest("DELETE", uri);
queryParameters.add("resource-version", "3434394839483");
response = legacyMoxyConsumer.delete(
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -472,7 +504,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
response = legacyMoxyConsumer.deleteRelationship(
payload,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -499,9 +531,9 @@ public class LegacyMoxyConsumerTest extends AAISetup {
MockHttpServletRequest mockReq = new MockHttpServletRequest("GET", uri);
Response response = legacyMoxyConsumer.getLegacy(
"",
- "-1",
- "-1",
- Version.getLatest().toString(),
+ null,
+ null,
+ schemaVersions.getDefaultVersion().toString(),
uri,
"all",
"false",
@@ -514,7 +546,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
mockReq = new MockHttpServletRequest("PUT", uri);
response = legacyMoxyConsumer.update(
payload,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -538,7 +570,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
mockReq = new MockHttpServletRequest("PATCH", uri);
response = legacyMoxyConsumer.patch(
patchData,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -560,9 +592,9 @@ public class LegacyMoxyConsumerTest extends AAISetup {
MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri);
Response response = legacyMoxyConsumer.getLegacy(
"",
- "-1",
- "-1",
- Version.getLatest().toString(),
+ null,
+ null,
+ schemaVersions.getDefaultVersion().toString(),
uri,
"all",
"false",
@@ -578,7 +610,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri);
response = legacyMoxyConsumer.update(
payload,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -596,9 +628,9 @@ public class LegacyMoxyConsumerTest extends AAISetup {
queryParameters.add("depth", "10000");
response = legacyMoxyConsumer.getLegacy(
"",
- "-1",
- "-1",
- Version.getLatest().toString(),
+ null,
+ null,
+ schemaVersions.getDefaultVersion().toString(),
uri,
"all",
"false",
@@ -631,7 +663,7 @@ public class LegacyMoxyConsumerTest extends AAISetup {
MockHttpServletRequest mockReq = new MockHttpServletRequest("DELETE", uri);
Response response = legacyMoxyConsumer.deleteRelationship(
payload,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -659,6 +691,10 @@ public class LegacyMoxyConsumerTest extends AAISetup {
public String getUri(String hostname){
return String.format("cloud-infrastructure/pservers/pserver/%s", hostname);
}
+ public String getGetAllPserversURI(){
+ return "cloud-infrastructure/pservers";
+ }
+
public String getUri(){
return getUri("pserver-hostname-test");
@@ -711,9 +747,9 @@ public class LegacyMoxyConsumerTest extends AAISetup {
MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri);
Response response = legacyMoxyConsumer.getLegacy(
"",
- "-1",
- "-1",
- Version.getLatest().toString(),
+ null,
+ null,
+ schemaVersions.getDefaultVersion().toString(),
uri,
"all",
"false",
@@ -740,9 +776,9 @@ public class LegacyMoxyConsumerTest extends AAISetup {
MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri);
Response response = legacyMoxyConsumer.getLegacy(
"",
- "-1",
- "-1",
- Version.getLatest().toString(),
+ null,
+ null,
+ schemaVersions.getDefaultVersion().toString(),
uri,
"all",
"false",
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/PserverGenerateUrlTest.java b/aai-resources/src/test/java/org/onap/aai/rest/PserverGenerateUrlTest.java
new file mode 100644
index 0000000..7c27477
--- /dev/null
+++ b/aai-resources/src/test/java/org/onap/aai/rest/PserverGenerateUrlTest.java
@@ -0,0 +1,77 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 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.onap.aai.rest;
+
+import com.jayway.jsonpath.JsonPath;
+import org.junit.Test;
+import org.springframework.http.*;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.UUID;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsString;
+import static org.junit.Assert.assertEquals;
+public class PserverGenerateUrlTest extends AbstractSpringRestTest {
+
+ @Test
+ public void testPutPserverExtractVertexGenerateUrlAndDeleteIt() throws UnsupportedEncodingException {
+
+ String endpoint = "/aai/v11/cloud-infrastructure/pservers/pserver/test" + UUID.randomUUID().toString();
+
+ ResponseEntity responseEntity = null;
+
+ responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class);
+ assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode());
+
+ responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode());
+
+ String vertexId = responseEntity.getHeaders().getFirst("vertex-id");
+ responseEntity = restTemplate.exchange(baseUrl + "/aai/v11/generateurl/id/" + vertexId, HttpMethod.GET, plainHttpEntity(), String.class);
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+ assertThat(responseEntity.getBody().toString(), containsString(endpoint));
+
+ responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class);
+ assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
+
+ String body = responseEntity.getBody().toString();
+ String resourceVersion = JsonPath.read(body, "$.resource-version");
+
+ responseEntity = restTemplate.exchange(baseUrl + endpoint+ "?resource-version=" + resourceVersion, HttpMethod.DELETE, httpEntity, String.class);
+ assertEquals(HttpStatus.NO_CONTENT, responseEntity.getStatusCode());
+ }
+
+ private HttpEntity plainHttpEntity() throws UnsupportedEncodingException {
+
+ HttpHeaders headers = new HttpHeaders();
+
+ headers.setAccept(Collections.singletonList(MediaType.TEXT_PLAIN));
+ headers.add("Real-Time", "true");
+ headers.add("X-FromAppId", "JUNIT");
+ headers.add("X-TransactionId", "JUNIT");
+
+ String authorization = Base64.getEncoder().encodeToString("AAI:AAI".getBytes("UTF-8"));
+ headers.add("Authorization", "Basic " + authorization);
+ return new HttpEntity(headers);
+ }
+}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/PserverMissingTest.java b/aai-resources/src/test/java/org/onap/aai/rest/PserverMissingTest.java
new file mode 100644
index 0000000..da982a9
--- /dev/null
+++ b/aai-resources/src/test/java/org/onap/aai/rest/PserverMissingTest.java
@@ -0,0 +1,87 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 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.onap.aai.rest;
+
+import org.junit.Test;
+import org.onap.aai.PayloadUtil;
+import org.springframework.http.*;
+
+import java.util.*;
+
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.StringContains.containsString;
+import static org.junit.Assert.assertEquals;
+public class PserverMissingTest extends AbstractSpringRestTest {
+
+ @Test
+ public void testWhenContentTypeMissingItWillFunctionalAndCreateObjectWithPayloadInJson() throws Exception {
+
+ String id = "test-" + UUID.randomUUID().toString();
+ String endpoint = "/aai/v11/cloud-infrastructure/pservers/pserver/"+ id;
+ HttpHeaders headers = new HttpHeaders();
+
+ headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
+ headers.add("Real-Time", "true");
+ headers.add("X-FromAppId", "JUNIT");
+ headers.add("X-TransactionId", "JUNIT");
+ String authorization = Base64.getEncoder().encodeToString("AAI:AAI".getBytes("UTF-8"));
+ headers.add("Authorization", "Basic " + authorization);
+
+ Map<String, String> templateMap = new HashMap<>();
+
+ templateMap.put("hostname", id);
+ String body = PayloadUtil.getTemplatePayload("pserver.json", templateMap);
+
+ httpEntity = new HttpEntity(body, headers);
+ baseUrl = "https://localhost:" + randomPort;
+
+ ResponseEntity responseEntity;
+ responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+
+ assertEquals(HttpStatus.CREATED, responseEntity.getStatusCode());
+ }
+
+ @Test
+ public void testWhenAcceptMissingItWillReturnThePayloadInXml() throws Exception {
+
+ String id = "test-" + UUID.randomUUID().toString();
+ String endpoint = "/aai/v11/cloud-infrastructure/pservers/pserver/"+ id;
+ HttpHeaders headers = new HttpHeaders();
+
+ headers.add("Real-Time", "true");
+ headers.add("X-FromAppId", "JUNIT");
+ headers.add("X-TransactionId", "JUNIT");
+ String authorization = Base64.getEncoder().encodeToString("AAI:AAI".getBytes("UTF-8"));
+ headers.add("Authorization", "Basic " + authorization);
+
+ httpEntity = new HttpEntity(headers);
+ baseUrl = "https://localhost:" + randomPort;
+
+ ResponseEntity responseEntity;
+ responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class);
+
+ String body = responseEntity.getBody().toString();
+
+ assertEquals(HttpStatus.NOT_FOUND, responseEntity.getStatusCode());
+ assertThat(body, containsString("<Fault>"));
+ assertThat(body, containsString("Resource not found for"));
+ assertThat(body, containsString("Node Not Found"));
+ }
+}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/PserverRelationshipTest.java b/aai-resources/src/test/java/org/onap/aai/rest/PserverRelationshipTest.java
new file mode 100644
index 0000000..017844e
--- /dev/null
+++ b/aai-resources/src/test/java/org/onap/aai/rest/PserverRelationshipTest.java
@@ -0,0 +1,97 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 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.onap.aai.rest;
+
+import org.junit.Test;
+import org.onap.aai.PayloadUtil;
+import org.onap.aai.util.MapperUtil;
+import org.springframework.http.HttpEntity;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+
+import java.util.HashMap;
+import java.util.HashSet;
+import java.util.Map;
+import java.util.Set;
+
+import static org.hamcrest.CoreMatchers.not;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.Matchers.containsInAnyOrder;
+import static org.hamcrest.Matchers.containsString;
+import static org.junit.Assert.assertEquals;
+
+public class PserverRelationshipTest extends AbstractSpringRestTest {
+
+ @Test
+ public void testGetRelationshipThrowUnrecognizedAAIObjectException() {
+
+ String endpoint = "/aai/v12/cloud-infrastructure/pservers/pserver/test/relationship-list/relationship";
+
+ ResponseEntity responseEntity = null;
+
+ responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class);
+ String body = responseEntity.getBody().toString();
+
+ Set<HttpMethod> httpMethodSet = new HashSet<>();
+
+ httpMethodSet.add(HttpMethod.PUT);
+ httpMethodSet.add(HttpMethod.DELETE);
+ httpMethodSet.add(HttpMethod.OPTIONS);
+
+
+ assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
+ assertThat(body, containsString("Unrecognized AAI function"));
+ assertThat(responseEntity.getHeaders().getAllow(), containsInAnyOrder(httpMethodSet.toArray()));
+ }
+
+ @Test
+ public void testPutPserverAndCloudRegionAndReturnEdgesWithLabel() throws Exception {
+
+ String hostname = "test-pserver1";
+ String endpoint = "/aai/v12/cloud-infrastructure/pservers/pserver/" + hostname;
+
+ ResponseEntity responseEntity = null;
+
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+
+ String cloudRegionId = "test-region-1";
+ String cloudOwnerId = "test-owner-1";
+ endpoint = "/aai/v12/cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwnerId + "/" + cloudRegionId;
+
+ Map<String, String> map = new HashMap<>();
+ map.put("hostname", hostname);
+ map.put("cloud-region-id", cloudRegionId);
+ map.put("cloud-owner", cloudOwnerId);
+
+ String payload = PayloadUtil.getTemplatePayload("pserver-to-cloud-region.json", map);
+ httpEntity = new HttpEntity(payload, headers);
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+
+ httpEntity = new HttpEntity(headers);
+ responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class);
+ assertThat(responseEntity.getBody().toString(), containsString("relationship-label"));
+
+ endpoint = "/aai/v11/cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwnerId + "/" + cloudRegionId;
+
+ responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class);
+ assertThat(responseEntity.getBody().toString(), not(containsString("relationship-label")));
+ }
+}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/PserverTest.java b/aai-resources/src/test/java/org/onap/aai/rest/PserverTest.java
index 2acc3c4..7f48ff8 100644
--- a/aai-resources/src/test/java/org/onap/aai/rest/PserverTest.java
+++ b/aai-resources/src/test/java/org/onap/aai/rest/PserverTest.java
@@ -20,25 +20,11 @@
package org.onap.aai.rest;
import com.jayway.jsonpath.JsonPath;
-import org.junit.Before;
import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.onap.aai.ResourcesApp;
-import org.onap.aai.ResourcesTestConfiguration;
-import org.onap.aai.config.PropertyPasswordConfiguration;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.context.embedded.LocalServerPort;
-import org.springframework.boot.test.context.SpringBootTest;
-import org.springframework.context.annotation.Import;
-import org.springframework.http.*;
-import org.springframework.test.context.ContextConfiguration;
-import org.springframework.test.context.TestPropertySource;
-import org.springframework.test.context.junit4.SpringRunner;
-import org.springframework.web.client.RestTemplate;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
-import java.io.UnsupportedEncodingException;
-import java.util.Base64;
-import java.util.Collections;
import java.util.UUID;
import static org.junit.Assert.assertEquals;
@@ -54,40 +40,7 @@ import static org.junit.Assert.assertEquals;
* This can be used to potentially replace a lot of the fitnesse tests since
* they will be testing against the same thing except fitnesse uses hbase
*/
-@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = ResourcesApp.class)
-@TestPropertySource(locations = "classpath:application-test.properties")
-@ContextConfiguration(initializers = PropertyPasswordConfiguration.class)
-@Import(ResourcesTestConfiguration.class)
-public class PserverTest {
-
- @Autowired
- RestTemplate restTemplate;
-
- @LocalServerPort
- int randomPort;
-
- private HttpEntity httpEntity;
-
- private String baseUrl;
-
- @Before
- public void setup() throws UnsupportedEncodingException {
-
- HttpHeaders headers = new HttpHeaders();
-
- headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
- headers.setContentType(MediaType.APPLICATION_JSON);
- headers.add("Real-Time", "true");
- headers.add("X-FromAppId", "JUNIT");
- headers.add("X-TransactionId", "JUNIT");
-
- String authorization = Base64.getEncoder().encodeToString("AAI:AAI".getBytes("UTF-8"));
- headers.add("Authorization", "Basic " + authorization);
-
- httpEntity = new HttpEntity(headers);
- baseUrl = "https://localhost:" + randomPort;
- }
+public class PserverTest extends AbstractSpringRestTest {
@Test
public void testPutPserverExtractVertexAndThenDoGetByVertexIdAndThenDeleteIt() {
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/PserverWrongHeaderTest.java b/aai-resources/src/test/java/org/onap/aai/rest/PserverWrongHeaderTest.java
new file mode 100644
index 0000000..4d75a2e
--- /dev/null
+++ b/aai-resources/src/test/java/org/onap/aai/rest/PserverWrongHeaderTest.java
@@ -0,0 +1,50 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 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.onap.aai.rest;
+
+import org.junit.Test;
+import org.springframework.http.*;
+
+import java.util.UUID;
+
+import static org.hamcrest.Matchers.containsString;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+public class PserverWrongHeaderTest extends AbstractSpringRestTest{
+
+ @Test
+ public void testWhenNoHeadersItFailsWithBadRequestAndReturnsXml(){
+
+ HttpHeaders httpHeaders = new HttpHeaders();
+
+ httpEntity = new HttpEntity(httpHeaders);
+
+ String endpoint = "/aai/v11/cloud-infrastructure/pservers/pserver/test" + UUID.randomUUID().toString();
+
+ ResponseEntity responseEntity;
+ responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.GET, httpEntity, String.class);
+
+ String body = responseEntity.getBody().toString();
+
+ assertEquals(HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
+ assertThat(body, containsString("<Fault>"));
+ assertThat(body, containsString("Invalid X-FromAppId in header"));
+ }
+}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java
index c49d10b..2edec7b 100644
--- a/aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java
+++ b/aai-resources/src/test/java/org/onap/aai/rest/URLFromVertexIdConsumerTest.java
@@ -29,8 +29,6 @@ import org.mockito.Mockito;
import org.onap.aai.AAISetup;
import org.onap.aai.dbmap.AAIGraph;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.ModelInjestor;
-import org.onap.aai.introspection.Version;
import javax.ws.rs.core.*;
import java.io.IOException;
@@ -68,15 +66,18 @@ public class URLFromVertexIdConsumerTest extends AAISetup {
private List<MediaType> outputMediaTypes;
private static final EELFLogger logger = EELFManager.getInstance().getLogger(LegacyMoxyConsumerTest.class.getName());
-
+ private boolean initialized = false;
@BeforeClass
public static void setupRest(){
- AAIGraph.getInstance();
- ModelInjestor.getInstance();
+ // AAIGraph.getInstance();
}
@Before
public void setup(){
+ if(!initialized){
+ initialized = true;
+ AAIGraph.getInstance();
+ }
logger.info("Starting the setup for the integration tests of Rest Endpoints");
urlFromVertexIdConsumer = new URLFromVertexIdConsumer();
@@ -129,7 +130,7 @@ public class URLFromVertexIdConsumerTest extends AAISetup {
"",
"-1",
"-1",
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
"all",
"false",
@@ -142,7 +143,7 @@ public class URLFromVertexIdConsumerTest extends AAISetup {
MockHttpServletRequest mockReq = new MockHttpServletRequest("PUT", uri);
response = legacyMoxyConsumer.update(
payload,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -164,7 +165,7 @@ public class URLFromVertexIdConsumerTest extends AAISetup {
String vertexId = responseHeaders.get("vertex-id").get(0).toString();
response = urlFromVertexIdConsumer.generateUrlFromVertexId(
"",
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
Long.valueOf(vertexId).longValue(),
httpHeaders,
uriInfo,
@@ -187,7 +188,7 @@ public class URLFromVertexIdConsumerTest extends AAISetup {
MockHttpServletRequest mockReqGet = new MockHttpServletRequest("GET", uri);
Response response = urlFromVertexIdConsumer.generateUrlFromVertexId(
"",
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
Long.valueOf(vertexId).longValue(),
httpHeaders,
uriInfo,
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java
index 41214db..8d3f5a8 100644
--- a/aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java
+++ b/aai-resources/src/test/java/org/onap/aai/rest/VertexIdConsumerTest.java
@@ -29,8 +29,6 @@ import org.mockito.Mockito;
import org.onap.aai.AAISetup;
import org.onap.aai.dbmap.AAIGraph;
import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.introspection.ModelInjestor;
-import org.onap.aai.introspection.Version;
import javax.ws.rs.core.*;
import java.io.IOException;
@@ -40,7 +38,6 @@ import static org.junit.Assert.*;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.when;
import org.springframework.mock.web.MockHttpServletRequest;
-
public class VertexIdConsumerTest extends AAISetup {
protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
@@ -68,15 +65,19 @@ public class VertexIdConsumerTest extends AAISetup {
private List<MediaType> outputMediaTypes;
private static final EELFLogger logger = EELFManager.getInstance().getLogger(LegacyMoxyConsumerTest.class.getName());
-
+ private boolean initialized = false;
+
@BeforeClass
public static void setupRest(){
- AAIGraph.getInstance();
- ModelInjestor.getInstance();
+ //AAIGraph.getInstance();
}
@Before
public void setup(){
+ if(!initialized){
+ initialized = true;
+ AAIGraph.getInstance();
+ }
logger.info("Starting the setup for the integration tests of Rest Endpoints");
vertexIdConsumer = new VertexIdConsumer();
@@ -129,7 +130,7 @@ public class VertexIdConsumerTest extends AAISetup {
"",
"-1",
"-1",
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
"all",
"false",
@@ -143,7 +144,7 @@ public class VertexIdConsumerTest extends AAISetup {
response = legacyMoxyConsumer.update(
payload,
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
uri,
httpHeaders,
uriInfo,
@@ -166,7 +167,7 @@ public class VertexIdConsumerTest extends AAISetup {
response = vertexIdConsumer.getByVertexId(
"",
- Version.getLatest().toString(),
+ schemaVersions.getDefaultVersion().toString(),
Long.valueOf(vertexId).longValue(),
"10000",
httpHeaders,
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/bulk/BulkSingleTransactionConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/bulk/BulkSingleTransactionConsumerTest.java
new file mode 100644
index 0000000..e317297
--- /dev/null
+++ b/aai-resources/src/test/java/org/onap/aai/rest/bulk/BulkSingleTransactionConsumerTest.java
@@ -0,0 +1,369 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 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.onap.aai.rest.bulk;
+
+import org.apache.tinkerpop.gremlin.structure.Property;
+import org.apache.tinkerpop.gremlin.structure.Vertex;
+import org.apache.tinkerpop.gremlin.structure.VertexProperty;
+import org.json.JSONException;
+import org.json.JSONObject;
+import org.junit.Before;
+import org.junit.Rule;
+import org.junit.Test;
+import org.junit.rules.TestName;
+import org.onap.aai.db.props.AAIProperties;
+import org.onap.aai.dbmap.AAIGraph;
+import org.onap.aai.rest.BulkConsumer;
+import org.onap.aai.rest.BulkProcessorTestAbstraction;
+import org.springframework.mock.web.MockHttpServletRequest;
+
+import javax.ws.rs.HttpMethod;
+import javax.ws.rs.core.Response;
+import java.io.IOException;
+import java.util.Iterator;
+
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+import static org.mockito.Mockito.when;
+
+public class BulkSingleTransactionConsumerTest extends BulkProcessorTestAbstraction {
+
+ private BulkSingleTransactionConsumer bulkSingleTransactionConsumer = new BulkSingleTransactionConsumer();
+
+ @Rule
+ public TestName name = new TestName();
+
+ private String sot = "Junit";
+
+ @Before
+ public void before() {
+ sot = "JUNIT-" + name.getMethodName();
+ when(uriInfo.getPath()).thenReturn(uri);
+ when(uriInfo.getPath(false)).thenReturn(uri);
+ headersMultiMap.addFirst("X-FromAppId", sot);
+
+ }
+
+ @Test
+ public void addPserverPatchSamePserverTest() throws IOException {
+
+ String payload = getBulkPayload("single-transaction/put-patch-same-pserver").replaceAll("<methodName>", name.getMethodName());
+ Response response = executeRequest(payload);
+
+ assertEquals("Request success",
+ Response.Status.CREATED.getStatusCode(),
+ response.getStatus());
+ assertEquals("1 vertex from this test in graph",
+ Long.valueOf(1L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next());
+ assertEquals("1 vertex from this test with fqdn = patched-fqdn",
+ Long.valueOf(1L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot)
+ .has("fqdn", "patched-fqdn").count().next());
+
+
+ }
+
+ @Test
+ public void putPserverComplexRelBetween() throws IOException {
+
+ String payload = getBulkPayload("single-transaction/put-pserver-complex-rel-between").replaceAll("<methodName>", name.getMethodName());
+ Response response = executeRequest(payload);
+
+ assertEquals("Request success",
+ Response.Status.CREATED.getStatusCode(),
+ response.getStatus());
+ assertEquals("2 vertex from this test in graph",
+ Long.valueOf(2L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next());
+ assertEquals("1 complex vertex",
+ Long.valueOf(1L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot)
+ .has(AAIProperties.NODE_TYPE, "complex").count().next());
+ assertEquals("1 pserver vertex",
+ Long.valueOf(1L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot)
+ .has(AAIProperties.NODE_TYPE, "pserver").count().next());
+ assertEquals("pserver has edge to complex",
+ Long.valueOf(1L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot)
+ .has(AAIProperties.NODE_TYPE, "pserver")
+ .bothE()
+ .otherV()
+ .has(AAIProperties.NODE_TYPE, "complex")
+ .has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next());
+
+
+ }
+
+ @Test
+ public void putPatchSamePserverPutAnotherPserver() throws IOException {
+ String payload = getBulkPayload("single-transaction/put-patch-same-pserver-put-another-pserver")
+ .replaceAll("<methodName>", name.getMethodName());
+ Response response = executeRequest(payload);
+
+ assertEquals("Request success",
+ Response.Status.CREATED.getStatusCode(),
+ response.getStatus());
+ assertEquals("2 vertex from this test in graph",
+ Long.valueOf(2L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next());
+ assertEquals("pserver 1 has hostname pserver-1-" + name.getMethodName() + " fqdn = patched-fqdn",
+ Long.valueOf(1L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot)
+ .has("hostname", "pserver-1-" + name.getMethodName())
+ .has("fqdn", "patched-fqdn").count().next());
+ assertEquals("pserver 2 has hostname pserver-2-" + name.getMethodName(),
+ Long.valueOf(1L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot)
+ .has("hostname", "pserver-2-" + name.getMethodName()).count().next());
+ }
+
+
+ protected String asString(Vertex v) {
+ final JSONObject result = new JSONObject();
+ Iterator<VertexProperty<Object>> properties = v.properties();
+ Property<Object> pk = null;
+ try {
+ while (properties.hasNext()) {
+ pk = properties.next();
+ result.put(pk.key(), pk.value());
+ }
+ } catch (JSONException e) {
+ e.printStackTrace();
+ }
+
+ return result.toString();
+ }
+
+ @Test
+ public void putPserverComplexRelBetweenDelExistingGvnf() throws IOException {
+
+ AAIGraph.getInstance().getGraph().traversal().addV()
+ .property(AAIProperties.NODE_TYPE, "generic-vnf")
+ .property(AAIProperties.SOURCE_OF_TRUTH, sot)
+ .property(AAIProperties.AAI_URI, "/network/generic-vnfs/generic-vnf/gvnf-putPserverComplexRelBetweenDelExistingGvnf")
+ .property(AAIProperties.RESOURCE_VERSION, "0")
+ .property("vnf-id", "gvnf-" + name.getMethodName())
+ .next();
+ AAIGraph.getInstance().getGraph().tx().commit();
+
+ assertEquals("1 generic-vnf vertex exists before payload",
+ Long.valueOf(1L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot)
+ .has(AAIProperties.NODE_TYPE, "generic-vnf").count().next());
+
+ String payload = getBulkPayload("single-transaction/put-pserver-complex-rel-between-del-existing-gvnf")
+ .replaceAll("<methodName>", name.getMethodName());
+ Response response = executeRequest(payload);
+
+ assertEquals("Request success",
+ Response.Status.CREATED.getStatusCode(),
+ response.getStatus());
+ assertEquals("2 vertex from this test in graph",
+ Long.valueOf(2L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next());
+ assertEquals("1 complex vertex",
+ Long.valueOf(1L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot)
+ .has(AAIProperties.NODE_TYPE, "complex").count().next());
+ assertEquals("1 pserver vertex",
+ Long.valueOf(1L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot)
+ .has(AAIProperties.NODE_TYPE, "pserver").count().next());
+ assertEquals("pserver has edge to complex",
+ Long.valueOf(1L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot)
+ .has(AAIProperties.NODE_TYPE, "pserver")
+ .bothE()
+ .otherV()
+ .has(AAIProperties.NODE_TYPE, "complex")
+ .has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next());
+ assertEquals("0 generic-vnf vertex exists after payload",
+ Long.valueOf(0L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot)
+ .has(AAIProperties.NODE_TYPE, "generic-vnf").count().next());
+
+ assertThat("Response contains 204 status.",
+ response.getEntity().toString(),
+ containsString("\"response-status-code\":204"));
+ }
+
+ @Test
+ public void putPserverComplexRelBetweenDelExistingGvnfFail() throws IOException {
+
+ AAIGraph.getInstance().getGraph().traversal().addV()
+ .property(AAIProperties.NODE_TYPE, "generic-vnf")
+ .property(AAIProperties.SOURCE_OF_TRUTH, sot)
+ .property(AAIProperties.AAI_URI, "/network/generic-vnfs/generic-vnf/gvnf-putPserverComplexRelBetweenDelExistingGvnfFail")
+ .property(AAIProperties.RESOURCE_VERSION, "0")
+ .property("vnf-id", "gvnf-" + name.getMethodName())
+ .next();
+ AAIGraph.getInstance().getGraph().tx().commit();
+
+ assertEquals("1 generic-vnf vertex exists before payload",
+ Long.valueOf(1L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot)
+ .has(AAIProperties.NODE_TYPE, "generic-vnf").count().next());
+
+ String payload = getBulkPayload("single-transaction/put-pserver-complex-rel-between-del-existing-gvnf-fail")
+ .replaceAll("<methodName>", name.getMethodName());
+ Response response = executeRequest(payload);
+
+ assertEquals("Request failed",
+ Response.Status.BAD_REQUEST.getStatusCode(),
+ response.getStatus());
+
+ assertEquals("1 vertex exists after payload due to failure",
+ Long.valueOf(1L),
+ AAIGraph.getInstance().getGraph().newTransaction().traversal().
+ V().has(AAIProperties.SOURCE_OF_TRUTH, sot).count().next());
+
+ assertThat("Response contains correct index of failed operation.",
+ response.getEntity().toString(),
+ containsString("Operation 3 failed with status code (412) and msg"));
+
+ assertThat("Response contains resource version msg for failed transaction.",
+ response.getEntity().toString(),
+ containsString("Precondition Failed:resource-version MISMATCH for delete of generic-vnf"));
+
+ }
+
+ @Test
+ public void checkExceedsLimit() throws IOException{
+
+ String payload = getBulkPayload("single-transaction/pserver-bulk-limit-exceed");
+ Response response = executeRequest(payload);
+
+ assertEquals("Request fails with 400",
+ Response.Status.BAD_REQUEST.getStatusCode(),
+ response.getStatus());
+ assertThat("Response contains payload limit msg.",
+ response.getEntity().toString(),
+ containsString("Payload Limit Reached, reduce payload: Allowed limit = "));
+ }
+
+ @Test
+ public void invalidJson() {
+
+ String payload = "{]}";//malformed json
+ Response response = executeRequest(payload);
+
+ assertEquals("Request fails with 400",
+ Response.Status.BAD_REQUEST.getStatusCode(),
+ response.getStatus());
+ assertThat("Response contains invalid payload msg.",
+ response.getEntity().toString(),
+ containsString("JSON processing error:Input payload does not follow bulk/single-transaction interface"));
+ }
+
+
+ @Test
+ public void noOperations() {
+
+ String payload = "{'operations':[]}";
+ Response response = executeRequest(payload);
+
+ assertEquals("Request fails with 400",
+ Response.Status.BAD_REQUEST.getStatusCode(),
+ response.getStatus());
+ assertThat("Response contains invalid payload msg.",
+ response.getEntity().toString(),
+ containsString("Required Field not passed.: Payload has no objects to operate on"));
+ }
+
+ @Test
+ public void invalidAction() throws IOException {
+
+ String payload = getBulkPayload("single-transaction/invalid-action");
+ Response response = executeRequest(payload);
+
+ assertEquals("Request fails with 400",
+ Response.Status.BAD_REQUEST.getStatusCode(),
+ response.getStatus());
+ assertThat("Response contains invalid payload msg.",
+ response.getEntity().toString(),
+ containsString("JSON processing error:input payload missing required properties"));
+ assertThat("Response contains invalid payload details.",
+ response.getEntity().toString(),
+ containsString("[Operation 0 has invalid action 'create', Operation 1 has invalid action 'destroy']"));
+
+ }
+
+ @Test
+ public void missingFields() throws IOException {
+
+ String payload = getBulkPayload("single-transaction/missing-fields");
+ Response response = executeRequest(payload);
+
+ assertEquals("Request fails with 400",
+ Response.Status.BAD_REQUEST.getStatusCode(),
+ response.getStatus());
+ assertThat("Response contains invalid payload msg.",
+ response.getEntity().toString(),
+ containsString("JSON processing error:input payload missing required properties"));
+ assertThat("Response contains invalid payload details.",
+ response.getEntity().toString(),
+ containsString("[Operation 0 missing 'body', Operation 1 missing 'action', Operation 2 missing 'uri']"));
+
+ }
+
+
+
+
+ protected Response executeRequest(String finalPayload) {
+ MockHttpServletRequest mockReq = new MockHttpServletRequest(HttpMethod.POST, "http://www.test.com");
+
+ return bulkSingleTransactionConsumer.process(
+ finalPayload,
+ schemaVersions.getDefaultVersion().toString(),
+ httpHeaders,
+ uriInfo,
+ mockReq
+ );
+ }
+
+ @Override
+ protected BulkConsumer getConsumer() {
+ return null;
+ }
+
+ @Override
+ protected String getUri() {
+ return "/aai/" + schemaVersions.getDefaultVersion().toString() + "/bulk-single-transaction-multi-operation";
+ }
+} \ No newline at end of file
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerSpringTest.java b/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerSpringTest.java
new file mode 100644
index 0000000..1fae4a7
--- /dev/null
+++ b/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerSpringTest.java
@@ -0,0 +1,143 @@
+/**
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017-2018 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.onap.aai.rest.retired;
+
+import com.att.eelf.configuration.EELFLogger;
+import com.att.eelf.configuration.EELFManager;
+import org.junit.Test;
+import org.onap.aai.rest.AbstractSpringRestTest;
+import org.springframework.http.HttpMethod;
+import org.springframework.http.HttpStatus;
+import org.springframework.http.ResponseEntity;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import static org.junit.Assert.assertEquals;
+public class RetiredConsumerSpringTest extends AbstractSpringRestTest {
+
+ private static final EELFLogger LOGGER = EELFManager.getInstance().getLogger(RetiredConsumerSpringTest.class);
+
+ private Map<String, HttpStatus> httpStatusMap;
+
+ @Test
+ public void testOldVersionsEndpointReturnRetired(){
+ setupOldVersions();
+ executeRestCalls();
+ }
+
+ @Test
+ public void testOldModelsRetired(){
+ setupModelsRetired();
+ executeRestCalls();
+ }
+
+ @Test
+ public void testOldNamedQueriesRetired(){
+ setupNamedQueriesRetired();
+ executeRestCalls();
+ }
+
+ @Test
+ public void testEdgeTagQueryRetired(){
+ setupEdgeTagQueriesRetired();
+ executeRestCalls();
+ }
+
+ @Test
+ public void testSDNZoneQueryRetired(){
+ setupSDNZoneQueryRetired();
+ executeRestCalls();
+ }
+
+ private void setupSDNZoneQueryRetired() {
+ httpStatusMap = new HashMap<>();
+
+ httpStatusMap.put("/aai/v2/search/sdn-zone-query", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v3/search/sdn-zone-query", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v4/search/sdn-zone-query", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v5/search/sdn-zone-query", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v6/search/sdn-zone-query", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v7/search/sdn-zone-query", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v8/search/sdn-zone-query", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v9/search/sdn-zone-query", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v10/search/sdn-zone-query", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v11/search/sdn-zone-query", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v12/search/sdn-zone-query", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v12/search/sdn-zone-query/fjaisdofjasdjf", HttpStatus.GONE);
+ }
+
+ private void setupEdgeTagQueriesRetired() {
+
+ httpStatusMap = new HashMap<>();
+
+ httpStatusMap.put("/aai/v2/search/edge-tag-query", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v2/search/edge-tag-query/", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v2/search/edge-tag-query/something", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v3/search/edge-tag-query/aifjsodifjiasjdfioadjsiofjaiosdj", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v4/search/edge-tag-query/aifjsodifjiasjdfioadjsiofjaiosdj", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v5/search/edge-tag-query/aifjsodifjiasjdfioadjsiofjaiosdj", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v6/search/edge-tag-query/aifjsodifjiasjdfioadjsiofjaiosdj", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v7/search/edge-tag-query/aifjsodifjiasjdfioadjsiofjaiosdj", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v8/search/edge-tag-query/aifjsodifjiasjdfioadjsiofjaiosdj", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v9/search/edge-tag-query/aifjsodifjiasjdfioadjsiofjaiosdj", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v10/search/edge-tag-query/aifjsodifjiasjdfioadjsiofjaiosdj", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v11/search/edge-tag-query/aifjsodifjiasjdfioadjsiofjaiosdj", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v12/search/edge-tag-query/aifjsodifjiasjdfioadjsiofjaiosdj", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v13/search/edge-tag-query/aifjsodifjiasjdfioadjsiofjaiosdj", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v13/search/edge-tag-query", HttpStatus.GONE);
+ }
+
+ private void setupNamedQueriesRetired() {
+ httpStatusMap = new HashMap<>();
+
+ httpStatusMap.put("/aai/v8/cloud-infrastructure/pservers/pserver/samomaisdjfajsfoas", HttpStatus.NOT_FOUND);
+
+ httpStatusMap.put("/aai/v8/service-design-and-creation/named-queries/named-query/samomaisdjfajsfoas", HttpStatus.GONE);
+ }
+
+ protected void executeRestCalls() {
+ httpStatusMap.forEach((url, status) -> {
+ ResponseEntity responseEntity;
+ responseEntity = restTemplate.exchange(baseUrl + url, HttpMethod.GET, httpEntity, String.class);
+ LOGGER.debug("For url {} expected status {} actual status {} and body {}", url, status, responseEntity.getStatusCodeValue(), responseEntity.getBody());
+ assertEquals(status, responseEntity.getStatusCode());
+ });
+ }
+
+ private void setupOldVersions() {
+ httpStatusMap = new HashMap<>();
+
+ httpStatusMap.put("/aai/v2/cloud-infrastructure/pservers/pserver/test-pserver1", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v3/cloud-infrastructure/pservers/pserver/test-pserver1", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v4/cloud-infrastructure/pservers/pserver/test-pserver1", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v5/cloud-infrastructure/pservers/pserver/test-pserver1", HttpStatus.GONE);
+ httpStatusMap.put("/aai/v6/cloud-infrastructure/pservers/pserver/test-pserver1", HttpStatus.GONE);
+ }
+
+ private void setupModelsRetired() {
+
+ httpStatusMap = new HashMap<>();
+
+ httpStatusMap.put("/aai/v8/cloud-infrastructure/pservers/pserver/samomaisdjfajsfoas", HttpStatus.NOT_FOUND);
+
+ httpStatusMap.put("/aai/v8/service-design-and-creation/models/model/samomaisdjfajsfoas", HttpStatus.GONE);
+ }
+}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerTest.java
deleted file mode 100644
index 3c2897c..0000000
--- a/aai-resources/src/test/java/org/onap/aai/rest/retired/RetiredConsumerTest.java
+++ /dev/null
@@ -1,127 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.rest.retired;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.onap.aai.AAISetup;
-import org.onap.aai.introspection.Version;
-
-import javax.ws.rs.core.*;
-import java.util.*;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Mockito.when;
-
-public abstract class RetiredConsumerTest extends AAISetup {
-
- protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
-
- private static final Set<Integer> VALID_HTTP_STATUS_CODES = new HashSet<>();
-
- static {
- VALID_HTTP_STATUS_CODES.add(200);
- VALID_HTTP_STATUS_CODES.add(201);
- VALID_HTTP_STATUS_CODES.add(204);
- }
-
- protected RetiredConsumer retiredConsumer;
- protected HttpHeaders httpHeaders;
- protected UriInfo uriInfo;
-
- private MultivaluedMap<String, String> headersMultiMap;
- private MultivaluedMap<String, String> queryParameters;
-
- private List<String> aaiRequestContextList;
-
- private List<MediaType> outputMediaTypes;
-
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(RetiredConsumer.class.getName());
-
- @Before
- public void setup(){
- logger.info("Starting the setup for the integration tests of Rest Endpoints");
-
- retiredConsumer = getRetiredConsumer();
- httpHeaders = Mockito.mock(HttpHeaders.class);
- uriInfo = Mockito.mock(UriInfo.class);
-
- headersMultiMap = new MultivaluedHashMap<>();
- queryParameters = Mockito.spy(new MultivaluedHashMap<>());
-
- headersMultiMap.add("X-FromAppId", "JUNIT");
- headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
- headersMultiMap.add("Real-Time", "true");
- headersMultiMap.add("Accept", "application/json");
- headersMultiMap.add("aai-request-context", "");
-
- outputMediaTypes = new ArrayList<>();
- outputMediaTypes.add(APPLICATION_JSON);
-
- aaiRequestContextList = new ArrayList<>();
- aaiRequestContextList.add("");
-
- when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
- when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
-
- when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);
-
-
- when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
- when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters);
-
- // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be very unreasonable
- Mockito.doReturn(null).when(queryParameters).remove(anyObject());
-
- when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
- }
-
- @Test
- public void testRetiredForAllEndPoints(){
- when(uriInfo.getPath()).thenReturn("/aai/v3/cloud-infrastructure/pservers/pserver/test-pserver1");
-
- Response response = retiredConsumer.createMessageGet(Version.getLatest().toString(), httpHeaders, uriInfo, null);
- assertNotNull(response);
- assertEquals(Response.Status.GONE.getStatusCode(), response.getStatus());
-
- response = retiredConsumer.createMessagePost(Version.getLatest().toString(), httpHeaders, uriInfo, null);
- assertNotNull(response);
- assertEquals(Response.Status.GONE.getStatusCode(), response.getStatus());
-
- response = retiredConsumer.createMessagePatch(Version.getLatest().toString(), httpHeaders, uriInfo, null);
- assertNotNull(response);
- assertEquals(Response.Status.GONE.getStatusCode(), response.getStatus());
-
- response = retiredConsumer.createMessagePut(Version.getLatest().toString(), httpHeaders, uriInfo, null);
- assertNotNull(response);
- assertEquals(Response.Status.GONE.getStatusCode(), response.getStatus());
-
- response = retiredConsumer.createMessageDelete(Version.getLatest().toString(), httpHeaders, uriInfo, null);
- assertNotNull(response);
- assertEquals(Response.Status.GONE.getStatusCode(), response.getStatus());
- }
-
- public abstract RetiredConsumer getRetiredConsumer();
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/retired/V7V8ModelsTest.java b/aai-resources/src/test/java/org/onap/aai/rest/retired/V7V8ModelsTest.java
deleted file mode 100644
index 76b38af..0000000
--- a/aai-resources/src/test/java/org/onap/aai/rest/retired/V7V8ModelsTest.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.rest.retired;
-
-public class V7V8ModelsTest extends RetiredConsumerTest {
-
- @Override
- public RetiredConsumer getRetiredConsumer() {
- return new V7V8Models();
- }
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/retired/V7V8NamedQueriesTest.java b/aai-resources/src/test/java/org/onap/aai/rest/retired/V7V8NamedQueriesTest.java
deleted file mode 100644
index 88ae287..0000000
--- a/aai-resources/src/test/java/org/onap/aai/rest/retired/V7V8NamedQueriesTest.java
+++ /dev/null
@@ -1,28 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.rest.retired;
-
-public class V7V8NamedQueriesTest extends RetiredConsumerTest {
-
- @Override
- public RetiredConsumer getRetiredConsumer() {
- return new V7V8NamedQueries();
- }
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/tools/ModelVersionTransformerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/tools/ModelVersionTransformerTest.java
deleted file mode 100644
index 1fb048a..0000000
--- a/aai-resources/src/test/java/org/onap/aai/rest/tools/ModelVersionTransformerTest.java
+++ /dev/null
@@ -1,135 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.rest.tools;
-
-import com.att.eelf.configuration.EELFLogger;
-import com.att.eelf.configuration.EELFManager;
-import org.junit.Before;
-import org.junit.BeforeClass;
-import org.junit.Test;
-import org.mockito.Mockito;
-import org.onap.aai.AAISetup;
-import org.onap.aai.dbmap.AAIGraph;
-import org.onap.aai.introspection.ModelInjestor;
-import org.skyscreamer.jsonassert.JSONAssert;
-
-import javax.ws.rs.core.*;
-import java.util.*;
-
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Mockito.when;
-
-public class ModelVersionTransformerTest extends AAISetup {
-
-
- protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
-
- private static final Set<Integer> VALID_HTTP_STATUS_CODES = new HashSet<>();
-
- static {
- VALID_HTTP_STATUS_CODES.add(200);
- VALID_HTTP_STATUS_CODES.add(201);
- VALID_HTTP_STATUS_CODES.add(204);
- }
-
- private ModelVersionTransformer modelVersionTransformer;
-
- private HttpHeaders httpHeaders;
-
- private UriInfo uriInfo;
-
- private MultivaluedMap<String, String> headersMultiMap;
- private MultivaluedMap<String, String> queryParameters;
-
- private List<String> aaiRequestContextList;
-
- private List<MediaType> outputMediaTypes;
-
- private static final EELFLogger logger = EELFManager.getInstance().getLogger(ModelVersionTransformerTest.class.getName());
-
- @BeforeClass
- public static void setupRest(){
- AAIGraph.getInstance();
- ModelInjestor.getInstance();
- }
-
- @Before
- public void setup(){
- logger.info("Starting the setup for the integration tests of Rest Endpoints");
-
- modelVersionTransformer = new ModelVersionTransformer();
- httpHeaders = Mockito.mock(HttpHeaders.class);
- uriInfo = Mockito.mock(UriInfo.class);
-
- headersMultiMap = new MultivaluedHashMap<>();
- queryParameters = Mockito.spy(new MultivaluedHashMap<>());
-
- headersMultiMap.add("X-FromAppId", "JUNIT");
- headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
- headersMultiMap.add("Real-Time", "true");
- headersMultiMap.add("Content-Type", "application/xml");
- headersMultiMap.add("Accept", "application/json");
- headersMultiMap.add("aai-request-context", "");
-
- outputMediaTypes = new ArrayList<>();
- outputMediaTypes.add(APPLICATION_JSON);
-
- aaiRequestContextList = new ArrayList<>();
- aaiRequestContextList.add("");
-
- when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
- when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
- when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);
-
-
- when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
- when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters);
-
- // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be very unreasonable
- Mockito.doReturn(null).when(queryParameters).remove(anyObject());
-
- when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
- }
-
- @Test
- public void modelTransform() throws Exception {
-
- String modelXmlPayload = getPayload("payloads/modeltransforms/model.xml");
- String modelJsonPayload = getPayload("payloads/modeltransforms/model.json");
-
- String uri = "modeltransform";
-
- when(uriInfo.getPath()).thenReturn(uri);
- // Comment the following line for the null pointer exception
- when(uriInfo.getPath(false)).thenReturn(uri);
-
- outputMediaTypes = new ArrayList<>();
- outputMediaTypes.add(MediaType.valueOf("application/xml"));
-
- when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
- when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
- when(httpHeaders.getMediaType()).thenReturn(MediaType.valueOf("application/xml"));
-
- Response response = modelVersionTransformer.modelTransform(modelXmlPayload,uri, httpHeaders, uriInfo, null);
-
- assertNotNull(response);
- }
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/retired/V3ThroughV7ConsumerTest.java b/aai-resources/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java
index fef695a..f17257b 100644
--- a/aai-resources/src/test/java/org/onap/aai/rest/retired/V3ThroughV7ConsumerTest.java
+++ b/aai-resources/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java
@@ -17,12 +17,18 @@
* limitations under the License.
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.rest.retired;
+package org.onap.aai.rest.util;
-public class V3ThroughV7ConsumerTest extends RetiredConsumerTest {
+import org.junit.Test;
- @Override
- public RetiredConsumer getRetiredConsumer() {
- return new V3ThroughV7Consumer();
+import static org.junit.Assert.assertNotNull;
+
+public class LogFormatToolsTest {
+
+ @Test
+ public void testLogFormatTools(){
+
+ String dateTime = new LogFormatTools().getCurrentDateTime();
+ assertNotNull(dateTime);
}
}
diff --git a/aai-resources/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java b/aai-resources/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java
index 483d254..136b64e 100644
--- a/aai-resources/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java
+++ b/aai-resources/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java
@@ -75,6 +75,7 @@ public class ValidateEncodingTest {
assertEquals(false, validator.validate(mockUriInfo));
}
+
@Test
public void goodQueryParams() throws UnsupportedEncodingException {
MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>();
@@ -87,6 +88,18 @@ public class ValidateEncodingTest {
assertEquals(true, validator.validate(mockUriInfo));
}
+
+ @Test
+ public void testWhenQueryParameterHasPlusSignItShouldPass() throws UnsupportedEncodingException {
+
+ MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>();
+ map.putSingle("some-key", "test+one+two+three");
+ UriInfo mockUriInfo = getMockUriInfo("", map);
+
+ ValidateEncoding validator = ValidateEncoding.getInstance();
+
+ assertEquals(true, validator.validate(mockUriInfo));
+ }
private UriInfo getMockUriInfo(String path, MultivaluedMap<String, String> map) {
UriInfo mockUriInfo = Mockito.mock(UriInfo.class);
diff --git a/aai-resources/src/test/java/org/onap/aai/schema/db/ManageSchemaTest.java b/aai-resources/src/test/java/org/onap/aai/schema/db/ManageSchemaTest.java
deleted file mode 100644
index de5eba1..0000000
--- a/aai-resources/src/test/java/org/onap/aai/schema/db/ManageSchemaTest.java
+++ /dev/null
@@ -1,111 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.schema.db;
-
-import org.janusgraph.core.JanusGraphFactory;
-import org.janusgraph.core.JanusGraph;
-import org.janusgraph.core.schema.JanusGraphManagement;
-import org.codehaus.jackson.JsonParseException;
-import org.codehaus.jackson.map.JsonMappingException;
-import org.codehaus.jackson.map.ObjectMapper;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.onap.aai.AAISetup;
-import org.onap.aai.db.schema.DBIndex;
-import org.onap.aai.db.schema.ManageJanusGraphSchema;
-
-import java.io.IOException;
-import java.util.Set;
-
-@Ignore("not ready yet")
-public class ManageSchemaTest extends AAISetup {
-
- private JanusGraph graph = null;
-
- @Before
- public void beforeTest() {
- graph = JanusGraphFactory.open("bundleconfig-local/etc/appprops/aaiconfig.properties");
- }
-
- /*
- @Test
- public void populateEmptyGraph() {
- ManageJanusGraphSchema schema = new ManageJanusGraphSchema(graph);
- schema.buildSchema();
- }
-
- @Test
- public void modifyIndex() {
- ManageJanusGraphSchema schema = new ManageJanusGraphSchema(graph);
- schema.buildSchema();
- Vertex v = graph.addVertex();
- v.setProperty("aai-node-type", "pserver");
- v.setProperty("hostname", "test1");
- v.setProperty("internet-topology", "test2");
- graph.commit();
- DBIndex index = new DBIndex();
- index.setName("internet-topology");
- index.setUnique(false);
- schema.updateIndex(index);
-
- }
- */
- @Test
- public void closeRunningInstances() {
-
- JanusGraphManagement mgmt = graph.openManagement();
- Set<String> instances = mgmt.getOpenInstances();
-
- for (String instance : instances) {
-
- if (!instance.contains("(current)")) {
- mgmt.forceCloseInstance(instance);
- }
- }
- mgmt.commit();
-
- graph.close();
-
- }
- @Test
- public void addNewIndex() throws JsonParseException, JsonMappingException, IOException {
- ObjectMapper mapper = new ObjectMapper();
- String content = " {\r\n" +
- " \"name\" : \"equipment-name\",\r\n" +
- " \"unique\" : false,\r\n" +
- " \"properties\" : [ {\r\n" +
- " \"name\" : \"equipment-name\",\r\n" +
- " \"cardinality\" : \"SINGLE\",\r\n" +
- " \"typeClass\" : \"java.lang.String\"\r\n" +
- " } ]\r\n" +
- " }";
- DBIndex index = mapper.readValue(content, DBIndex.class);
- ManageJanusGraphSchema schema = new ManageJanusGraphSchema(graph);
- JanusGraphManagement mgmt = graph.openManagement();
- Set<String> instances = mgmt.getOpenInstances();
- System.out.println(instances);
- schema.updateIndex(index);
-
- graph.close();
-
- }
-
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java b/aai-resources/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java
deleted file mode 100644
index 609de5f..0000000
--- a/aai-resources/src/test/java/org/onap/aai/serialization/queryformats/QueryFormatTestHelper.java
+++ /dev/null
@@ -1,74 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.serialization.queryformats;
-
-import org.apache.tinkerpop.gremlin.structure.Graph;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.apache.tinkerpop.gremlin.structure.io.IoCore;
-import org.apache.tinkerpop.gremlin.tinkergraph.structure.TinkerGraph;
-import org.mockito.invocation.InvocationOnMock;
-import org.mockito.stubbing.Answer;
-import org.onap.aai.db.props.AAIProperties;
-import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
-import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
-
-import java.io.IOException;
-import java.lang.reflect.Field;
-import java.lang.reflect.Modifier;
-
-import static org.mockito.Matchers.isA;
-import static org.mockito.Mockito.when;
-
-public class QueryFormatTestHelper {
-
-
- public static final String testResources = "src/test/resources/org.onap.aai/serialization/queryformats/";
- public static final String graphsonResources = "src/test/resources/org.onap.aai/serialization/queryformats/graphson/";
-
-
- public static void mockPathed(UrlBuilder mock) throws AAIFormatVertexException {
- Answer<String> answer = new Answer<String>() {
- public String answer(InvocationOnMock invocation) throws Throwable {
- Vertex v = invocation.getArgumentAt(0, Vertex.class);
-
- return v.<String>property(AAIProperties.AAI_URI).orElse("urimissing");
- }
- };
- when(mock.pathed(isA(Vertex.class))).thenAnswer(answer);
-
- }
-
- public static Graph loadGraphson(String fileName) throws IOException {
- final Graph graph = TinkerGraph.open();
- graph.io(IoCore.graphson()).readGraph(QueryFormatTestHelper.graphsonResources + fileName);
-
- return graph;
- }
-
- public static void setFinalStatic(Field field, Object newValue) throws Exception {
- field.setAccessible(true);
- // remove final modifier from field
- Field modifiersField = Field.class.getDeclaredField("modifiers");
- modifiersField.setAccessible(true);
- modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
- field.set(null, newValue);
- }
-
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatSpec.java b/aai-resources/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatSpec.java
deleted file mode 100644
index 19a2ffd..0000000
--- a/aai-resources/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatSpec.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.serialization.queryformats;
-
-import com.bazaarvoice.jolt.JsonUtils;
-import com.google.gson.Gson;
-import com.google.gson.JsonObject;
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
-import org.apache.tinkerpop.gremlin.structure.Graph;
-import org.onap.aai.transforms.JoltTestUtil;
-
-import java.io.IOException;
-import java.util.List;
-
-public class ResourceFormatSpec {
-
-
- private final Graph graph;
- public ResourceFormatSpec() throws IOException {
-
- this.graph = QueryFormatTestHelper.loadGraphson("resource.graphson");
- }
-
-
- public void verifyFormat(Formatter formatter, String fileName) throws IOException {
- List<Object> vertices = graph.traversal().V().not(__.has("aai-node-type", "cloud-region")).map(x -> (Object)x.get()).toList();
-
- JsonObject obj = formatter.output(vertices);
- String jsonStr = new Gson().toJson(obj);
- Object actual = JsonUtils.jsonToObject(jsonStr);
-
- Object expected = JsonUtils.filepathToObject(QueryFormatTestHelper.testResources + fileName);
-
- JoltTestUtil.runArrayOrderObliviousDiffy("Failed case ", expected, actual);
- }
-
- public void mockToJson(String result) {
-
-
-
- }
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatTest.java b/aai-resources/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatTest.java
deleted file mode 100644
index 5379676..0000000
--- a/aai-resources/src/test/java/org/onap/aai/serialization/queryformats/ResourceFormatTest.java
+++ /dev/null
@@ -1,77 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.serialization.queryformats;
-
-import com.google.gson.JsonObject;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
-import org.onap.aai.introspection.Loader;
-import org.onap.aai.serialization.db.DBSerializer;
-import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexException;
-import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
-
-import java.io.IOException;
-
-import static org.mockito.Matchers.isA;
-import static org.mockito.Mockito.doReturn;
-import static org.mockito.Mockito.spy;
-
-@Ignore
-public class ResourceFormatTest {
-
- @Mock
- private UrlBuilder urlBuilder;
- @Mock
- private DBSerializer serializer;
- @Mock
- private Loader loader;
-
- private ResourceFormatSpec spec;
-
- @Before
- public void setup() throws Exception {
- spec = new ResourceFormatSpec();
- MockitoAnnotations.initMocks(this);
- }
-
- @Test
- public void resourceAndUrl() throws Exception {
- QueryFormatTestHelper.mockPathed(urlBuilder);
- Resource resource = new Resource.Builder(loader, serializer, urlBuilder).includeUrl().build();
- Resource spy = spy(resource);
- doReturn(new JsonObject()).when(spy).vertexToJsonObject(isA(Vertex.class));
- Formatter formatter = new Formatter(spy);
- spec.verifyFormat(formatter, "resource_and_url-format.json");
- }
-
- @Test
- public void resource() throws IOException, AAIFormatVertexException {
- QueryFormatTestHelper.mockPathed(urlBuilder);
- Resource resource = new Resource.Builder(loader, serializer, urlBuilder).build();
- Resource spy = spy(resource);
- doReturn(new JsonObject()).when(spy).vertexToJsonObject(isA(Vertex.class));
- Formatter formatter = new Formatter(spy);
- spec.verifyFormat(formatter, "resource-format.json");
- }
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/transforms/JoltTestUtil.java b/aai-resources/src/test/java/org/onap/aai/transforms/JoltTestUtil.java
deleted file mode 100644
index 07832a8..0000000
--- a/aai-resources/src/test/java/org/onap/aai/transforms/JoltTestUtil.java
+++ /dev/null
@@ -1,59 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.transforms;
-
-
-import com.bazaarvoice.jolt.ArrayOrderObliviousDiffy;
-import com.bazaarvoice.jolt.Diffy;
-import com.bazaarvoice.jolt.JsonUtils;
-import org.junit.Assert;
-
-import java.io.IOException;
-
-public class JoltTestUtil {
-
- private static final Diffy diffy = new Diffy();
- private static final Diffy arrayOrderObliviousDiffy = new ArrayOrderObliviousDiffy();
-
- public static void runDiffy( String failureMessage, Object expected, Object actual ) throws IOException {
- runDiffy( diffy, failureMessage, expected, actual );
- }
-
- public static void runDiffy( Object expected, Object actual ) throws IOException {
- runDiffy( diffy, "Failed", expected, actual );
- }
-
- public static void runArrayOrderObliviousDiffy( String failureMessage, Object expected, Object actual ) throws IOException {
- runDiffy( arrayOrderObliviousDiffy, failureMessage, expected, actual );
- }
-
- public static void runArrayOrderObliviousDiffy( Object expected, Object actual ) throws IOException {
- runDiffy( arrayOrderObliviousDiffy, "Failed", expected, actual );
- }
-
-
- private static void runDiffy( Diffy diffy, String failureMessage, Object expected, Object actual ) {
- String actualObject = JsonUtils.toPrettyJsonString( actual );
- Diffy.Result result = diffy.diff( expected, actual );
- if (!result.isEmpty()) {
- Assert.fail( "\nActual object\n" + actualObject + "\n" + failureMessage + "\nDiffy output\n" + result.toString());
- }
- }
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverterTest.java b/aai-resources/src/test/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverterTest.java
deleted file mode 100644
index c88e005..0000000
--- a/aai-resources/src/test/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverterTest.java
+++ /dev/null
@@ -1,72 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.transforms;
-
-import org.junit.Test;
-import org.junit.runner.RunWith;
-import org.junit.runners.Parameterized;
-import org.junit.runners.Parameterized.Parameters;
-
-import java.util.Arrays;
-import java.util.Collection;
-
-import static org.junit.Assert.assertEquals;
-
-@RunWith(Parameterized.class)
-public class LowerHyphenToLowerCamelConverterTest {
-
- private Converter converter = new LowerHyphenToLowerCamelConverter();
-
- private String input;
- private String expected;
-
- public LowerHyphenToLowerCamelConverterTest(String input, String expected){
- this.input = input;
- this.expected = expected;
- }
-
- /**
- * Data Provider for the Lower Hyphen to Camel Converter Tests
- * Make sure the capitalization is not lost during the conversion
- * @return
- */
- @Parameters
- public static Collection<Object[]> data(){
-
- return Arrays.asList(new Object[][]{
- {null, null},
- {"test-name", "testName"},
- {"test---name", "testName"}, // Case multiple
- {"testName", "testName"}, // Case where upper case word shouldn't be lowercased
- {"test-name-cool", "testNameCool"},
- {"test-name-Cool", "testNameCool"},
- {"test-name-Cool-Name-wow----Rest", "testNameCoolNameWowRest"},
- {"test-name#fast#", "testName#fast#"},
- {"test-name---", "testName"},
- {"----test-name", "TestName"},
- });
- }
-
- @Test
- public void testIfInputSuccessfullyModified(){
- String actual = converter.convert(input);
- assertEquals(expected, actual);
- }
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/transforms/MapTraverserTest.java b/aai-resources/src/test/java/org/onap/aai/transforms/MapTraverserTest.java
deleted file mode 100644
index fef84c2..0000000
--- a/aai-resources/src/test/java/org/onap/aai/transforms/MapTraverserTest.java
+++ /dev/null
@@ -1,53 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.transforms;
-
-import com.bazaarvoice.jolt.JsonUtils;
-import org.junit.Test;
-
-import java.io.IOException;
-import java.util.Map;
-
-public class MapTraverserTest {
-
- private final String testResources = "src/test/resources/maputils/testcases/";
-
- private String[] testCases = { "TestCase1.json", "TestCase2.json" };
- private MapTraverser traverser = new MapTraverser(new LowerCamelToLowerHyphenConverter());
-
- @Test(expected = NullPointerException.class)
- public void testIfMapIsNullThrowNullPointerException(){
- Map<String, Object> map = null;
- traverser.convertKeys(map);
- }
-
- @Test
- public void runTestCases() throws IOException {
-
- for(String testCase : testCases){
- Map<String, Object> values = JsonUtils.filepathToMap(testResources + testCase);
-
- Object input = values.get("input");
- Object actual = traverser.convertKeys((Map<String, Object>)input);
- Object output = values.get("output");
- JoltTestUtil.runArrayOrderObliviousDiffy( "failed case " + testCase, output, actual );
- }
- }
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/util/AAIRSyncUtilityTest.java b/aai-resources/src/test/java/org/onap/aai/util/AAIRSyncUtilityTest.java
deleted file mode 100644
index c1aeff9..0000000
--- a/aai-resources/src/test/java/org/onap/aai/util/AAIRSyncUtilityTest.java
+++ /dev/null
@@ -1,211 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.util;
-
-
-import org.junit.Before;
-import org.junit.Ignore;
-import org.junit.Test;
-import org.onap.aai.AAISetup;
-
-import java.io.File;
-import java.lang.reflect.Field;
-import java.lang.reflect.InvocationTargetException;
-import java.lang.reflect.Method;
-import java.lang.reflect.Modifier;
-import java.net.InetAddress;
-import java.net.UnknownHostException;
-import java.nio.file.Files;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.StringTokenizer;
-import java.util.UUID;
-
-import static org.junit.Assert.*;
-
-@Ignore
-public class AAIRSyncUtilityTest extends AAISetup {
-
- AAIRSyncUtility syncUtil;
- AAIRSyncUtility syncUtilOmitDoCommand;
- AAIConfig aaiConfig;
- String hostName;
- String transId = UUID.randomUUID().toString();
-
- /**
- * Initialize.
- */
- @Before
- public void initialize(){
- syncUtil = new AAIRSyncUtility();
-
- syncUtilOmitDoCommand = new AAIRSyncUtility(){
- /**
- * {@inheritDoc}
- */
- @Override
- public int doCommand(List<String> command) throws Exception
- {
- return 1;
- }
- };
-
- partialSetupForAAIConfig();
-
- InetAddress ip = null;
- try {
- ip = InetAddress.getLocalHost();
- } catch (UnknownHostException e2) {
- e2.printStackTrace();
- }
- hostName = ip.getHostName();
- }
-
-
- /**
- * Test sendRsync.
- */
- @Test
- public void testSendRsyncCommand(){
- syncUtilOmitDoCommand.sendRsyncCommand(transId, "RandomFileName");
- //TODO write codes to check what is being logged
- }
-
- /**
- * Test getHost.
- */
- @Test
- public void testGetHost(){
-
- String returnedHost = null;
- Method getHostMethod = makePublic("getHost");
- try {
- returnedHost = (String)getHostMethod.invoke(syncUtil, null);
- } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
- e.printStackTrace();
- }
-
- assertEquals("Host name didn't match", returnedHost, hostName);
- }
-
- /**
- * Test getRemoteHostList.
- */
- @Test
- public void testGetRemoteHostList(){
- String localHost = "host_local";
- String remoteHost1 = "hostR1";
- String remoteHost2 = "hostR2";
- ArrayList<String> remotes = new ArrayList<String>();
- remotes.add(remoteHost1);
- remotes.add(remoteHost2);
-
- StringTokenizer stTokenizer = new StringTokenizer(remoteHost1+"\r"+remoteHost2+"\r"+localHost);
-
- Method m = makePublic("getRemoteHostList");
- try {
- assertEquals("Remote host missing", remotes, m.invoke(syncUtil, stTokenizer, localHost));
- } catch (IllegalAccessException | IllegalArgumentException | InvocationTargetException e) {
- e.printStackTrace();
- }
- }
-
- /**
- * Test doCommand.
- */
- @Test
- public void testDoCommand(){
-
- assertTrue("Don't have execute permissions", Files.isExecutable(new File(".").toPath()));
-
- List<String> commands = new ArrayList<String>();
- commands.add("ping");
- commands.add("google.com");
- try {
- assertEquals("Failed to execute commands", 1, syncUtilOmitDoCommand.doCommand(commands));
- } catch (Exception e) {
- fail("Failed to execute a command");
- e.printStackTrace();
- }
-
- }
-
- /**
- * Test doCommand with null.
- */
- @Test
- public void testDoCommand_withNull(){
- assertTrue("Don't have execute permissions", Files.isExecutable(new File(".").toPath()));
- try {
- assertEquals("This should be unreachable", 1, syncUtil.doCommand(null));
- } catch (Exception e) {
- assertTrue("Expecting an NPE from ProcessBuilder", e instanceof NullPointerException);
- }
-
- }
-
-
- /**
- * Helper method to covert access type of a method from private to public .
- *
- * @param privateMethodName Method which is private originally
- * @return method object with 'access type = 'public'
- */
- public Method makePublic(String privateMethodName){
- Method targetMethod = null;
- try {
- if (privateMethodName.equals("getHost"))
- targetMethod = AAIRSyncUtility.class.getDeclaredMethod(privateMethodName, null);
- else if (privateMethodName.equals("getRemoteHostList"))
- targetMethod = AAIRSyncUtility.class.getDeclaredMethod(privateMethodName, StringTokenizer.class, String.class);
- } catch (NoSuchMethodException | SecurityException e) {
- e.printStackTrace();
- }
- targetMethod.setAccessible(true);
- return targetMethod;
- }
-
- /**
- * Helper method to load aai config from test configuration file
- * This requires that the 'test_aaiconfig.properties' file is available
- */
- static void setFinalStatic(Field field, Object newValue) throws Exception {
- field.setAccessible(true);
- Field modifiersField = Field.class.getDeclaredField("modifiers");
- modifiersField.setAccessible(true);
- modifiersField.setInt(field, field.getModifiers() & ~Modifier.FINAL);
- field.set(null, newValue);
- }
-
- /**
- * Helper method to setup AAIConfig for test.
- */
- public void partialSetupForAAIConfig(){
- try {
- setFinalStatic(AAIConfig.class.getDeclaredField("GlobalPropFileName"), "src/test/resources/bundleconfig-local/etc/appprops/aaiconfig.properties");
- }
- catch (SecurityException e) {fail();}
- catch (NoSuchFieldException e) {fail();}
- catch (Exception e) {fail();}
-
- AAIConfig.reloadConfig();
- }
-
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/util/DataConversionHelperTest.java b/aai-resources/src/test/java/org/onap/aai/util/DataConversionHelperTest.java
deleted file mode 100644
index 3acbf03..0000000
--- a/aai-resources/src/test/java/org/onap/aai/util/DataConversionHelperTest.java
+++ /dev/null
@@ -1,87 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.util;
-
-import org.junit.Rule;
-import org.junit.Test;
-import org.powermock.modules.agent.PowerMockAgent;
-import org.powermock.modules.junit4.rule.PowerMockRule;
-
-import static org.junit.Assert.assertEquals;
-
-public class DataConversionHelperTest {
-
- @Rule
- public PowerMockRule rule = new PowerMockRule();
-
- static {
- PowerMockAgent.initializeIfNeeded();
- }
-
- /**
- * Test convertIPVersionNumToString with value "4".
- */
- @Test
- public void testConvertIPVersionNumToString_withNum4(){
- assertEquals(DataConversionHelper.IPVERSION_IPV4, DataConversionHelper.convertIPVersionNumToString("4"));
- }
-
- /**
- * Test convertIPVersionNumToString with value "6".
- */
- @Test
- public void testConvertIPVersionNumToString_withNum6(){
- assertEquals(DataConversionHelper.IPVERSION_IPV6, DataConversionHelper.convertIPVersionNumToString("6"));
- }
-
- /**
- * Test convertIPVersionNumToString with a value other than "4" or "6".
- */
- @Test
- public void testConvertIPVersionNumToString_withAThirdNumber(){
- assertEquals(DataConversionHelper.IPVERSION_UNKNOWN, DataConversionHelper.convertIPVersionNumToString("-1"));
- }
-
- /**
- * Test convertIPVersionStringToNum with "v4".
- */
- @Test
- public void testConvertIPVersionStringToNum_withV4(){
- assertEquals("4", DataConversionHelper.convertIPVersionStringToNum(DataConversionHelper.IPVERSION_IPV4));
- }
-
- /**
- * Test convertIPVersionStringToNum with "v6".
- */
- @Test
- public void testConvertIPVersionStringToNum_withV6(){
- assertEquals("6", DataConversionHelper.convertIPVersionStringToNum(DataConversionHelper.IPVERSION_IPV6));
- }
-
- /**
- * Test convertIPVersionStringToNum with an illegal version.
- */
- @Test
- public void testConvertIPVersionStringToNum_withRandomString(){
- assertEquals("0", DataConversionHelper.convertIPVersionStringToNum("test string"));
- }
-
-
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/util/DbTestConfig.java b/aai-resources/src/test/java/org/onap/aai/util/DbTestConfig.java
deleted file mode 100644
index 09e4cd7..0000000
--- a/aai-resources/src/test/java/org/onap/aai/util/DbTestConfig.java
+++ /dev/null
@@ -1,294 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.util;
-
-import java.io.*;
-import java.net.InetAddress;
-import java.util.*;
-
-public class DbTestConfig {
-
- public static final String AUDIT_FILESEP = (System.getProperty("file.separator") == null) ? "/" : System.getProperty("file.separator");
- public static final String AUDIT_HOME = (System.getProperty("audit.home") == null) ? AUDIT_FILESEP + "opt" + AUDIT_FILESEP + "audit" : System.getProperty("audit.home");
- public static final String AuditPropFilename = "c:\\tmp\\auditConfig.prop";
- public static final String AUDIT_CONFIG_CHECKINGTIME = "audit.config.checktime";
- public static final String AUDIT_NODENAME = "localhost";
- public static final String AUDIT_DEBUG = "audit.config.debug";
-
- private static Properties serverProps;
- private static boolean propsInitialized = false;
- private static boolean timerSet = false;
- private static Timer timer = null;
-
- private static String propFile = null;
-
- /**
- * Inits the.
- *
- * @param propertyFile the property file
- */
- public synchronized static void init(String propertyFile) {
- propFile = propertyFile;
- init();
- }
-
- /**
- * Inits the.
- */
- public synchronized static void init() {
- System.out.println("Initializing Config");
-
- DbTestConfig.getConfigFile();
- DbTestConfig.reloadConfig();
-
- if ( propFile == null)
- propFile = AuditPropFilename;
- TimerTask task = null;
- task = new DbTestFileWatcher ( new File(propFile)) {
- protected void onChange( File file ) {
- // here we implement the onChange
- DbTestConfig.reloadConfig();
- }
- };
-
- if (!timerSet) {
- timerSet = true;
- // repeat the check every second
- timer = new Timer();
- String fwi = DbTestConfig.get(AUDIT_CONFIG_CHECKINGTIME);
- timer.schedule( task , new Date(), Integer.parseInt(fwi) );
- System.out.println("Config Watcher Interval=" + fwi);
-
- System.out.println("File" + propFile+" Loaded!");
- }
-
- }
-
- /**
- * Cleanup.
- */
- public static void cleanup() {
- timer.cancel();
- }
-
- /**
- * Gets the config file.
- *
- * @return the config file
- */
- public static String getConfigFile() {
- return propFile;
- }
-
- /**
- * Reload config.
- */
- public synchronized static void reloadConfig() {
-
- String propFileName = propFile;
-
- Properties newServerProps = null;
-
- System.out.println("Reloading config from "+propFileName);
-
- try {
- InputStream is = new FileInputStream(propFileName);
- newServerProps = new Properties();
- newServerProps.load(is);
- propsInitialized = true;
-
- serverProps = newServerProps;
- if (get(AUDIT_DEBUG).equals("on")) {
- serverProps.list(System.out);
- }
- newServerProps = null;
-
- } catch (FileNotFoundException fnfe) {
- System.out.println("AuditConfig: " + propFileName + ". FileNotFoundException: "+fnfe.getMessage());
- } catch (IOException e) {
- System.out.println("AuditConfig: " + propFileName + ". IOException: "+e.getMessage());
- }
- }
-
- /**
- * Gets the.
- *
- * @param key the key
- * @param defaultValue the default value
- * @return the string
- */
- public static String get(String key, String defaultValue) {
- String result = defaultValue;
- try {
- result = get (key);
- }
- catch ( Exception a ) {
- }
- return result;
- }
-
- /**
- * Gets the.
- *
- * @param key the key
- * @return the string
- */
- public static String get(String key) {
- String response = null;
-
- if (key.equals(AUDIT_NODENAME)) {
- // Get this from InetAddress rather than the properties file
- String nodeName = getNodeName();
- if (nodeName != null) {
- return nodeName;
- }
- // else get from property file
- }
-
- if (!propsInitialized || (serverProps == null)) {
- reloadConfig();
- }
- if (!serverProps.containsKey(key)) {
- System.out.println( "Property key "+key+" cannot be found");
- } else {
- response = serverProps.getProperty(key);
- if (response == null || response.isEmpty()) {
- System.out.println("Property key "+key+" is null or empty");
- }
- }
- return response;
- }
-
- /**
- * Gets the int.
- *
- * @param key the key
- * @return the int
- */
- public static int getInt(String key) {
- return Integer.valueOf(DbTestConfig.get(key));
- }
-
- /**
- * Gets the server props.
- *
- * @return the server props
- */
- public static Properties getServerProps() {
- return serverProps;
- }
-
- /**
- * Gets the node name.
- *
- * @return the node name
- */
- public static String getNodeName() {
- try {
- InetAddress ip = InetAddress.getLocalHost();
- if (ip != null) {
- String hostname = ip.getHostName();
- if (hostname != null) {
- return hostname;
- }
- }
- } catch (Exception e) {
- return null;
- }
- return null;
- }
-
- /**
- * Extracts a specific property key subset from the known properties.
- * The prefix may be removed from the keys in the resulting dictionary,
- * or it may be kept. In the latter case, exact matches on the prefix
- * will also be copied into the resulting dictionary.
- *
- * @param prefix is the key prefix to filter the properties by.
- * @param keepPrefix if true, the key prefix is kept in the resulting
- * dictionary. As side-effect, a key that matches the prefix exactly
- * will also be copied. If false, the resulting dictionary's keys are
- * shortened by the prefix. An exact prefix match will not be copied,
- * as it would result in an empty string key.
- * @return a property dictionary matching the filter key. May be
- * an empty dictionary, if no prefix matches were found.
- *
- * @see #getProperty( String ) is used to assemble matches
- */
- public static Properties matchingSubset(String prefix, boolean keepPrefix) {
- Properties result = new Properties();
-
- // sanity check
- if (prefix == null || prefix.length() == 0) {
- return result;
- }
-
- String prefixMatch; // match prefix strings with this
- String prefixSelf; // match self with this
- if (prefix.charAt(prefix.length() - 1) != '.') {
- // prefix does not end in a dot
- prefixSelf = prefix;
- prefixMatch = prefix + '.';
- } else {
- // prefix does end in one dot, remove for exact matches
- prefixSelf = prefix.substring(0, prefix.length() - 1);
- prefixMatch = prefix;
- }
- // POSTCONDITION: prefixMatch and prefixSelf are initialized!
-
- // now add all matches into the resulting properties.
- // Remark 1: #propertyNames() will contain the System properties!
- // Remark 2: We need to give priority to System properties. This is done
- // automatically by calling this class's getProperty method.
- String key;
- for (Enumeration e = serverProps.keys(); e.hasMoreElements(); ) {
- key = (String) e.nextElement();
-
- if (keepPrefix) {
- // keep full prefix in result, also copy direct matches
- if (key.startsWith(prefixMatch) || key.equals(prefixSelf)) {
- result.setProperty(key, serverProps.getProperty(key));
- }
- } else {
- // remove full prefix in result, dont copy direct matches
- if (key.startsWith(prefixMatch)) {
- result.setProperty(key.substring(prefixMatch.length()), serverProps.getProperty(key));
- }
- }
- }
-
- // done
- return result;
- }
-
-
-
- /**
- * The main method.
- *
- * @param args the arguments
- */
- public static void main(String[] args) {
- // TODO Auto-generated method stub
- DbTestConfig.init( );
-
- }
-
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/util/DbTestFileWatcher.java b/aai-resources/src/test/java/org/onap/aai/util/DbTestFileWatcher.java
deleted file mode 100644
index 60b9039..0000000
--- a/aai-resources/src/test/java/org/onap/aai/util/DbTestFileWatcher.java
+++ /dev/null
@@ -1,63 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.util;
-
-import java.io.File;
-import java.util.TimerTask;
-
-public abstract class DbTestFileWatcher extends TimerTask {
- private long timeStamp;
- private File file;
-
- /**
- * Instantiates a new db test file watcher.
- *
- * @param file the file
- */
- public DbTestFileWatcher( File file ) {
- this.file = file;
- this.timeStamp = file.lastModified();
- }
-
- /**
- * {@inheritDoc}
- */
- public final void run() {
- long timeStamp = file.lastModified();
-
- if( (timeStamp - this.timeStamp) > 500 ) {
- this.timeStamp = timeStamp;
- onChange(file);
- }
- try {
- Thread.sleep(1000);
- } catch (InterruptedException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
- }
-
- /**
- * On change.
- *
- * @param file the file
- */
- protected abstract void onChange( File file );
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/util/DbTestGetFileTime.java b/aai-resources/src/test/java/org/onap/aai/util/DbTestGetFileTime.java
deleted file mode 100644
index fb1f1ee..0000000
--- a/aai-resources/src/test/java/org/onap/aai/util/DbTestGetFileTime.java
+++ /dev/null
@@ -1,54 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.util;
-
-import java.io.File;
-import java.io.IOException;
-import java.nio.file.Files;
-import java.nio.file.Path;
-import java.nio.file.Paths;
-import java.nio.file.attribute.BasicFileAttributeView;
-import java.nio.file.attribute.BasicFileAttributes;
-import java.nio.file.attribute.FileTime;
-
-public class DbTestGetFileTime {
-
-
- /**
- * Creates the file return time.
- *
- * @param path the path
- * @return the file time
- * @throws IOException Signals that an I/O exception has occurred.
- */
- public FileTime createFileReturnTime( String path) throws IOException {
- File file = new File(path);
- if(!file.exists()) {
- file.createNewFile();
- }
- Path p = Paths.get(file.getAbsolutePath());
- BasicFileAttributes view
- = Files.getFileAttributeView(p, BasicFileAttributeView.class)
- .readAttributes();
- FileTime fileTime=view.creationTime();
- // also available view.lastAccessTine and view.lastModifiedTime
- return fileTime;
- }
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/util/DbTestProcessBuilder.java b/aai-resources/src/test/java/org/onap/aai/util/DbTestProcessBuilder.java
deleted file mode 100644
index 503ec0f..0000000
--- a/aai-resources/src/test/java/org/onap/aai/util/DbTestProcessBuilder.java
+++ /dev/null
@@ -1,213 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.util;
-
-import java.io.*;
-import java.nio.file.attribute.FileTime;
-import java.text.SimpleDateFormat;
-import java.util.Arrays;
-import java.util.List;
-import java.util.concurrent.Executors;
-import java.util.concurrent.ScheduledExecutorService;
-import java.util.concurrent.ScheduledFuture;
-import java.util.concurrent.TimeUnit;
-
-public class DbTestProcessBuilder {
- ///public static Logger clog = Logger.getLogger("auditConsole");
- //public static Logger alog = Logger.getLogger("auditLog");
-
- /**
- * Start audit process non blocking.
- *
- * @param wait the wait
- * @param cmds the cmds
- * @param dir the dir
- */
- public void startAuditProcessNonBlocking(final long wait, final String cmds[], final String dir) {
-
- final ProcessBuilder pb = new ProcessBuilder(cmds).redirectErrorStream(true).directory(new File(dir));
-
- new Thread(new Runnable() {
- public void run() {
- try {
- //System.out.println( "sleeping seconds " + wait + " cmds " + Arrays.toString(cmds));
- Thread.sleep(wait*1000);
- //System.out.println( "returned from sleep");
- final Process p = pb.start();
- //System.out.println( "returned from pb.start");
- final InputStream is = p.getInputStream();
- final BufferedReader stdError = new BufferedReader(new InputStreamReader(p.getErrorStream()));
- final InputStreamReader isr = new InputStreamReader(is);
- final BufferedReader br = new BufferedReader(isr);
-//clog.debug("Output of running " + Arrays.toString(cmds) + " is:");
- System.out.println("Output of running is:" );
- String line;
- while ((line = br.readLine()) != null ) {
- System.out.println(line);
- }
- System.out.println("stderr of running is:" );
-
- while ((line = stdError.readLine()) != null ) {
- System.out.println(line);
- }
-
- } catch (IOException ie) {
-
- } catch (InterruptedException itre) {
- Thread.currentThread().interrupt();
- }
- }
- }).start();
-
- }
-
-
- private final ScheduledExecutorService auditProcessScheduler =
- Executors.newScheduledThreadPool(10);
-
- /**
- * Run W command every X seconds for Y minutes.
- *
- * @param w the w
- * @param x the x
- * @param y the y
- * @param runningDir the running dir
- */
- public void runWCommandEveryXSecondsForYMinutes(String[] w, int x, int y, final String runningDir) {
- final String[] c1 = w;
- final Runnable audit = new Runnable() {
- public void run() {
-//clog.debug("checkpoint "+(new Date()).toString());
- DbTestProcessBuilder a1 = new DbTestProcessBuilder();
- a1.startAuditProcessNonBlocking(1, c1, "/tmp");
- }
- };
-
- final ScheduledFuture<?> auditHandle =
- auditProcessScheduler.scheduleAtFixedRate(audit, 0, x, TimeUnit.SECONDS);
- auditProcessScheduler.schedule(new Runnable() {
- public void run() {
- auditHandle.cancel(true);
- }
- }, y * 60, TimeUnit.SECONDS);
- }
-
-
- /**
- * The main method.
- *
- * @param args the arguments
- */
- @SuppressWarnings({ "null", "static-access" })
- public static void main(String args[]) {
- String props = "NA";
- if (args.length > 0) {
- System.out.println( "DbTestProcessBuilder called with " + args.length + " arguments, " + args[0]);
- props = args[0].trim();
- } else {
- System.out.print("usage: DbTestProcessBuilder <auditConfig.prop path\n");
- return;
- }
- DbTestConfig.init(props);
- String ail = DbTestConfig.get("audit.list");
- String path = DbTestConfig.get("audit.path");
- final String runningDir = DbTestConfig.get("audit.runningdir");
- try {
- DbTestGetFileTime getFileTime = new DbTestGetFileTime();
- FileTime fileTime = getFileTime.createFileReturnTime( path );
- System.out.println(path + " creation time :"
- + new SimpleDateFormat("dd/MM/yyyy HH:mm:ss")
- .format(fileTime.toMillis()) + " runningDir " + runningDir);
- } catch ( IOException io ) {
- System.out.println( "IOException getting creation time " + path + " message " + io.getMessage());
- io.printStackTrace();
- }
-
- List<String> items = Arrays.asList(ail.split("\\s*,\\s*"));
- for (String ai: items) {
- if (!DbTestConfig.get("audit.task."+ai+".status").startsWith("a")) {
- continue;
- }
-//clog.debug("***audit item = " + ai + " Starting***");
-
- String w1 = DbTestConfig.get("audit.task."+ai+".cmd");
- String[] w2 = w1.split("\\s*,\\s*");
- System.out.print( "task items are : " + Arrays.toString(w2));
- // append the audit item name as the prefix of the audit directory name
- /*final int N = w2.length;
- w2 = Arrays.copyOf(w2, N+1);
- w2[N-2] = "\"-Dp=" + DbTestConfig.get("audit.task.odl.output.dir")+ai + "\"";
-//clog.debug("***java -D:"+w2[N-2]);
- //w2[N] = "\""+DbTestConfig.get("audit.task.odl.output.dir")+ai+"\"";
- w2[N] = "\""+DbTestConfig.get("audit.task.odl.output.dir")+ai+"\"";
- */
- DbTestProcessBuilder apb = new DbTestProcessBuilder();
-
- String ts1 = DbTestConfig.get("audit.task."+ai+".schedule");
- String[] ts2 = ts1.split("\\s*,\\s*");
- // note ts2[0] is the wait-before time, and it is not being used right now. We start with ts2[1]
- apb.runWCommandEveryXSecondsForYMinutes(w2,Integer.parseInt(ts2[1]),Integer.parseInt(ts2[2]), runningDir);
-//clog.debug("***audit item = " + ai + " started***");
- System.out.println( "started test " + ai);
-
- /*
- int ct = 0;
-
- while (true) try {
- if (DbTestConfig.get("jcl").startsWith("q")) {
- System.out.println("***Audit Main Program exiting...");
- System.exit(0);
- }
-
- Thread.currentThread().sleep(1000);
- if (ct < 10) {
- ct++;
- } else {
- //clog.debug(AuditConfig.get("jcl").charAt(0));
- ct=0;
- }
-
- } catch (InterruptedException ie) {
-
- } */
- }
- int ct = 0;
-
- while (true) try {
- if (DbTestConfig.get("jcl").startsWith("q")) {
- System.out.println("***Audit Main Program exiting...");
- System.exit(0);
- }
-
- Thread.currentThread().sleep(1000);
- if (ct < 10) {
- ct++;
- } else {
- //clog.debug(AuditConfig.get("jcl").charAt(0));
- ct=0;
- }
-
- } catch (InterruptedException ie) {
-
- }
-
- }
-
-}
diff --git a/aai-resources/src/test/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java b/aai-resources/src/test/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java
deleted file mode 100644
index 7c4abc9..0000000
--- a/aai-resources/src/test/java/org/onap/aai/util/JettyObfuscationConversionCommandLineUtilTest.java
+++ /dev/null
@@ -1,71 +0,0 @@
-/**
- * ============LICENSE_START=======================================================
- * org.onap.aai
- * ================================================================================
- * Copyright © 2017-2018 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.onap.aai.util;
-
-import org.junit.Ignore;
-import org.junit.Test;
-
-import java.io.ByteArrayOutputStream;
-import java.io.PrintStream;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
-import static org.junit.Assert.assertTrue;
-
-@Ignore
-public class JettyObfuscationConversionCommandLineUtilTest {
- private final ByteArrayOutputStream testOut = new ByteArrayOutputStream();
-
- /**
- * Test.
- */
- @Test
- public void test() {
- //setup, this will catch main's print statements for evaluation
-// System.setOut(new PrintStream(testOut));
-
- /* ------ TEST OBFUSCATION ----*/
- JettyObfuscationConversionCommandLineUtil.main(new String[]{"-e", "hello world"});
- /*
- * testOut was also catching any logging statements which interfered with result checking.
- * This regex business was the workaround - it tries to find the expected value in
- * the results and asserts against that.
- */
- String obfResult = testOut.toString();
- String obfExpected = "OBF:1thf1ugo1x151wfw1ylz11tr1ymf1wg21x1h1uh21th7";
- Pattern obfExpectPat = Pattern.compile(obfExpected);
- Matcher obfMatch = obfExpectPat.matcher(obfResult);
- assertTrue(obfMatch.find());
-
- testOut.reset(); //clear out previous result
-
- /* ------ TEST DEOBFUSCATION ----- */
- JettyObfuscationConversionCommandLineUtil.main(new String[]{"-d", obfExpected});
- String deobfResult = testOut.toString();
- String deobfExpected = "hello world";
- Pattern deobfExpectPat = Pattern.compile(deobfExpected);
- Matcher deobfMatch = deobfExpectPat.matcher(deobfResult);
- assertTrue(deobfMatch.find());
-
- //clean up, resets to stdout
-// System.setOut(null);
- }
-
-}