summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorFiete Ostkamp <Fiete.Ostkamp@telekom.de>2022-10-05 09:55:45 +0200
committerFiete Ostkamp <Fiete.Ostkamp@telekom.de>2022-10-05 09:55:45 +0200
commite632cf8afa27bdedf8b2044c430cd604ab7d4987 (patch)
tree85cf35932109fd858e09f4bf1a0a5d0724057697
parent20ea11d8067c57fe47d9bdc64663b8cc8a5742ca (diff)
Run the formatter for the traversal service
When building the traversal service with mvn install, the spotless and formatter plugins are invoked to verify the formatting. This results in 40000 lines of format violations that are printed out to the console. By invoking mvn formatter:format spotless:apply process-sources this number can be reduced to 2000 lines of format violations. Issue-ID: AAI-3543 Signed-off-by: Fiete Ostkamp <Fiete.Ostkamp@telekom.de> Change-Id: Id0011b3e0a626369c79fd0656cd44455347b7fde
-rw-r--r--aai-traversal/.classpath30
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/Profiles.java17
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/TraversalApp.java299
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/aailog/logs/AaiDBTraversalMetricLog.java22
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/config/DslConfiguration.java19
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/config/ErrorHandler.java29
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/config/JettyPasswordDecoder.java2
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/config/PasswordDecoder.java2
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/config/PropertyPasswordConfiguration.java28
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/config/SearchConfiguration.java43
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/dbgraphgen/ModelBasedProcessing.java7487
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/dbgraphgen/ResultSet.java263
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/dbgraphmap/SearchGraph.java327
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/AAIContainerFilter.java32
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/AAIHeaderProperties.java19
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/package-info.java6
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/post/AAIResponseFilterPriority.java13
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/post/InvalidResponseStatus.java51
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/post/ResponseHeaderManipulation.java51
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/post/ResponseTransactionLogging.java261
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/pre/AAIRequestFilterPriority.java29
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/pre/HeaderValidation.java179
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/pre/HttpHeaderInterceptor.java29
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/pre/OneWaySslAuthorization.java40
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RequestHeaderManipulation.java40
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RequestModification.java71
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RequestTransactionLogging.java223
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RetiredInterceptor.java73
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/pre/VersionInterceptor.java58
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/interceptors/pre/VersionLatestInterceptor.java23
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/CQ2Gremlin.java153
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/CQ2GremlinTest.java325
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/DslConsumer.java429
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/ExceptionHandler.java140
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/QueryConsumer.java624
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/RecentAPIConsumer.java404
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/TraversalConsumer.java158
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/dsl/AAIDslErrorListener.java7
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/dsl/DslContext.java270
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/dsl/DslQueryBuilder.java110
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/dsl/DslQueryProcessor.java273
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/dsl/Edge.java14
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/dsl/EdgeLabel.java6
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/dsl/v1/DslListener.java532
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/dsl/v2/DslListener.java595
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslQueryValidator.java15
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslSchemaValidator.java2
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslValidator.java3
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslValidatorRule.java7
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/enums/EdgeDirection.java11
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/enums/QueryVersion.java7
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/CQConfig.java4
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryConfig.java61
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryConfigDTO.java44
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryDTO.java60
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryTestDTO.java146
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/ExpectedResultsDto.java24
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/GenericQueryProcessor.java837
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/GetCustomQueryConfig.java205
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/GremlinServerSingleton.java44
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/GroovyShellImpl.java39
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/LocalCQConfig.java29
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/ModelAndNamedQueryRestProvider.java428
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/NodeQueryProcessor.java165
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/QueryProcessorType.java5
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/SchemaServiceCQConfig.java29
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/search/SearchProvider.java168
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/security/WebSecurityConfig.java22
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/util/AAIExtensionMap.java17
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/util/ConvertQueryPropertiesToJson.java164
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/util/EchoResponse.java150
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/util/LogFormatTools.java16
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/rest/util/ValidateEncoding.java258
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/service/AuthorizationService.java54
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/service/RetiredService.java29
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/transforms/Converter.java2
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/transforms/LowerCamelToLowerHyphenConverter.java4
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverter.java22
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/transforms/MapTraverser.java30
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/util/GenericQueryBuilder.java6
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/util/MakeNamedQuery.java444
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/util/NodesQueryBuilder.java6
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/util/TraversalConstants.java36
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/web/JerseyConfiguration.java73
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/web/LocalHostAccessLog.java43
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/web/MicrometerConfiguration.java21
-rw-r--r--aai-traversal/src/main/java/org/onap/aai/web/WebConfiguration.java32
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/AAIGremlinQueryTest.java107
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/AAISetup.java113
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/HttpTestUtil.java198
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/PayloadUtil.java39
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/QueryParameterTest.java44
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/SubgraphPruneTest.java36
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/TraversalTestConfiguration.java48
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/dbgraphgen/ModelBasedProcessingInvalidDataTest.java310
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/dbgraphgen/ModelBasedProcessingTest.java1734
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/dbgraphmap/SearchGraphEdgeRuleTest.java60
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/dbgraphmap/SearchGraphNamedQueryTest.java426
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/dbgraphmap/SearchGraphTest.java218
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestConfiguration.java22
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestProperties.java2
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/it/multitenancy/MultiTenancyIT.java96
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/it/multitenancy/RoleHandler.java24
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/AbstractSpringRestTest.java41
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/BadQueryFormatTest.java32
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/ConfigurationTest.java42
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/DslConsumerTest.java1870
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/ExceptionHandlerTest.java51
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/GfpVserverDataStoredQueryTest.java162
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/QueryConsumerTest.java328
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/RecentApiTest.java285
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/SearchProviderRestTest.java63
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslContextTest.java22
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslQueryBuilderTest.java29
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslQueryProcessorV1Test.java1230
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslQueryProcessorV2Test.java1289
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/dsl/EdgeLabelTest.java10
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/dsl/EdgeTest.java15
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/dsl/ProdDslTest.java66
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/history/AbstractSpringHistoryRestTest.java41
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/history/CQAllChildernFromPnfStateTest.java355
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryLifecycleEdgeTest.java805
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryLifecycleNodeDeletedThenRecreatedTest.java1375
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryLifecycleSingleNodeTest.java830
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryStateEdgeTest.java807
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryStateTest.java1303
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/retired/RetiredConsumerSpringTest.java25
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/AccessServiceFromServiceInstanceTest.java112
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/AvailabilityZoneAndComplexfromCloudRegionQueryTest.java95
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/ClosedLoopQueryTest.java155
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionAndSourceFromConfigurationQueryTest.java150
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromNfTypeQueryTest.java106
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromNfTypeVendorVersionTest.java147
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromNfTypeVendorVersion_withOptionalTest.java155
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromVnfTest.java123
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionSitesQueryTest.java94
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionfromCountryCloudRegionVersionQueryTest.java87
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionfromCountryQueryTest.java86
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionsByGenericVnfHGPairsTest.java360
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/ColocatedDevicesQueryTest.java180
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/ComplexFromVnfTest.java99
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/ContainmentPathQueryTest.java48
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/CountVnfByVnfTypeTest.java107
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/DestinationFromConfigurationQueryTest.java141
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/FabricInformationFromVnfTest.java153
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/FirstNetTopology_LineOfBusinessTest.java134
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/FirstNetTopology_ServiceInstanceTest.java157
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GFPVnfDataTest.java247
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GenericVnfsFromPserverTest.java149
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetClfiRoadmTailSummaryTest.java121
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetComplexAndPserversTest.java88
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetComplexByPnfNameQueryTest.java78
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetComplexFromHostnameQueryTest.java82
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetCustomQueryConfigTest.java82
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetCustomerVPNBondingServiceDetailsTest.java136
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetDHVLogicalLinkTest.java88
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetL3networkCloudRegionByNetworkRoleQueryTest.java46
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetLinterfaceFromNewvceTest.java123
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetNetworksByServiceInstanceTest.java186
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetNetworksTest.java129
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetPinterfacePhysicalLinkBySvcInstIdTest.java153
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetRouterRoadmTailSummaryTest.java120
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetServiceInstanceSummaryTest.java161
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetServiceInstanceVnfVfModuleModelsTest.java96
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetServiceTopologyTest.java231
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetTenantInfoAtSvcInstanceQueryTest.java144
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetTenantInfoAtSvcSubscriptionTest.java110
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetVNFVpnBondingServiceDetailsTest.java85
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetVnfVlanByCircuitIdTest.java126
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetVserverDetailTest.java205
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GetWlBundleIdQueryTest.java142
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GfpVserverDataQueryTest.java110
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GfpVserverQueryTest.java82
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/GroovyShellImplTest.java46
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/ImageFromCloudRegionNfTypeTest.java169
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/InstanceGroupsByCloudRegionQueryTest.java88
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/IpsNetworksFromVnfTest.java382
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedDevices_ComplicatedGVtoGV.java130
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedDevices_NewvceVserverTest.java152
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedDevices_SimpleGVtoGVQueryTest.java106
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedHashMapQueryTest.java22
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/LinterfacesCPFromVnfcTest.java136
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/LocationNetTypeNetRolefromCloudRegionQueryTest.java101
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/LogicalLinkByCloudRegionIdTest.java24
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/ModelAndNamedQueryRestProviderTest.java93
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/MsoRequestVfModuleTest.java147
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/NetworkCollectionByServiceInstanceTest.java57
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/NetworkNameFromNetworkRoleQueryTest.java100
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/NfTypefromCloudRegionQueryTest.java105
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/OnapQueryTest.java283
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/OwningEntityfromServiceInstance.java76
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/PathQueryTest.java22
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/PendingTopologyDetailTest.java246
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/PnfTopologyQueryTest.java153
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/PserverFromFqdnFirstTokenTest.java77
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/PserverFromHostnameFirstTokenTest.java76
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/PserverfromConfigurationFilterInterfaceIdTest.java141
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/PserverfromConfigurationTest.java140
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/PserversFromVnfQueryTest.java124
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/PserversWithNoComplexTest.java89
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/QueryCountTest.java33
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/QueryPnfFromModelByRegionTest.java163
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/QueryPnfFromModelTest.java81
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/QueryTest.java285
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/QueryVnfFromModelByRegionTest.java124
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/RelatedToBothCousinAndTreeCustomQueryTest.java34
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/RelatedToCustomQueryTest.java22
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/RelatedToTreeCustomQueryTest.java21
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/SearchProviderTest.java100
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceFromPserverAndSubsNameTest.java173
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceModelsByDistributionStatusTest.java109
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceSitesQueryTest.java114
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceTopologyTest.java192
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/SimpleFormatTest.java141
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/SiteL3NetworkCloudRegionQueryTest.java98
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/SitesByCloudRegionIdQueryTest.java86
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/SitesByCountryFilterCloudRegionIdQueryTest.java99
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/SitesByCountryFilterCloudRegionVerQueryTest.java103
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/SriovTopologyFromVnfQueryTest.java166
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyDetailFromVnfQueryTest.java302
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyDetailFromVserverQueryTest.java264
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyDetailsQueryTest.java313
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyFromCloudRegionIdAndServiceIdTest.java307
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyFromSubscriberNameAndServiceTypeTest.java458
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/TopologySummaryFromCloudRegionQueryTest.java78
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/TopologySummaryFromTenantTest.java119
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/TopologySummaryQueryTest.java165
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/TreeQueryTest.java22
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/UcpeInstanceQueryTest.java95
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/UcpeTopologyQueryTest.java188
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VfModuleFromServiceInstanceTest.java104
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VnfInstancesFromServiceInstancebyModelVersionTest.java116
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VnfSummaryFromVnfTest.java158
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VnfToEsrSystemInfoQueryTest.java131
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VnfToServiceInstanceQueryTest.java88
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VnfTopologyFromServiceInstanceTest.java171
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VnfTopologyFromVfModuleTest.java141
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VnfTopologyFromVnfTest.java215
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VnfVserverFromCustomerTest.java115
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VnfsFromPserverQueryTest.java125
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VnfsFromServiceInstanceTest.java96
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VnfsVlansFromServiceInstanceTest.java222
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VserverFromPserverTreeTest.java45
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VserverFromVnfQueryTest.java126
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VserverLinterfacesFromVnfcTest.java122
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/VserverLogicallinkFromPServerTest.java98
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/search/getSvcSubscriberModelInfoTest.java32
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/util/ConvertQueryPropertiesToJsonTest.java20
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/util/EchoResponseTest.java44
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java8
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java159
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/transforms/JoltTestUtil.java39
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverterTest.java41
-rw-r--r--aai-traversal/src/test/java/org/onap/aai/transforms/MapTraverserTest.java19
254 files changed, 25204 insertions, 23101 deletions
diff --git a/aai-traversal/.classpath b/aai-traversal/.classpath
index ff97a07..ed528ab 100644
--- a/aai-traversal/.classpath
+++ b/aai-traversal/.classpath
@@ -10,6 +10,7 @@
<attributes>
<attribute name="optional" value="true"/>
<attribute name="maven.pomderived" value="true"/>
+ <attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry kind="con" path="org.eclipse.jdt.launching.JRE_CONTAINER/org.eclipse.jdt.internal.debug.ui.launcher.StandardVMType/JavaSE-1.8">
@@ -30,8 +31,37 @@
<classpathentry excluding="**" kind="src" output="target/test-classes" path="src/test/resources">
<attributes>
<attribute name="maven.pomderived" value="true"/>
+ <attribute name="test" value="true"/>
</attributes>
</classpathentry>
<classpathentry exported="true" kind="con" path="GROOVY_DSL_SUPPORT"/>
+ <classpathentry kind="src" output="target/classes" path="target/generated-sources/antlr4">
+ <attributes>
+ <attribute name="optional" value="true"/>
+ <attribute name="maven.pomderived" value="true"/>
+ </attributes>
+ </classpathentry>
+ <classpathentry excluding="**" kind="src" output="target/classes" path="src/main/docker">
+ <attributes>
+ <attribute name="maven.pomderived" value="true"/>
+ </attributes>
+ </classpathentry>
+ <classpathentry kind="src" path="target/generated-sources/annotations">
+ <attributes>
+ <attribute name="optional" value="true"/>
+ <attribute name="maven.pomderived" value="true"/>
+ <attribute name="ignore_optional_problems" value="true"/>
+ <attribute name="m2e-apt" value="true"/>
+ </attributes>
+ </classpathentry>
+ <classpathentry kind="src" output="target/test-classes" path="target/generated-test-sources/test-annotations">
+ <attributes>
+ <attribute name="optional" value="true"/>
+ <attribute name="maven.pomderived" value="true"/>
+ <attribute name="ignore_optional_problems" value="true"/>
+ <attribute name="m2e-apt" value="true"/>
+ <attribute name="test" value="true"/>
+ </attributes>
+ </classpathentry>
<classpathentry kind="output" path="target/classes"/>
</classpath>
diff --git a/aai-traversal/src/main/java/org/onap/aai/Profiles.java b/aai-traversal/src/main/java/org/onap/aai/Profiles.java
index 25f51c3..0a886af 100644
--- a/aai-traversal/src/main/java/org/onap/aai/Profiles.java
+++ b/aai-traversal/src/main/java/org/onap/aai/Profiles.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -21,15 +21,16 @@ package org.onap.aai;
public final class Profiles {
- public static final String DMAAP = "dmaap";
- public static final String DME2 = "dme2";
+ public static final String DMAAP = "dmaap";
+ public static final String DME2 = "dme2";
- public static final String ONE_WAY_SSL = "one-way-ssl";
+ public static final String ONE_WAY_SSL = "one-way-ssl";
// AAF Basic Auth
- public static final String AAF_AUTHENTICATION = "aaf-auth";
+ public static final String AAF_AUTHENTICATION = "aaf-auth";
// AAF Auth with Client Certs
- public static final String AAF_CERT_AUTHENTICATION = "aaf-cert-auth";
- public static final String TWO_WAY_SSL = "two-way-ssl";
+ public static final String AAF_CERT_AUTHENTICATION = "aaf-cert-auth";
+ public static final String TWO_WAY_SSL = "two-way-ssl";
- private Profiles(){}
+ private Profiles() {
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/TraversalApp.java b/aai-traversal/src/main/java/org/onap/aai/TraversalApp.java
index 56573bc..5ac3ff1 100644
--- a/aai-traversal/src/main/java/org/onap/aai/TraversalApp.java
+++ b/aai-traversal/src/main/java/org/onap/aai/TraversalApp.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,11 @@
*/
package org.onap.aai;
+import java.util.Map;
+
+import javax.annotation.PostConstruct;
+import javax.annotation.PreDestroy;
+
import org.apache.commons.lang3.exception.ExceptionUtils;
import org.onap.aai.aailog.logs.AaiDebugLog;
import org.onap.aai.config.PropertyPasswordConfiguration;
@@ -41,164 +46,154 @@ import org.springframework.boot.autoconfigure.orm.jpa.HibernateJpaAutoConfigurat
import org.springframework.context.annotation.ComponentScan;
import org.springframework.core.env.Environment;
-import javax.annotation.PostConstruct;
-import javax.annotation.PreDestroy;
-
-import java.util.Map;
-
-@SpringBootApplication(exclude = {
- DataSourceAutoConfiguration.class,
- DataSourceTransactionManagerAutoConfiguration.class,
- HibernateJpaAutoConfiguration.class
-})
+@SpringBootApplication(
+ exclude = {DataSourceAutoConfiguration.class,
+ DataSourceTransactionManagerAutoConfiguration.class, HibernateJpaAutoConfiguration.class})
// Component Scan provides a way to look for spring beans
// It only searches beans in the following packages
// Any method annotated with @Bean annotation or any class
// with @Component, @Configuration, @Service will be picked up
-@ComponentScan(basePackages = {
- "org.onap.aai.config",
- "org.onap.aai.web",
- "org.onap.aai.setup",
- "org.onap.aai.tasks",
- "org.onap.aai.service",
- "org.onap.aai.rest",
- "org.onap.aai.aaf",
- "org.onap.aai.aailog"
-})
+@ComponentScan(
+ basePackages = {"org.onap.aai.config", "org.onap.aai.web", "org.onap.aai.setup",
+ "org.onap.aai.tasks", "org.onap.aai.service", "org.onap.aai.rest", "org.onap.aai.aaf",
+ "org.onap.aai.aailog"})
public class TraversalApp {
- private static final Logger logger = LoggerFactory.getLogger(TraversalApp.class.getName());
-
- private static AaiDebugLog debugLog = new AaiDebugLog();
- static {
- debugLog.setupMDC();
- }
-
- private static final String APP_NAME = "aai-traversal";
- private static Map<String,String> contextMap;
-
- @Autowired
- private Environment env;
-
- @Autowired
- private NodeIngestor nodeIngestor;
-
- @Autowired
- private SpringContextAware context;
-
- @Autowired
- private SpringContextAware loaderFactory;
-
-
- @PostConstruct
- private void init() throws AAIException {
- System.setProperty("org.onap.aai.serverStarted", "false");
- setDefaultProps();
-
- contextMap = MDC.getCopyOfContextMap();
-
- logger.debug("AAI Server initialization started...");
-
- // Setting this property to allow for encoded slash (/) in the path parameter
- // This is only needed for tomcat keeping this as temporary
- System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
-
- logger.debug("Starting AAIGraph connections and the NodeInjestor");
-
- if(env.acceptsProfiles(Profiles.TWO_WAY_SSL) && env.acceptsProfiles(Profiles.ONE_WAY_SSL)){
- logger.debug("You have seriously misconfigured your application");
- }
-
- AAIConfig.init();
-
- AAIGraph.getInstance();
- }
-
- @PreDestroy
- public void cleanup(){
- logger.debug("Traversal MicroService stopped");
- logger.info("Shutting down both realtime and cached connections");
- AAIGraph.getInstance().graphShutdown();
- }
-
- public static void main(String[] args) throws AAIException{
-
- setDefaultProps();
-
- Environment env =null;
- AAIConfig.init();
-
- try{
- SpringApplication app = new SpringApplication(TraversalApp.class);
- app.setLogStartupInfo(false);
- app.setRegisterShutdownHook(true);
- app.addInitializers(new PropertyPasswordConfiguration());
- env = app.run(args).getEnvironment();
- }
- catch(Exception ex){
- AAIException aai = schemaServiceExceptionTranslator(ex);
- ErrorLogHelper.logException(aai);
- ErrorLogHelper.logError(aai.getCode(), ex.getMessage() + ", resolve and restart Traversal");
- throw aai;
- }
-
-
- MDC.setContextMap (contextMap);
- logger.info(
- "Application '{}' is running on {}!" ,
- env.getProperty("spring.application.name"),
- env.getProperty("server.port")
- );
-
- logger.debug("Traversal MicroService Started");
- System.out.println("Traversal Microservice Started");
- }
-
- public static void setDefaultProps(){
-
- if (System.getProperty("file.separator") == null) {
- System.setProperty("file.separator", "/");
- }
-
- String currentDirectory = System.getProperty("user.dir");
- System.setProperty("aai.service.name", TraversalApp.class.getSimpleName());
-
- if (System.getProperty("AJSC_HOME") == null) {
- System.setProperty("AJSC_HOME", ".");
- }
-
- if(currentDirectory.contains(APP_NAME)){
- if (System.getProperty("BUNDLECONFIG_DIR") == null) {
- System.setProperty("BUNDLECONFIG_DIR", "src/main/resources");
- }
- } else {
- if (System.getProperty("BUNDLECONFIG_DIR") == null) {
- System.setProperty("BUNDLECONFIG_DIR", "aai-traversal/src/main/resources");
- }
- }
-
- }
- private static AAIException schemaServiceExceptionTranslator(Exception ex) {
- AAIException aai = null;
- logger.info("Error Message is {} details - {}", ExceptionUtils.getRootCause(ex).toString(), ExceptionUtils.getRootCause(ex).getMessage());
- if ( ExceptionUtils.getRootCause(ex) == null || ExceptionUtils.getRootCause(ex).getMessage() == null ) {
- aai = new AAIException("AAI_3025","Error parsing exception - Please Investigate" +
- LogFormatTools.getStackTop(ex));
+ private static final Logger logger = LoggerFactory.getLogger(TraversalApp.class.getName());
+
+ private static AaiDebugLog debugLog = new AaiDebugLog();
+ static {
+ debugLog.setupMDC();
+ }
+
+ private static final String APP_NAME = "aai-traversal";
+ private static Map<String, String> contextMap;
+
+ @Autowired
+ private Environment env;
+
+ @Autowired
+ private NodeIngestor nodeIngestor;
+
+ @Autowired
+ private SpringContextAware context;
+
+ @Autowired
+ private SpringContextAware loaderFactory;
+
+ @PostConstruct
+ private void init() throws AAIException {
+ System.setProperty("org.onap.aai.serverStarted", "false");
+ setDefaultProps();
+
+ contextMap = MDC.getCopyOfContextMap();
+
+ logger.debug("AAI Server initialization started...");
+
+ // Setting this property to allow for encoded slash (/) in the path parameter
+ // This is only needed for tomcat keeping this as temporary
+ System.setProperty("org.apache.tomcat.util.buf.UDecoder.ALLOW_ENCODED_SLASH", "true");
+
+ logger.debug("Starting AAIGraph connections and the NodeInjestor");
+
+ if (env.acceptsProfiles(Profiles.TWO_WAY_SSL)
+ && env.acceptsProfiles(Profiles.ONE_WAY_SSL)) {
+ logger.debug("You have seriously misconfigured your application");
+ }
+
+ AAIConfig.init();
+
+ AAIGraph.getInstance();
+ }
+
+ @PreDestroy
+ public void cleanup() {
+ logger.debug("Traversal MicroService stopped");
+ logger.info("Shutting down both realtime and cached connections");
+ AAIGraph.getInstance().graphShutdown();
+ }
+
+ public static void main(String[] args) throws AAIException {
+
+ setDefaultProps();
+
+ Environment env = null;
+ AAIConfig.init();
+
+ try {
+ SpringApplication app = new SpringApplication(TraversalApp.class);
+ app.setLogStartupInfo(false);
+ app.setRegisterShutdownHook(true);
+ app.addInitializers(new PropertyPasswordConfiguration());
+ env = app.run(args).getEnvironment();
+ } catch (Exception ex) {
+ AAIException aai = schemaServiceExceptionTranslator(ex);
+ ErrorLogHelper.logException(aai);
+ ErrorLogHelper.logError(aai.getCode(),
+ ex.getMessage() + ", resolve and restart Traversal");
+ throw aai;
+ }
+
+ MDC.setContextMap(contextMap);
+ logger.info("Application '{}' is running on {}!",
+ env.getProperty("spring.application.name"), env.getProperty("server.port"));
+
+ logger.debug("Traversal MicroService Started");
+ System.out.println("Traversal Microservice Started");
+ }
+
+ public static void setDefaultProps() {
+
+ if (System.getProperty("file.separator") == null) {
+ System.setProperty("file.separator", "/");
+ }
+
+ String currentDirectory = System.getProperty("user.dir");
+ System.setProperty("aai.service.name", TraversalApp.class.getSimpleName());
+
+ if (System.getProperty("AJSC_HOME") == null) {
+ System.setProperty("AJSC_HOME", ".");
+ }
+
+ if (currentDirectory.contains(APP_NAME)) {
+ if (System.getProperty("BUNDLECONFIG_DIR") == null) {
+ System.setProperty("BUNDLECONFIG_DIR", "src/main/resources");
+ }
+ } else {
+ if (System.getProperty("BUNDLECONFIG_DIR") == null) {
+ System.setProperty("BUNDLECONFIG_DIR", "aai-traversal/src/main/resources");
+ }
+ }
+
+ }
+
+ private static AAIException schemaServiceExceptionTranslator(Exception ex) {
+ AAIException aai = null;
+ logger.info("Error Message is {} details - {}", ExceptionUtils.getRootCause(ex).toString(),
+ ExceptionUtils.getRootCause(ex).getMessage());
+ if (ExceptionUtils.getRootCause(ex) == null
+ || ExceptionUtils.getRootCause(ex).getMessage() == null) {
+ aai = new AAIException("AAI_3025",
+ "Error parsing exception - Please Investigate" + LogFormatTools.getStackTop(ex));
} else {
- logger.info("Exception is " + ExceptionUtils.getRootCause(ex).getMessage() + "Root cause is"+ ExceptionUtils.getRootCause(ex).toString());
- if(ExceptionUtils.getRootCause(ex).getMessage().contains("NodeIngestor")){
- aai = new AAIException("AAI_3026","Error reading OXM from SchemaService - Investigate");
- }
- else if(ExceptionUtils.getRootCause(ex).getMessage().contains("EdgeIngestor")){
- aai = new AAIException("AAI_3027","Error reading EdgeRules from SchemaService - Investigate");
- }
- else if(ExceptionUtils.getRootCause(ex).getMessage().contains("Connection refused")){
- aai = new AAIException("AAI_3025","Error connecting to SchemaService - Investigate");
- }else {
- aai = new AAIException("AAI_3025","Error connecting to SchemaService - Please Investigate");
- }
+ logger.info("Exception is " + ExceptionUtils.getRootCause(ex).getMessage()
+ + "Root cause is" + ExceptionUtils.getRootCause(ex).toString());
+ if (ExceptionUtils.getRootCause(ex).getMessage().contains("NodeIngestor")) {
+ aai = new AAIException("AAI_3026",
+ "Error reading OXM from SchemaService - Investigate");
+ } else if (ExceptionUtils.getRootCause(ex).getMessage().contains("EdgeIngestor")) {
+ aai = new AAIException("AAI_3027",
+ "Error reading EdgeRules from SchemaService - Investigate");
+ } else if (ExceptionUtils.getRootCause(ex).getMessage()
+ .contains("Connection refused")) {
+ aai =
+ new AAIException("AAI_3025", "Error connecting to SchemaService - Investigate");
+ } else {
+ aai = new AAIException("AAI_3025",
+ "Error connecting to SchemaService - Please Investigate");
+ }
}
- return aai;
- }
+ return aai;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/aailog/logs/AaiDBTraversalMetricLog.java b/aai-traversal/src/main/java/org/onap/aai/aailog/logs/AaiDBTraversalMetricLog.java
index 8afc58b..7b28c7b 100644
--- a/aai-traversal/src/main/java/org/onap/aai/aailog/logs/AaiDBTraversalMetricLog.java
+++ b/aai-traversal/src/main/java/org/onap/aai/aailog/logs/AaiDBTraversalMetricLog.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -20,6 +20,12 @@
package org.onap.aai.aailog.logs;
+import java.net.URI;
+import java.time.ZoneOffset;
+import java.time.ZonedDateTime;
+import java.time.format.DateTimeFormatter;
+import java.util.Optional;
+
import org.onap.aai.util.AAIConstants;
import org.onap.logging.filter.base.Constants;
import org.onap.logging.filter.base.MDCSetup;
@@ -28,23 +34,17 @@ import org.onap.logging.ref.slf4j.ONAPLogConstants;
import org.slf4j.*;
import org.springframework.beans.factory.annotation.Value;
-import java.net.URI;
-import java.time.ZoneOffset;
-import java.time.ZonedDateTime;
-import java.time.format.DateTimeFormatter;
-import java.util.Optional;
-
public class AaiDBTraversalMetricLog extends MDCSetup {
protected static final Logger logger = LoggerFactory.getLogger(AaiDBTraversalMetricLog.class);
private final String partnerName;
private static final Marker INVOKE_RETURN = MarkerFactory.getMarker("INVOKE-RETURN");
private static final String TARGET_ENTITY = ONAPComponents.AAI.toString() + ".DB";
+
public AaiDBTraversalMetricLog(String subcomponent) {
partnerName = getPartnerName(subcomponent);
}
-
protected String getTargetServiceName(Optional<URI> uri) {
return (getServiceName(uri));
}
@@ -60,12 +60,11 @@ public class AaiDBTraversalMetricLog extends MDCSetup {
return serviceName;
}
-
protected String getTargetEntity(Optional<URI> uri) {
return TARGET_ENTITY;
}
- protected String getPartnerName(@Value(AAIConstants.AAI_TRAVERSAL_MS) String subcomponent ) {
+ protected String getPartnerName(@Value(AAIConstants.AAI_TRAVERSAL_MS) String subcomponent) {
StringBuilder sb = new StringBuilder(ONAPComponents.AAI.toString()).append(subcomponent);
return (sb.toString());
}
@@ -95,7 +94,8 @@ public class AaiDBTraversalMetricLog extends MDCSetup {
}
protected void setupMDC(Optional<URI> uri) {
- MDC.put("InvokeTimestamp", ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
+ MDC.put("InvokeTimestamp",
+ ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT));
MDC.put("TargetServiceName", this.getTargetServiceName(uri));
MDC.put("StatusCode", ONAPLogConstants.ResponseStatus.INPROGRESS.toString());
this.setInvocationIdFromMDC();
diff --git a/aai-traversal/src/main/java/org/onap/aai/config/DslConfiguration.java b/aai-traversal/src/main/java/org/onap/aai/config/DslConfiguration.java
index d10d4ac..81e96d1 100644
--- a/aai-traversal/src/main/java/org/onap/aai/config/DslConfiguration.java
+++ b/aai-traversal/src/main/java/org/onap/aai/config/DslConfiguration.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,9 @@
*/
package org.onap.aai.config;
+import java.util.HashMap;
+import java.util.Map;
+
import org.antlr.v4.runtime.tree.ParseTreeListener;
import org.onap.aai.edges.EdgeIngestor;
import org.onap.aai.introspection.LoaderFactory;
@@ -30,24 +33,24 @@ import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Scope;
-import java.util.HashMap;
-import java.util.Map;
-
@Configuration
public class DslConfiguration {
@Bean
@Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
- public Map<QueryVersion, ParseTreeListener> dslListeners(EdgeIngestor edgeIngestor, SchemaVersions schemaVersions, LoaderFactory loaderFactory){
+ public Map<QueryVersion, ParseTreeListener> dslListeners(EdgeIngestor edgeIngestor,
+ SchemaVersions schemaVersions, LoaderFactory loaderFactory) {
Map<QueryVersion, ParseTreeListener> dslListeners = new HashMap<>();
- dslListeners.put(QueryVersion.V1,new org.onap.aai.rest.dsl.v1.DslListener(edgeIngestor, schemaVersions, loaderFactory));
- dslListeners.put(QueryVersion.V2,new org.onap.aai.rest.dsl.v2.DslListener(edgeIngestor, schemaVersions, loaderFactory));
+ dslListeners.put(QueryVersion.V1,
+ new org.onap.aai.rest.dsl.v1.DslListener(edgeIngestor, schemaVersions, loaderFactory));
+ dslListeners.put(QueryVersion.V2,
+ new org.onap.aai.rest.dsl.v2.DslListener(edgeIngestor, schemaVersions, loaderFactory));
return dslListeners;
}
@Bean
@Scope(scopeName = ConfigurableBeanFactory.SCOPE_PROTOTYPE)
- public DslQueryProcessor dslQueryProcessor(Map<QueryVersion, ParseTreeListener> dslListeners){
+ public DslQueryProcessor dslQueryProcessor(Map<QueryVersion, ParseTreeListener> dslListeners) {
return new DslQueryProcessor(dslListeners);
}
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/config/ErrorHandler.java b/aai-traversal/src/main/java/org/onap/aai/config/ErrorHandler.java
index 22e12a6..40a0eee 100644
--- a/aai-traversal/src/main/java/org/onap/aai/config/ErrorHandler.java
+++ b/aai-traversal/src/main/java/org/onap/aai/config/ErrorHandler.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,21 +19,22 @@
*/
package org.onap.aai.config;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.logging.ErrorLogHelper;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.core.annotation.Order;
-import org.springframework.stereotype.Component;
-import org.springframework.web.filter.OncePerRequestFilter;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.ws.rs.core.MediaType;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
+
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.logging.ErrorLogHelper;
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.core.annotation.Order;
+import org.springframework.stereotype.Component;
+import org.springframework.web.filter.OncePerRequestFilter;
/**
* Responsible for dealing with uri that doesn't start with basePath
@@ -46,15 +47,17 @@ public class ErrorHandler extends OncePerRequestFilter {
private String basePath;
- public ErrorHandler(@Value("${schema.uri.base.path}") String basePath){
+ public ErrorHandler(@Value("${schema.uri.base.path}") String basePath) {
this.basePath = basePath;
- if(!basePath.endsWith("/")){
+ if (!basePath.endsWith("/")) {
this.basePath = basePath + "/";
}
}
@Override
- protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
+ protected void doFilterInternal(HttpServletRequest httpServletRequest,
+ HttpServletResponse httpServletResponse, FilterChain filterChain)
+ throws ServletException, IOException {
String uri = httpServletRequest.getRequestURI();
diff --git a/aai-traversal/src/main/java/org/onap/aai/config/JettyPasswordDecoder.java b/aai-traversal/src/main/java/org/onap/aai/config/JettyPasswordDecoder.java
index 944f951..bffb7fb 100644
--- a/aai-traversal/src/main/java/org/onap/aai/config/JettyPasswordDecoder.java
+++ b/aai-traversal/src/main/java/org/onap/aai/config/JettyPasswordDecoder.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
diff --git a/aai-traversal/src/main/java/org/onap/aai/config/PasswordDecoder.java b/aai-traversal/src/main/java/org/onap/aai/config/PasswordDecoder.java
index 0dcb845..a257b34 100644
--- a/aai-traversal/src/main/java/org/onap/aai/config/PasswordDecoder.java
+++ b/aai-traversal/src/main/java/org/onap/aai/config/PasswordDecoder.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
diff --git a/aai-traversal/src/main/java/org/onap/aai/config/PropertyPasswordConfiguration.java b/aai-traversal/src/main/java/org/onap/aai/config/PropertyPasswordConfiguration.java
index 0a76d6d..5d5a075 100644
--- a/aai-traversal/src/main/java/org/onap/aai/config/PropertyPasswordConfiguration.java
+++ b/aai-traversal/src/main/java/org/onap/aai/config/PropertyPasswordConfiguration.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,8 @@
*/
package org.onap.aai.config;
+import com.att.eelf.configuration.EELFManager;
+
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
@@ -29,19 +31,20 @@ import java.util.Properties;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
+import org.apache.commons.io.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.att.eelf.configuration.EELFManager;
-import org.apache.commons.io.IOUtils;
import org.springframework.context.ApplicationContextInitializer;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.*;
-public class PropertyPasswordConfiguration implements ApplicationContextInitializer<ConfigurableApplicationContext> {
+public class PropertyPasswordConfiguration
+ implements ApplicationContextInitializer<ConfigurableApplicationContext> {
private static final Pattern decodePasswordPattern = Pattern.compile("password\\((.*?)\\)");
private PasswordDecoder passwordDecoder = new JettyPasswordDecoder();
- private static final Logger logger = LoggerFactory.getLogger(PropertyPasswordConfiguration.class.getName());
+ private static final Logger logger =
+ LoggerFactory.getLogger(PropertyPasswordConfiguration.class.getName());
@Override
public void initialize(ConfigurableApplicationContext applicationContext) {
@@ -113,21 +116,25 @@ public class PropertyPasswordConfiguration implements ApplicationContextInitiali
Map<String, Object> propertyOverrides = new LinkedHashMap<>();
decodePasswords(propertySource, propertyOverrides);
if (!propertyOverrides.isEmpty()) {
- PropertySource<?> decodedProperties = new MapPropertySource("decoded "+ propertySource.getName(), propertyOverrides);
- environment.getPropertySources().addBefore(propertySource.getName(), decodedProperties);
+ PropertySource<?> decodedProperties =
+ new MapPropertySource("decoded " + propertySource.getName(), propertyOverrides);
+ environment.getPropertySources().addBefore(propertySource.getName(),
+ decodedProperties);
}
}
if (!sslProps.isEmpty()) {
logger.debug("Using AAF Certman files");
- PropertySource<?> additionalProperties = new MapPropertySource("additionalProperties", sslProps);
+ PropertySource<?> additionalProperties =
+ new MapPropertySource("additionalProperties", sslProps);
environment.getPropertySources().addFirst(additionalProperties);
}
}
private void decodePasswords(PropertySource<?> source, Map<String, Object> propertyOverrides) {
if (source instanceof EnumerablePropertySource) {
- EnumerablePropertySource<?> enumerablePropertySource = (EnumerablePropertySource<?>) source;
+ EnumerablePropertySource<?> enumerablePropertySource =
+ (EnumerablePropertySource<?>) source;
for (String key : enumerablePropertySource.getPropertyNames()) {
Object rawValue = source.getProperty(key);
if (rawValue instanceof String) {
@@ -139,7 +146,8 @@ public class PropertyPasswordConfiguration implements ApplicationContextInitiali
}
private String decodePasswordsInString(String input) {
- if (input == null) return null;
+ if (input == null)
+ return null;
StringBuffer output = new StringBuffer();
Matcher matcher = decodePasswordPattern.matcher(input);
while (matcher.find()) {
diff --git a/aai-traversal/src/main/java/org/onap/aai/config/SearchConfiguration.java b/aai-traversal/src/main/java/org/onap/aai/config/SearchConfiguration.java
index 5f131bf..248e799 100644
--- a/aai-traversal/src/main/java/org/onap/aai/config/SearchConfiguration.java
+++ b/aai-traversal/src/main/java/org/onap/aai/config/SearchConfiguration.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -20,7 +20,6 @@
package org.onap.aai.config;
import org.onap.aai.dbgraphmap.SearchGraph;
-
import org.onap.aai.edges.EdgeIngestor;
import org.onap.aai.introspection.LoaderFactory;
import org.onap.aai.rest.search.CQConfig;
@@ -39,30 +38,28 @@ import org.springframework.context.annotation.PropertySource;
public class SearchConfiguration {
- private static final String SCHEMA_SERVICE_TRANSLATOR = "schema-service";
-
- @Value("${schema.translator.list}")
- private String translator;
-
- @Bean
- public SearchGraph searchGraph(LoaderFactory loaderFactory, EdgeIngestor edgeIngestor, SchemaVersions schemaVersions) {
- return new SearchGraph(loaderFactory, edgeIngestor, schemaVersions);
- }
-
- @Bean
- public GremlinServerSingleton gremlinServerSingleton(){
- return new GremlinServerSingleton(getCustomQueryConfig());
- }
+ private static final String SCHEMA_SERVICE_TRANSLATOR = "schema-service";
+ @Value("${schema.translator.list}")
+ private String translator;
- @Bean
- public CQConfig getCustomQueryConfig(){
- if(translator.equals(SCHEMA_SERVICE_TRANSLATOR)) {
- return new SchemaServiceCQConfig();
- }
- return new LocalCQConfig();
- }
+ @Bean
+ public SearchGraph searchGraph(LoaderFactory loaderFactory, EdgeIngestor edgeIngestor,
+ SchemaVersions schemaVersions) {
+ return new SearchGraph(loaderFactory, edgeIngestor, schemaVersions);
+ }
+ @Bean
+ public GremlinServerSingleton gremlinServerSingleton() {
+ return new GremlinServerSingleton(getCustomQueryConfig());
+ }
+ @Bean
+ public CQConfig getCustomQueryConfig() {
+ if (translator.equals(SCHEMA_SERVICE_TRANSLATOR)) {
+ return new SchemaServiceCQConfig();
+ }
+ return new LocalCQConfig();
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/dbgraphgen/ModelBasedProcessing.java b/aai-traversal/src/main/java/org/onap/aai/dbgraphgen/ModelBasedProcessing.java
index de25586..aa4fdad 100644
--- a/aai-traversal/src/main/java/org/onap/aai/dbgraphgen/ModelBasedProcessing.java
+++ b/aai-traversal/src/main/java/org/onap/aai/dbgraphgen/ModelBasedProcessing.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,17 +19,20 @@
*/
package org.onap.aai.dbgraphgen;
-import org.onap.aai.logging.ErrorLogHelper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
import com.google.common.util.concurrent.SimpleTimeLimiter;
import com.google.common.util.concurrent.TimeLimiter;
import com.google.common.util.concurrent.UncheckedTimeoutException;
+
+import java.util.*;
+import java.util.concurrent.TimeUnit;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.apache.tinkerpop.gremlin.structure.VertexProperty;
+import org.onap.aai.concurrent.AaiCallable;
+import org.onap.aai.config.SpringContextAware;
import org.onap.aai.db.DbMethHelper;
import org.onap.aai.db.props.AAIProperties;
import org.onap.aai.dbgen.PropertyLimitDesc;
@@ -40,3688 +43,3820 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.Introspector;
import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
+import org.onap.aai.logging.ErrorLogHelper;
import org.onap.aai.query.builder.QueryBuilder;
import org.onap.aai.schema.enums.PropertyMetadata;
import org.onap.aai.serialization.db.DBSerializer;
-
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.util.AAIConfig;
-import org.onap.aai.concurrent.AaiCallable;
-import org.onap.aai.config.SpringContextAware;
-
-import java.util.*;
-import java.util.concurrent.TimeUnit;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
/**
- * Utility class that uses Model/Named-Query definitions to navigate the graph.
+ * Utility class that uses Model/Named-Query definitions to navigate the graph.
*/
public class ModelBasedProcessing {
- private static Logger logger = LoggerFactory.getLogger(ModelBasedProcessing.class);
- private static final int MAX_LEVELS = 50; // max depth allowed for our model - to protect against infinite loop problems
-
- private TransactionalGraphEngine engine;
- private Loader loader;
- private DBSerializer serializer;
- private DbMethHelper dbMethHelper;
-
- protected ModelBasedProcessing() {
-
- }
- public ModelBasedProcessing(Loader loader, TransactionalGraphEngine engine, DBSerializer serializer) {
- this.loader = loader;
- this.engine = engine;
- this.serializer = serializer;
- dbMethHelper = new DbMethHelper(loader, engine);
- }
- /**
- * Gets the start nodes and model-ver's.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param passedModelVersionId the passed model-version-id -- optional (unique id for a model-ver)
- * @param passedModelInvId the passed model-invariant-id -- optional
- * @param passedModelName the passed model-name -- optional
- * @param passedTopNodeType the passed top node type -- optional (needed if neither model=invariant-id nor model-version-id is passed)
- * @param startNodeFilterArrayOfHashes the start node filter array of hashes -- optional (used to locate the first node(s) of instance data)
- * @param apiVer the api ver
- * @return HashMap of startNodes and their corresponding model-version-id's
- * @throws AAIException the AAI exception
- */
- public Map<String,String> getStartNodesAndModVersionIds( String transId, String fromAppId,
- String passedModelVersionId,
- String passedModelInvId,
- String passedModelName,
- String passedTopNodeType,
- List<Map<String,Object>> startNodeFilterArrayOfHashes,
- String apiVer )
- throws AAIException {
- // ----------------------------------------------------------------------------------------------------
- // Get a hash for all start-nodes (key = vtxId, val = modelVersionId that applies)
- // If no start-node-key info is passed, then use either the passed modelVersion or
- // the passed model-invariant-id or model-name to collect them.
- // If start-node-key info is given, use it instead to look for start-nodes.
- // Note: if ONLY start-node-key info is given, then it would have to map to nodes which
- // have persona data. Otherwise we'd have no way to know what model to collect data with.
- // ----------------------------------------------------------------------------------------------------
-
- Iterator<Vertex> startVerts = null;
- Map<String, String> startVertInfo = new HashMap<>();
-
- if( startNodeFilterArrayOfHashes.isEmpty() ){
- // Since they did not give any data to find start instances, we will have to find them
- // using whatever model-info they provided so we can use it to map to persona-data in the db.
- if( (passedModelVersionId == null || passedModelVersionId.equals(""))
- && (passedModelInvId == null || passedModelInvId.equals(""))
- && (passedModelName == null || passedModelName.equals(""))){
- throw new AAIException("AAI_6118", "ModelInvariantId or ModelName or ModelVersionId required if no startNodeFilter data passed.");
- }
- else {
- // Use whatever model info they pass to find start-node instances
- // Get the first/top named-query-element used by this query
- if( passedModelVersionId != null && !passedModelVersionId.equals("") ){
- // Need to look up the model-invariant-id and model-version to check against persona data
- Vertex modVerVtx = getNodeUsingUniqueId(transId, fromAppId, "model-ver",
- "model-version-id", passedModelVersionId);
- Vertex modVtx = getModelGivenModelVer( modVerVtx, "" );
- String calcModId = modVtx.<String>property("model-invariant-id").orElse(null);
- // Now we can look up instances that match this model's info
- if( calcModId != null ){
- startVerts = this.engine.asAdmin().getReadOnlyTraversalSource().V().has(addDBAliasedSuffix("model-invariant-id"),calcModId).has(addDBAliasedSuffix("model-version-id"),passedModelVersionId);
- }
- }
- else if( passedModelInvId != null && !passedModelInvId.equals("") ){
- // They gave us the model-invariant-id
- startVerts = this.engine.asAdmin().getReadOnlyTraversalSource().V().has(addDBAliasedSuffix("model-invariant-id"),passedModelInvId);
- }
- else if( passedModelName != null && !passedModelName.equals("") ){
- List<Vertex> modelVerVtxList = getModelVersUsingName(transId, fromAppId, passedModelName);
- List<Vertex> startVtxList = new ArrayList<>();
- // Need to look up the model-inv-ids and model-versions to check against persona data
- if( !modelVerVtxList.isEmpty() ){
- for( int i = 0; i < modelVerVtxList.size(); i++ ){
- String calcModVerId = (modelVerVtxList.get(i)).<String>property("model-version-id").orElse(null);
- Vertex modVtx = getModelGivenModelVer(modelVerVtxList.get(i),"");
- String calcModInvId = modVtx.<String>property("model-invariant-id").orElse(null);
- // Now we can look up instances that match this model's info
- Iterator<Vertex> tmpStartIter = this.engine.asAdmin().getReadOnlyTraversalSource().V().has(addDBAliasedSuffix("model-invariant-id"),calcModInvId).has(addDBAliasedSuffix("model-version-id"),calcModVerId);
- while( tmpStartIter.hasNext() ){
- Vertex tmpStartVert = tmpStartIter.next();
- startVtxList.add(tmpStartVert);
- }
- }
- }
- if( !startVtxList.isEmpty() ){
- startVerts = startVtxList.iterator();
- }
- }
- }
-
- if( startVerts != null ){
- while( startVerts.hasNext() ){
- Vertex tmpStartVert = startVerts.next();
- String vid = tmpStartVert.id().toString();
- //String tmpModId = tmpStartVert.<String>property(addDBAliasedSuffix("model-invariant-id")).orElse(null);
- String tmpModVerId = tmpStartVert.<String>property(addDBAliasedSuffix("model-version-id")).orElse(null);
- startVertInfo.put(vid, tmpModVerId);
- }
- }
- if( startVertInfo.isEmpty() ){
- throw new AAIException("AAI_6114", "Start Node(s) could not be found for model data passed. " +
- "(modelVersionId = [" + passedModelVersionId +
- "], modelInvariantId = [" + passedModelInvId +
- "], modelName = [" + passedModelName +
- "])");
- }
-
- return startVertInfo;
- }
- else {
- // Use start-node filter info to find start-node(s) - Note - there could also be model info passed that we'll need
- // to use to trim down the set of start-nodes that we find based on the startNodeFilter data.
- String modTopNodeType ="";
- String modInfoStr = "";
- if( passedModelVersionId != null && !passedModelVersionId.equals("") ){
- modTopNodeType = getModelVerTopWidgetType( transId, fromAppId, passedModelVersionId, "", "" );
- modInfoStr = "modelVersionId = (" + passedModelVersionId + ")";
- }
- else if( passedModelInvId != null && !passedModelInvId.equals("") ){
- modTopNodeType = getModelVerTopWidgetType( transId, fromAppId,"", passedModelInvId, "" );
- modInfoStr = "modelId = (" + passedModelInvId + ")";
- }
- else if( passedModelName != null && !passedModelName.equals("") ){
- modTopNodeType = getModelVerTopWidgetType( transId, fromAppId,"", "", passedModelName );
- modInfoStr = "modelName = (" + passedModelName + ")";
- }
-
- if( modTopNodeType.equals("") ){
- if( (passedTopNodeType == null) || passedTopNodeType.equals("") ){
- String msg = "Could not determine the top-node nodeType for this request. modelInfo: [" + modInfoStr + "]";
- throw new AAIException("AAI_6118", msg);
- }
- else {
- // We couldn't find a top-model-type based on passed in model info, but they
- // gave us a type to use -- so use it.
- modTopNodeType = passedTopNodeType;
- }
- }
- else {
- // we did get a topNode type based on model info - make sure it doesn't contradict
- // the passsed-in one (if there is one)
- if( passedTopNodeType != null && !passedTopNodeType.equals("")
- && !passedTopNodeType.equals(modTopNodeType) ){
- throw new AAIException("AAI_6120", "topNodeType passed in [" + passedTopNodeType
- + "] does not match nodeType derived for model info passed in: ["
- + modTopNodeType + "]");
- }
- }
-
- List<String> modelVersionIds2Check = new ArrayList<>();
- if( (passedModelName != null && !passedModelName.equals("")) ){
- // They passed a modelName, so find all the model UUIDs (model-version-id's) that map to this
- modelVersionIds2Check = getModelVerIdsUsingName(transId, fromAppId, passedModelName);
- }
- if( (passedModelVersionId != null && !passedModelVersionId.equals("")) ){
- // They passed in a modelNameVersionId
- if( modelVersionIds2Check.isEmpty() ){
- // There was no modelName passed, so we can use the passed modelNameVersionId
- modelVersionIds2Check.add(passedModelVersionId);
- }
- else if( modelVersionIds2Check.contains(passedModelVersionId) ){
- // The passed in uuid does not conflict with what we got using the passed-in modelName.
- // We'll just use the passed in uuid in this case.
- // Hopefully they would not be passing strange combinations like this, but we'll try to deal with it.
- modelVersionIds2Check = new ArrayList<>(); // Clear out what we had
- modelVersionIds2Check.add(passedModelVersionId);
- }
- }
-
- // We should now be OK with our topNodeType for this request, so we can look for the actual startNodes
- for( int i=0; i < startNodeFilterArrayOfHashes.size(); i++ ){
- // Locate the starting node which will be used to look which corresponds to this set of filter data
- Vertex startVtx = null;
- try {
- Optional<Vertex> result = dbMethHelper.searchVertexByIdentityMap(modTopNodeType, startNodeFilterArrayOfHashes.get(i));
- if (!result.isPresent()) {
- throw new AAIException("AAI_6114", "No Node of type " + modTopNodeType + " found for properties");
- }
- startVtx = result.get();
- }
- catch( AAIException e ){
- String msg = "Could not find startNode of type = [" + modTopNodeType + "], given these params: "
- + startNodeFilterArrayOfHashes.get(i) + ". msg # from getUniqueNode() = " + e.getMessage();
- throw new AAIException("AAI_6114", msg);
- }
-
- String vid = startVtx.id().toString();
- String personaModInvId = startVtx.<String>property(addDBAliasedSuffix("model-invariant-id")).orElse(null);
- String personaModVerId = startVtx.<String>property(addDBAliasedSuffix("model-version-id")).orElse(null);
-
- // Either this start-node has persona info (which should not contradict any passed-in model info)
- // or they should have passed in the model to use - so we'd just use that.
- if( personaModVerId != null && !personaModVerId.equals("") ){
- // There is persona data in this start-node. So make sure it doesn't contradict any "passed" stuff
- if( modelVersionIds2Check.isEmpty()
- && (passedModelInvId == null || passedModelInvId.equals("")) ){
- // They didn't pass any model info, so use the persona one.
- startVertInfo.put(vid, personaModVerId);
- }
- else if( modelVersionIds2Check.isEmpty()
- && (passedModelInvId != null && !passedModelInvId.equals("")) ){
- // They passed in just the modelId - so check it
- if( passedModelInvId.equals(personaModInvId) ){
- startVertInfo.put(vid, personaModVerId);
- }
- }
- else if( !modelVersionIds2Check.isEmpty()
- && (passedModelInvId == null || passedModelInvId.equals("")) ){
- // They passed in just modelVersionId - so check
- if( modelVersionIds2Check.contains(personaModVerId) ){
- startVertInfo.put(vid, personaModVerId);
- }
- }
- else if( !modelVersionIds2Check.isEmpty()
- && (passedModelInvId != null && !passedModelInvId.equals("")) ){
- // We have BOTH a modelVersionIds and a modelId to check
- if( passedModelInvId.equals(personaModInvId)
- && modelVersionIds2Check.contains(personaModVerId) ){
- startVertInfo.put(vid, personaModVerId);
- }
- }
- }
- else {
- // This start node did not have persona info -- so we will use the passed in model info if they passed one
- if( passedModelVersionId!= null && !passedModelVersionId.equals("") ){
- // The model-version-id uniquely identifies a model-ver, so we can use it.
- startVertInfo.put(vid, passedModelVersionId);
- }
- else {
- throw new AAIException("AAI_6118", "Found startNode but since it does not have persona data, the " +
- " model-version-id is required. ");
- }
- }
- }
- }
-
- return startVertInfo;
-
- }//end of getStartNodesAndModVersionIds()
-
-
- /**
- * Query by model. (really model-ver)
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param modelVersionId the model-version-id (unique id in model-ver)
- * @param modelInvariantId the model-invariant-id (unique id in model)
- * @param modelName the model name
- * @param topNodeType - optional (needed if neither model-invariant-id nor model-version-id is passed)
- * @param startNodeFilterArrayOfHashes the start node filter array of hashes -- optional (used to locate the first node(s) of instance data)
- * @param apiVer the api ver
- * @return resultSet
- * @throws AAIException the AAI exception
- */
- public List<ResultSet> queryByModel(String transId, String fromAppId,
- String modelVersionId,
- String modelInvariantId,
- String modelName,
- String topNodeType,
- List<Map<String,Object>> startNodeFilterArrayOfHashes,
- String apiVer )
- throws AAIException {
-
- final String transId_f = transId;
- final String fromAppId_f = fromAppId;
- final String modelVersionId_f = modelVersionId;
- final String modelInvId_f = modelInvariantId;
- final String modelName_f = modelName;
- final String topNodeType_f = topNodeType;
- final List<Map<String,Object>> startNodeFilterArrayOfHashes_f = startNodeFilterArrayOfHashes;
- final String apiVer_f = apiVer;
-
- // Find out what our time-limit should be
- int timeLimitSec = 0;
- String timeLimitString = AAIConfig.get("aai.model.query.timeout.sec");
- if( timeLimitString != null && !timeLimitString.equals("") ){
- try {
- timeLimitSec = Integer.parseInt(timeLimitString);
- }
- catch ( Exception nfe ){
- // Don't worry, we will leave the limit as zero - which tells us not to use it.
- }
- }
-
- if( timeLimitSec <= 0 ){
- // We will NOT be using a timer
- return queryByModel_Timed( transId, fromAppId,
- modelVersionId,
- modelInvariantId,
- modelName,
- topNodeType,
- startNodeFilterArrayOfHashes,
- apiVer );
- }
-
- List<ResultSet> resultList = new ArrayList<>();
- TimeLimiter limiter = new SimpleTimeLimiter();
- try {
-
- resultList = limiter.callWithTimeout(new AaiCallable <List<ResultSet>>() {
- public List<ResultSet> process() throws AAIException {
- return queryByModel_Timed( transId_f, fromAppId_f,
- modelVersionId_f,
- modelInvId_f,
- modelName_f,
- topNodeType_f,
- startNodeFilterArrayOfHashes_f,
- apiVer_f );
- }
- }, timeLimitSec, TimeUnit.SECONDS, true);
- }
- catch (AAIException ae) {
- // Re-throw AAIException so we get can tell what happened internally
- throw ae;
- }
- catch (UncheckedTimeoutException ute) {
- throw new AAIException("AAI_6140", "Query Processing Limit exceeded. (limit = " + timeLimitSec + " seconds)");
- }
- catch (Exception e) {
- throw new AAIException("AAI_6128", "Unexpected exception in queryByModel(): " + e.getMessage() );
- }
-
- return resultList;
- }
-
-
- /**
- * Query by model (model-ver) timed.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param modelVersionId the model-version-id (unique id in model-ver)
- * @param modelInvariantId the model-invariant-id (unique id in model)
- * @param modelName the model name
- * @param topNodeType the top node type
- * @param startNodeFilterArrayOfHashesVal the start node filter array of hashes
- * @param apiVer the api ver
- * @return the array list
- * @throws AAIException the AAI exception
- */
- public List<ResultSet> queryByModel_Timed(String transId, String fromAppId,
- String modelVersionId,
- String modelInvariantId,
- String modelName,
- String topNodeType,
- List<Map<String,Object>> startNodeFilterArrayOfHashesVal,
- String apiVer )
- throws AAIException {
-
- List<ResultSet> resultArray = new ArrayList<>();
-
- // NOTE: this method can be used for different styles of queries:
- // a) They could pass neither a modelVersionId or a modelInvariantId but just pass a set of data defining start-nodes.
- // Note - with no model info, we need them to pass the startNodeType for us to be able to use the
- // start-node-filter data. We would look at each start node and ensure that each has persona-model info.
- // Then use whatever model corresponds to each instance to pull that instance's data.
- // b) They could pass a modelInvariantId, but no modelVersionId and no startNode info. In this case, we
- // Would look in the database for all nodes that have a model-invariant-id-local that matches what was
- // passed, and then for each of those instances, pull the data based on the corresponding model.
- // c) They could pass a model-version-id, but no startNode info. We'd make sure that if a
- // model-invariant-id was also passed, that it does not conflict - but it really should be null if they
- // are passing a full model-version-id. Like case -b-, we'd do a query for all nodes
- // that have persona info that corresponds to the model-version-id passed and then
- // collect data for each one.
- // d) They could pass either modelVersionId or modelInvariantId AND startNodeFilter info. In this case we
- // would look at the model info to figure out what the top-node-type is, then look at the
- // top-node instances based on the startNodeFilter. We'd only collect data for each instance if
- // it's persona model info matches what was passed in.
-
-
- // Sorry to do this, but code that gets called with an empty hash as the first array element was causing errors
- List<Map<String,Object>> startNodeFilterArrayOfHashes = new ArrayList <>();
- if( !startNodeFilterArrayOfHashesVal.isEmpty() ){
- Map<String,Object> tmpH = startNodeFilterArrayOfHashesVal.get(0);
- if( !tmpH.isEmpty() ){
- for( int i=0; i < startNodeFilterArrayOfHashesVal.size(); i++ ){
- startNodeFilterArrayOfHashes.add( startNodeFilterArrayOfHashesVal.get(i) );
- }
- }
- }
-
- // ----------------------------------------------------------------------------------------------------------
- // Get a Hash of all the start-nodes (top instance-data node for a model-ver where we will
- // start collecting data) for startNode2ModelVerHash:
- // key = vertex-id for the startNode,
- // value = model-version-id for the corresponding model-ver
- // ----------------------------------------------------------------------------------------------------------
- Map<String, String> startNode2ModelVerHash = getStartNodesAndModVersionIds( transId, fromAppId,
- modelVersionId, modelInvariantId, modelName, topNodeType,
- startNodeFilterArrayOfHashes, apiVer );
-
- //System.out.println("\nDEBUG -- Here's a dump of the startnodes/model-vers: " + startNode2ModelVerHash.toString());
-
- // --------------------------------------------------------------------------------------------------------
- // Figure out what-all models (model-ver nodes) we will be dealing with
- // Note - Instances must all use the same type of start-node, but do not have to all use the same model-ver.
- // --------------------------------------------------------------------------------------------------------
- Map<String, Vertex> distinctModelVersHash = new HashMap<>();
- // For distinctModelVersHash: key = modelVersionId, val= modelVerVertex
- String startNodeType = "";
- if( topNodeType != null && !topNodeType.equals("") ){
- startNodeType = topNodeType;
- }
-
- List<String> skipModelVerIdList = new ArrayList<>();
- List<String> skipStartVertVerIdList = new ArrayList<>();
- Set <String> snKeySet = startNode2ModelVerHash.keySet();
- Iterator<String> startNodeIterator = snKeySet.iterator();
- while( startNodeIterator.hasNext() ){
- String modVerIdKey = startNodeIterator.next();
- String modVerId = startNode2ModelVerHash.get(modVerIdKey);
- if( !distinctModelVersHash.containsKey(modVerId) ){
- // First time seeing this model-version-id
- Vertex modVerVtx = getNodeUsingUniqueId(transId, fromAppId, "model-ver",
- "model-version-id", modVerId);
- String tmpNodeType = "";
- try {
- tmpNodeType = getModelVerTopWidgetType( modVerVtx, "" );
- }
- catch( AAIException ae ){
- // There must be some old bad data in the db - we will skip over this model-ver since its
- // model is not good anymore - but will log that this is happening.
- skipModelVerIdList.add(modVerId);
- skipStartVertVerIdList.add(modVerIdKey);
- System.out.println(">>> WARNING - will not collect model data for this vertex since " +
- "it uses an inconsistant model-ver model. Model-version-id = " + modVerId );
- }
-
- if( tmpNodeType != null && !tmpNodeType.equals("") ){
- if( startNodeType.equals("") ){
- startNodeType = tmpNodeType;
- }
- else if( !startNodeType.equals(tmpNodeType) ){
- String msg = "Conflict between startNode types for models involved: [" + startNodeType
- + "], [" + tmpNodeType + "]";
- throw new AAIException("AAI_6125", msg);
- }
- distinctModelVersHash.put(modVerId, modVerVtx);
- }
- }
- }
-
- //System.out.println("\nDEBUG -- Here's a dump of the DISTINCT model-ver hash: " + distinctModelVersHash.toString() );
-
- // ------------------------------------------------------------------------------------------------------
- // Get the "valid-next-step" hash for each distinct model-ver
- // While we're at it, get a mapping of model-invariant-id|model-version to model-version-id for
- // the model-vers being used
- // ------------------------------------------------------------------------------------------------------
- Map<String, Multimap<String, String>> validNextStepHash = new HashMap<>();
- // validNextStepHash: key = modelVerId, value = nextStepMap
- Set <String> keySet = distinctModelVersHash.keySet();
- Iterator<String> modelVerIterator = keySet.iterator();
- while( modelVerIterator.hasNext() ){
- String modVerKey = modelVerIterator.next();
- if( ! skipModelVerIdList.contains(modVerKey) ){
- Vertex modelVerVtx = distinctModelVersHash.get(modVerKey);
- Multimap<String, String> tmpTopoMap = genTopoMap4ModelVer( transId, fromAppId,
- modelVerVtx, modVerKey);
- validNextStepHash.put(modVerKey, tmpTopoMap);
- }
- }
-
- // -------------------------------------------------------------------------------------------------
- // Figure out what the "start-node" for each instance will be (plus the info we will use to
- // represent that in our topology)
- // -------------------------------------------------------------------------------------------------
- List<String> failedPersonaCheckVids = new ArrayList<>();
- Map<String, String> firstStepInfoHash = new HashMap<>();
- // For firstStepInfoHash: key = startNodeVtxId, val=topNodeType plus personaData if applicable
- // ie. the value is what we'd use as the "first-step" for this model.
- if( !nodeTypeSupportsPersona( startNodeType) ){
- // This node type doesn't have persona info, so we just use startNodeType for the first-step-info
- snKeySet = startNode2ModelVerHash.keySet();
- startNodeIterator = snKeySet.iterator();
- while( startNodeIterator.hasNext() ){
- String vtxKey = startNodeIterator.next();
- firstStepInfoHash.put(vtxKey,startNodeType);
- }
- }
- else {
- // Need to check that this node's persona data is good and if it is - use it for the first step info
- snKeySet = startNode2ModelVerHash.keySet();
- startNodeIterator = snKeySet.iterator();
- while( startNodeIterator.hasNext() ){
- String vtxKey = startNodeIterator.next();
- Iterator<Vertex> vtxIterator = this.engine.asAdmin().getReadOnlyTraversalSource().V(vtxKey);
- Vertex tmpVtx = vtxIterator.next();
- String thisVtxModelVerId = startNode2ModelVerHash.get(vtxKey);
- if( skipModelVerIdList.contains(thisVtxModelVerId) ){
- // Skip this vertex because it uses a model-ver that is bad
- continue;
- }
- Vertex modelVerVtx = distinctModelVersHash.get(thisVtxModelVerId);
- Vertex modelVtx = getModelGivenModelVer( modelVerVtx, "" );
- String modInvId = modelVtx.<String>property("model-invariant-id").orElse(null);
- String personaModInvId = tmpVtx.<String>property(addDBAliasedSuffix("model-invariant-id")).orElse(null);
- String personaModVerId = tmpVtx.<String>property(addDBAliasedSuffix("model-version-id")).orElse(null);
- if( modInvId.equals(personaModInvId) && thisVtxModelVerId.equals(personaModVerId) ){
- String tmpPersonaInfoStr = startNodeType + "," + personaModInvId + "," + personaModVerId;
- firstStepInfoHash.put(vtxKey, tmpPersonaInfoStr );
- }
- else {
- // we won't use this start node below when we collect data because it should have
- // had persona data that matched it's model - but it did not.
- failedPersonaCheckVids.add(vtxKey);
- }
- }
- }
-
- //System.out.println("\nDEBUG -- Here's a dump of the firstStepInfoHash hash: " + firstStepInfoHash.toString() );
-
- // ------------------------------------------------------------------------------------------------
- // Loop through each start-node, collect it's data using collectInstanceData() and put the
- // resultSet onto the resultArray.
- // ------------------------------------------------------------------------------------------------
-
- // Make sure they're not bringing back too much data
- String maxString = AAIConfig.get("aai.model.query.resultset.maxcount");
- if( maxString != null && !maxString.equals("") ){
- int maxSets = 0;
- try {
- maxSets = Integer.parseInt(maxString);
- }
- catch ( Exception nfe ){
- // Don't worry, we will leave the max as zero - which tells us not to use it.
- }
-
- if( maxSets > 0 && (startNode2ModelVerHash.size() > maxSets) ){
- String msg = " Query returns " + startNode2ModelVerHash.size() + " resultSets. Max allowed is: " + maxSets;
- throw new AAIException("AAI_6141", msg);
- }
- }
-
- snKeySet = startNode2ModelVerHash.keySet();
- startNodeIterator = snKeySet.iterator();
- while( startNodeIterator.hasNext() ){
- String topNodeVtxId = startNodeIterator.next();
- if( failedPersonaCheckVids.contains(topNodeVtxId) || skipStartVertVerIdList.contains(topNodeVtxId) ){
- // Skip this vertex because it failed it's persona-data check above
- // Skip this vertex because it uses a model-ver that is bad
- continue;
- }
-
- Iterator<Vertex> vtxIterator = this.engine.asAdmin().getReadOnlyTraversalSource().V(topNodeVtxId);
- Vertex tmpStartVtx = vtxIterator.next();
- String elementLocationTrail = firstStepInfoHash.get(topNodeVtxId);
- String modelVerId = startNode2ModelVerHash.get(topNodeVtxId);
- Multimap<String, String> validNextStepMap = validNextStepHash.get(modelVerId);
-
- List<String> vidsTraversed = new ArrayList<>();
- Map<String,String> emptyDelKeyHash = new HashMap<>();
- Map<String,String> emptyNQElementHash = new HashMap<>(); // Only applies to Named Queries
- ResultSet tmpResSet = collectInstanceData( transId, fromAppId,
- tmpStartVtx, elementLocationTrail,
- validNextStepMap, vidsTraversed, 0, emptyDelKeyHash, emptyNQElementHash, apiVer );
-
- resultArray.add(tmpResSet);
- }
-
- return resultArray;
-
- }// queryByModel_Timed()
-
-
-
- /**
- * Run delete by model-ver.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param modelVersionId the model version id -- unique id for a model-ver node
- * @param topNodeTypeVal the top node type val -- required if no model-version-id is passed
- * @param startNodeFilterHash the start node filter hash -- used to locate the first node of instance data
- * @param apiVer the api ver
- * @param resVersion the res version -- resourceVersion of the top/first widget in the model instance
- * @return HashMap (keys = vertexIds that were deleted)
- * @throws AAIException the AAI exception
- */
- public Map<String,String> runDeleteByModel( String transId, String fromAppId,
- String modelVersionId, String topNodeTypeVal, Map<String,Object> startNodeFilterHash, String apiVer, String resVersion )
- throws AAIException {
-
- Map<String,String> retHash = new HashMap<>();
-
- // Locate the Model-ver node to be used
- Vertex modelVerVtx = null;
- if( modelVersionId != null && !modelVersionId.equals("") ){
- modelVerVtx = getNodeUsingUniqueId(transId, fromAppId, "model-ver",
- "model-version-id", modelVersionId);
- }
- else {
- // if they didn't pass the modelVersionId, then we need to use the startNode to figure it out
- // Locate the starting node based on the start node params
- if( topNodeTypeVal == null || topNodeTypeVal.equals("") ){
- throw new AAIException("AAI_6118", "If no model info is passed, then topNodeType is required. ");
- }
-
- Optional<Vertex> result = dbMethHelper.searchVertexByIdentityMap(topNodeTypeVal, startNodeFilterHash);
- if (!result.isPresent()) {
- throw new AAIException("AAI_6114", "No Node of type " + topNodeTypeVal + " found for properties");
- }
- Vertex startVtx = result.get();
-
- String startVertModVerId = startVtx.<String>property(addDBAliasedSuffix("model-version-id")).orElse(null);
- modelVerVtx = getNodeUsingUniqueId(transId, fromAppId, "model-ver",
- "model-version-id", startVertModVerId);
- }
-
- if( modelVerVtx == null ){
- throw new AAIException("AAI_6114", "Could not determine the model-ver for the given input parameters. ");
- }
-
- String topNType = "unknown";
- String modelType = getModelTypeFromModelVer( modelVerVtx, "" );
-
- if( modelType.equals("widget") ){
- // If they want to delete using a widget-level model.. That is just a delete of the one
- // instance of one of our nodes.
- String widgModNodeType = modelVerVtx.<String>property("model-name").orElse(null);
- if( (widgModNodeType == null) || widgModNodeType.equals("") ){
- String msg = "Could not find model-name for the widget model [" + modelVersionId + "].";
- throw new AAIException("AAI_6132", msg);
- }
- Optional<Vertex> result = dbMethHelper.locateUniqueVertex(widgModNodeType, startNodeFilterHash);
- if (!result.isPresent()) {
- throw new AAIException("AAI_6114", "No Node of type " + topNType + " found for properties");
- }
- Vertex widgetVtx = result.get();
- String widgId = widgetVtx.id().toString();
- serializer.delete(widgetVtx, resVersion, true);
- retHash.put(widgId, widgModNodeType);
- return retHash;
- }
-
- // ---------------------------------------------------------------------------------
- // If we got to here, this must be either a service or resource model.
- // So, we'll need to get a Hash of which parts of the model to delete.
- // NOTE- deleteByModel is deleting data based on one specific version of a model.
- // ---------------------------------------------------------------------------------
- String chkFirstNodePersonaModInvId = "";
- String chkFirstNodePersonaModVerId = "";
- String personaData = "";
- Vertex firstModElementVertex = getTopElementForSvcOrResModelVer( modelVerVtx, "" );
- topNType = getModElementWidgetType( firstModElementVertex, "" );
- if( (topNType == null) || topNType.equals("") ){
- String msg = "Could not determine the top-node nodeType for model-version-id: [" + modelVersionId + "]";
- throw new AAIException("AAI_6132", msg);
- }
- if( nodeTypeSupportsPersona(topNType) ){
- Vertex modelVtx = getModelGivenModelVer(modelVerVtx,"");
- chkFirstNodePersonaModInvId = modelVtx.<String>property("model-invariant-id").orElse(null);
- chkFirstNodePersonaModVerId = modelVerVtx.<String>property("model-version-id").orElse(null);
- personaData = "," + chkFirstNodePersonaModInvId + "," + chkFirstNodePersonaModVerId;
- }
-
- // Get the deleteKeyHash for this model
- String incomingTrail = "";
- Map<String, String> currentHash = new HashMap<>();
- Map<String, Vertex> modConHash = new HashMap<>();
- ArrayList <String> vidsTraversed = new ArrayList<>();
- Map<String, String> delKeyHash = collectDeleteKeyHash( transId, fromAppId,
- firstModElementVertex, incomingTrail, currentHash, vidsTraversed,
- 0, modConHash,
- chkFirstNodePersonaModInvId, chkFirstNodePersonaModVerId );
-
-
- System.out.println("\n ----DEBUG -----: Delete Hash for model: [" + modelVersionId + "] looks like: ");
- for( Map.Entry<String, String> entry : delKeyHash.entrySet() ){
- System.out.println("key = [" + entry.getKey() + "], val = [" + entry.getValue() + "]");
- }
- System.out.println("\n -----");
- // Locate the starting node that we'll use to start looking for instance data
- Optional<Vertex> result = dbMethHelper.searchVertexByIdentityMap(topNType, startNodeFilterHash);
- if (!result.isPresent()) {
- throw new AAIException("AAI_6114", "No Node of type " + topNType + " found for properties");
- }
- Vertex startVtx = result.get();
- if( !chkFirstNodePersonaModInvId.equals("") ){
- // NOTE: For Service or Resource models, if this is a nodeType that supports persona's, then
- // we need to make sure that the start node matches the persona values.
- String startVertPersonaModInvId = startVtx.<String>property(addDBAliasedSuffix("model-invariant-id")).orElse(null);
- String startVertPersonaModVerId = startVtx.<String>property(addDBAliasedSuffix("model-version-id")).orElse(null);
- if( !chkFirstNodePersonaModInvId.equals(startVertPersonaModInvId)
- || !chkFirstNodePersonaModVerId.equals(startVertPersonaModVerId) ){
- String msg = "Persona-Model data mismatch for start node (" + topNType + "), " +
- startNodeFilterHash ;
- throw new AAIException("AAI_6114", msg);
- }
- }
- String topVid = startVtx.id().toString();
-
- // Read the model-ver into a Map for processing
- Multimap<String, String> validNextStepMap = genTopoMap4ModelVer(transId, fromAppId,
- modelVerVtx, modelVersionId);
-
- // Collect the data
- String elementLocationTrail = topNType + personaData;
- vidsTraversed = new ArrayList<>();
- Map<String,String> emptyHash = new HashMap<>();
-
- // Pass emptyHash for the NQElement hash since that parameter only applies to Named Queries
- ResultSet retResSet = collectInstanceData( transId, fromAppId,
- startVtx, elementLocationTrail,
- validNextStepMap, vidsTraversed, 0, delKeyHash, emptyHash, apiVer );
-
- // Note: the new ResultSet will have each element tagged with the del flag so we'll know if it
- // should be deleted or not - so loop through the results in a try-block since some things
- // will get auto-deleted by parents before we get to them --- and try to remove each one.
- String vidToResCheck = topVid;
-
- retHash = deleteAsNeededFromResultSet( transId, fromAppId, retResSet,
- vidToResCheck, apiVer, resVersion, emptyHash );
- //String msgStr = "processed deletes for these vids: (\n"+ retHash.keySet().toString() + ").";
-
- return retHash;
-
- }// End of runDeleteByModel()
-
-
-
- /**
- * Delete as needed from result set.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param resSet the res set
- * @param vidToResCheck -- this vertex will need to have its resource-version checked
- * @param apiVer the api ver
- * @param resVersion the res version
- * @param hashSoFar the hash so far -- hash of what's been deleted so far
- * @return String
- * @throws AAIException the AAI exception
- */
- public Map<String,String> deleteAsNeededFromResultSet(String transId, String fromAppId,
- ResultSet resSet, String vidToResCheck, String apiVer, String resVersion, Map<String,String> hashSoFar )
- throws AAIException
- {
- Map<String,String> retHash = new HashMap<>();
- retHash.putAll( hashSoFar );
- Boolean deleteIt = false;
-
- if( resSet.getVert() == null ){
- return retHash;
- }
-
- Vertex thisVtx = resSet.getVert();
- String thisGuyId = "";
- String thisNT = "";
- String thisGuyStr = "";
-
- Boolean gotVtxOK = false;
- try {
- if( thisVtx != null ){
- thisGuyId = thisVtx.id().toString();
- thisNT = thisVtx.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- thisGuyStr = thisGuyId + "[" + thisNT + " found at:" + resSet.getLocationInModelSubGraph() + "]";
-
- // NOTE -- will try to set the NodeType to itself to see if the node has been deleted already in
- // this transaction. It lets you get properties from nodes being deleted where the
- // delete hasn't been committed yet. This check used to be accomplished with a call to
- // "vtx.isRemoved()" but that was a Titan-only feature and is not available anymore since
- // we no longer use Titan vertices.
- // If we don't do this check, we get errors later when we try to delete the node.
- thisVtx.property(AAIProperties.NODE_TYPE, thisNT);
- gotVtxOK = true;
- }
- }
- catch (Exception ex) {
- // Sometimes things have already been deleted by the time we get to them - just log it.
- AAIException aaiException = new AAIException("AAI_6154", thisGuyStr + ". msg = " + ex.getMessage());
- ErrorLogHelper.logException(aaiException);
-
- }
-
- if( !gotVtxOK ){
- // The vertex must have already been removed. Just return.
- // Note - We need to catch this because the DB sometimes can still have the vtx
- // and be able to get its ID but it is flagged internally as removed already.
- return retHash;
- }
- else {
- if( resSet.getNewDataDelFlag() != null && resSet.getNewDataDelFlag().equals("T") ){
- logger.debug(">> will try to delete this one >> " + thisGuyStr);
-
- try {
- Boolean requireResourceVersion = false;
- if( thisGuyId.equals(vidToResCheck) ){
- // This is the one vertex that we want to check the resourceId before deleting
- requireResourceVersion = true;
- }
- this.serializer.delete(thisVtx, resVersion, requireResourceVersion);
- }
- catch (AAIException ae) {
- String errorCode = ae.getErrorObject().getErrorCode();
- if ( errorCode.equals("6130") || errorCode.equals("6131") ) {
- // They didn't pass the correct resource-version for the top node.
- throw ae;
- }
- else {
- ErrorLogHelper.logException(ae);
- String errText = ae.getErrorObject().getErrorText();
- String errDetail = ae.getMessage();
- logger.debug("Exception when deleting " + thisGuyStr + ". ErrorCode = " + errorCode +
- ", errorText = " + errText + ", details = " + errDetail);
- }
- }
- catch( Exception e ){
- // We'd expect to get a "node not found" here sometimes depending on the order that
- // the model has us finding / deleting nodes.
- // Ignore the exception - but log it so we can see what happened.
- AAIException aaiException = new AAIException("AAI_6154", thisGuyStr + ". msg = " + e.getMessage());
- ErrorLogHelper.logException(aaiException);
-
- }
-
- // We can't depend on a thrown exception to tell us if a node was deleted since it may
- // have been auto=deleted before this removeAaiNode() call.
- // --- Not sure if we would want to check anything here -- because the graph.commit() is done outside of this call.
-
- deleteIt = true;
- }
- else {
- // --- DEBUG ----
- System.out.println(">>>>>>> NOT DELETING THIS ONE >>>> " + thisGuyStr );
- List<String> retArr = dbMethHelper.getVertexProperties(thisVtx);
- for( String info : retArr ){ System.out.println(info); }
- // --- DEBUG ----
- }
- }
-
- // Now call this routine for the sub-resultSets
- List <ResultSet> subResultSetList = resSet.getSubResultSet();
- Iterator <ResultSet> subResSetIter = subResultSetList.iterator();
- while( subResSetIter.hasNext() ){
- ResultSet tmpSubResSet = subResSetIter.next();
- retHash = deleteAsNeededFromResultSet( transId, fromAppId, tmpSubResSet,
- vidToResCheck, apiVer, resVersion, retHash );
- }
-
- if( deleteIt ){
- retHash.put(thisGuyId, thisGuyStr);
- }
-
- return retHash;
-
- }// deleteAsNeededFromResultSet()
-
-
-
- /**
- * Query by named query (old version).
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param namedQueryUuid the named query uuid
- * @param startNodeFilterArrayOfHashes the start node filter array of hashes --used to locate the first nodes of instance data
- * @param apiVer the api ver
- * @return resultSet
- * @throws AAIException the AAI exception
- */
- public List<ResultSet> queryByNamedQuery(String transId, String fromAppId,
- String namedQueryUuid,
- List <Map<String,Object>> startNodeFilterArrayOfHashes,
- String apiVer )
- throws AAIException {
-
- String dummyCutPoint = null;
- Map<String,Object> dummySecondaryFilterHash = null;
-
- return queryByNamedQuery( transId, fromAppId,
- namedQueryUuid,
- startNodeFilterArrayOfHashes,
- apiVer,
- dummyCutPoint,
- dummySecondaryFilterHash );
- }
-
-
- /**
- * Query by named query.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param namedQueryUuid the named query uuid
- * @param startNodeFilterArrayOfHashes the start node filter array of hashes --used to locate the first nodes of instance data
- * @param apiVer the api ver
- * @param secondaryFilterCutPoint nodeType where we will prune if secondary filter is not met
- * @param secondaryFilterHash secondary filter params
- * @return resultSet
- * @throws AAIException the AAI exception
- */
- public List<ResultSet> queryByNamedQuery(String transId, String fromAppId,
- String namedQueryUuid,
- List<Map<String,Object>> startNodeFilterArrayOfHashes,
- String apiVer,
- String secondaryFilterCutPoint,
- Map<String,Object> secondaryFilterHash )
- throws AAIException {
-
- final String transId_f = transId;
- final String fromAppId_f = fromAppId;
- final String namedQueryUuid_f = namedQueryUuid;
- final List<Map<String,Object>> startNodeFilterArrayOfHashes_f = startNodeFilterArrayOfHashes;
- final String apiVer_f = apiVer;
- final String secondaryFilterCutPoint_f = secondaryFilterCutPoint;
- final Map<String,Object> secondaryFilterHash_f = secondaryFilterHash;
-
- // Find out what our time-limit should be
- int timeLimitSec = 0;
- String timeLimitString = AAIConfig.get("aai.model.query.timeout.sec");
- if( timeLimitString != null && !timeLimitString.equals("") ){
- try {
- timeLimitSec = Integer.parseInt(timeLimitString);
- }
- catch ( Exception nfe ){
- // Don't worry, we will leave the limit as zero - which tells us not to use it.
- }
- }
-
- if( timeLimitSec <= 0 ){
- // We will NOT be using a timer
- return queryByNamedQuery_Timed( transId, fromAppId,
- namedQueryUuid,
- startNodeFilterArrayOfHashes,
- apiVer,
- secondaryFilterCutPoint_f,
- secondaryFilterHash_f );
- }
-
- List<ResultSet> resultList = new ArrayList<>();
- TimeLimiter limiter = new SimpleTimeLimiter();
- try {
- resultList = limiter.callWithTimeout(new AaiCallable <List<ResultSet>>() {
- public List<ResultSet> process() throws AAIException {
- return queryByNamedQuery_Timed( transId_f, fromAppId_f,
- namedQueryUuid_f,
- startNodeFilterArrayOfHashes_f,
- apiVer_f,
- secondaryFilterCutPoint_f,
- secondaryFilterHash_f );
- }
- }, timeLimitSec, TimeUnit.SECONDS, true);
-
- }
- catch (AAIException ae) {
- // Re-throw AAIException so we get can tell what happened internally
- throw ae;
- }
- catch (UncheckedTimeoutException ute) {
- throw new AAIException("AAI_6140", "Query Processing Limit exceeded. (limit = " + timeLimitSec + " seconds)");
- }
- catch (Exception e) {
- throw new AAIException("AAI_6128", "Unexpected exception in queryByNamedQuery(): " + e.getMessage() );
- }
-
- return resultList;
- }
-
-
- /**
- * Query by named query timed.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param namedQueryUuid the named query uuid
- * @param startNodeFilterArrayOfHashes the start node filter array of hashes --used to locate the first nodes of instance data
- * @param apiVer the api ver
- * @param secondaryFilterCutPoint the nodeType where we will parse for the secondary Filter
- * @param secondaryFilterHash the secondary filter hash
- * @return resultSet
- * @throws AAIException the AAI exception
- */
- public List<ResultSet> queryByNamedQuery_Timed(String transId, String fromAppId,
- String namedQueryUuid,
- List<Map<String,Object>> startNodeFilterArrayOfHashes,
- String apiVer,
- String secondaryFilterCutPoint,
- Map<String,Object> secondaryFilterHash
- )
- throws AAIException {
-
- // Locate the Query to be used
- Vertex queryVtx = getNodeUsingUniqueId(transId, fromAppId, "named-query",
- "named-query-uuid", namedQueryUuid);
-
- // Get the first/top named-query-element used by this query
- Iterator<Vertex> vertI = this.traverseIncidentEdges(EdgeType.TREE, queryVtx, "named-query-element");
- Vertex firstNqElementVert = null;
- int count = 0;
- String topNType = "";
- while( vertI != null && vertI.hasNext() ){
- firstNqElementVert = vertI.next();
- count++;
- topNType = getNqElementWidgetType( transId, fromAppId, firstNqElementVert, "" );
- }
-
- if( count < 1 ){
- // A named query must start with a single top element
- throw new AAIException("AAI_6133", "No top-node defined for named-query-uuid = [" + namedQueryUuid + "]");
- }
- else if( count > 1 ){
- // A named query should start with a single top element
- throw new AAIException("AAI_6133", "More than one top-node defined for named-query-uuid = [" + namedQueryUuid + "]");
- }
- if( (topNType == null) || topNType.equals("") ){
- String msg = "Could not determine the top-node nodeType for Named Query: [" + namedQueryUuid + "]";
- throw new AAIException("AAI_6133", msg);
- }
-
- // Read the topology into a hash for processing
- Multimap<String, String> validNextStepMap = genTopoMap4NamedQ(transId, fromAppId, queryVtx, namedQueryUuid);
-
- List<Vertex> startVertList = new ArrayList<>();
- if( startNodeFilterArrayOfHashes.size() == 1 ){
- // If there is only one set of startFilter info given, then allow it to possibly not be
- // defining just one start node.
- Map<String, Object> tmpHash = startNodeFilterArrayOfHashes.get(0);
- Set <String> propKeySet = tmpHash.keySet();
- Iterator<String> propIter = propKeySet.iterator();
- Introspector obj = loader.introspectorFromName(topNType);
- Set<String> keys = obj.getKeys();
- boolean foundIndexedField = false;
- int propertiesSet = 0;
- while( propIter.hasNext() ){
- String oldVtxKey = propIter.next();
- String newKey = oldVtxKey;
- String [] parts = oldVtxKey.split("\\.");
- if( parts.length == 2 ){
- newKey = parts[1];
- }
- Object obVal = tmpHash.get(oldVtxKey);
- if (obj.hasProperty(newKey)) {
- if (keys.contains(newKey)) {
- foundIndexedField = true;
- }
- obj.setValue(newKey, obVal);
- propertiesSet++;
- }
- }
- //we found all the properties in the startNodeType
- if (propertiesSet == propKeySet.size()) {
- if (foundIndexedField) {
- QueryBuilder builder = this.engine.getQueryBuilder().exactMatchQuery(obj);
- startVertList = builder.toList();
- } else {
- //force a filter from aai-node-type
- QueryBuilder builder = this.engine.getQueryBuilder().createContainerQuery(obj).exactMatchQuery(obj);
- startVertList = builder.toList();
- }
- } else {
- Optional<Vertex> tmpVtx = dbMethHelper.searchVertexByIdentityMap(topNType, startNodeFilterArrayOfHashes.get(0));
- // Only found one, so just use it.
- if (tmpVtx.isPresent()) {
- startVertList.add(tmpVtx.get());
- }
- }
- }
- else {
- // Since they give an array of startNodeFilterHash info, we expect each one
- // to just point to one node.
- for( int i = 0; i < startNodeFilterArrayOfHashes.size(); i++ ){
- // Locate the starting node for each set of data
- Optional<Vertex> tmpVtx = dbMethHelper.searchVertexByIdentityMap(topNType, startNodeFilterArrayOfHashes.get(i));
- if (tmpVtx.isPresent()) {
- startVertList.add(tmpVtx.get());
- }
- }
- }
-
- if (startVertList.isEmpty()) {
- throw new AAIException("AAI_6114", "No Node of type " + topNType + " found for properties");
- }
- // Make sure they're not bringing back too much data
- String maxString = AAIConfig.get("aai.model.query.resultset.maxcount");
- if( maxString != null && !maxString.equals("") ){
- int maxSets = Integer.parseInt(maxString);
- if( startVertList.size() > maxSets ){
- String msg = " Query returns " + startVertList.size() + " resultSets. Max allowed is: " + maxSets;
- throw new AAIException("AAI_6141", msg);
- }
- }
-
- // Loop through each start node and get its data
- List<ResultSet> resSetList = new ArrayList<>();
- for( int i = 0; i < startVertList.size(); i++ ){
- Vertex startVtx = startVertList.get(i);
- // Collect the data
- String elementLocationTrail = topNType;
- ArrayList <String> vidsTraversed = new ArrayList<>();
- Map<String,String> emptyDelKeyHash = new HashMap<>(); // Does not apply to Named Queries
-
- // Get the mapping of namedQuery elements to our widget topology for this namedQuery
- String incomingTrail = "";
- Map<String, String> currentHash = new HashMap<>();
-
- Map<String,String> namedQueryElementHash = collectNQElementHash( transId, fromAppId,
- firstNqElementVert, incomingTrail, currentHash, vidsTraversed, 0 );
-
- vidsTraversed = new ArrayList<>();
- ResultSet tmpResSet = collectInstanceData( transId, fromAppId,
- startVtx, elementLocationTrail,
- validNextStepMap, vidsTraversed, 0, emptyDelKeyHash, namedQueryElementHash, apiVer );
- resSetList.add(tmpResSet);
- }
-
- // If a secondary filter was defined, we will prune the collected instance data result set(s) based on it.
- List<ResultSet> prunedResSetList = new ArrayList<>();
- if( resSetList != null && !resSetList.isEmpty() ){
- for( int i = 0; i < resSetList.size(); i++ ){
- if( secondaryFilterCutPoint == null || secondaryFilterCutPoint.equals("") || secondaryFilterHash == null ){
- // They didn't want to do any pruning, so just use the results we already had
- prunedResSetList.add(resSetList.get(i));
- }
- else {
- ResultSet tmpResSet = pruneResultSet(resSetList.get(i), secondaryFilterCutPoint, secondaryFilterHash);
- if( tmpResSet != null ){
- prunedResSetList.add(tmpResSet);
- }
- }
- }
- }
-
- // Since a NamedQuery can mark some nodes as "do-not-display", we need to collapse our resultSet so
- // does not display those nodes.
- List<ResultSet> collapsedResSetList = new ArrayList<>();
- if( prunedResSetList != null && !prunedResSetList.isEmpty() ){
- for( int i = 0; i < prunedResSetList.size(); i++ ){
- // Note - a single resultSet could be collapsed into many smaller ones if they
- // marked all the "top" node-elements as do-not-output. Ie. the query may
- // have had a top-node of "generic-vnf" which joins down to different l-interfaces.
- // If they only want to see the l-interfaces, then a single result set
- // would be "collapsed" into many separate resultSets - each of which is
- // just a single l-interface.
- List<ResultSet> tmpResSetList = collapseForDoNotOutput(prunedResSetList.get(i));
- if( tmpResSetList != null && !tmpResSetList.isEmpty() ){
- for( int x = 0; x < tmpResSetList.size(); x++ ){
- //showResultSet( tmpResSetList.get(x), 0 ); //DEBUG-- this was just for testing
- collapsedResSetList.add(tmpResSetList.get(x));
- }
- }
- }
- }
-
- return collapsedResSetList;
-
- }// End of queryByNamedQuery()
-
-
- /**
- * Prune a result set as per a secondary filter.
- *
- * @param resSetVal the res set val
- * @param cutPointType the nodeType where the trim will happen
- * @param secFilterHash hash of properties and values to use as the secondary filter
- * @return pruned result set
- * @throws AAIException the AAI exception
- */
- public ResultSet pruneResultSet(ResultSet resSetVal, String cutPointType, Map<String,Object> secFilterHash )
- throws AAIException {
-
- // Given a ResultSet and some secondary filter info, do pruning as needed
- ResultSet pResSet = new ResultSet();
-
- // For this ResultSet, we will see if we are on a node of the type that is our cutPoint;
- // then only keep it if we peek "below" and see a match for our filter.
-
- String nt = resSetVal.getVert().<String>property(AAIProperties.NODE_TYPE).orElse(null);
- if( nt != null && nt.equals(cutPointType) ){
- // We are on the type of node that may need to be "pruned" along with it's sub-results
- if( ! satisfiesFilters(resSetVal, secFilterHash) ){
- // Return an empty result set since we are pruning at this level.
- return pResSet;
- }
- }
-
- // If we made it to here, we will not be pruning at this level, so we will
- // be returning a copy of this resultSet that has it's subResults pruned (as needed).
- pResSet.setVert(resSetVal.getVert());
- pResSet.setDoNotOutputFlag(resSetVal.getDoNotOutputFlag());
- pResSet.setExtraPropertyHash(resSetVal.getExtraPropertyHash());
- pResSet.setLocationInModelSubGraph(resSetVal.getLocationInModelSubGraph());
- pResSet.setNewDataDelFlag(resSetVal.getNewDataDelFlag());
- pResSet.setPropertyLimitDesc(resSetVal.getPropertyLimitDesc());
- pResSet.setPropertyOverRideHash(resSetVal.getPropertyOverRideHash());
-
- if( !resSetVal.getSubResultSet().isEmpty() ){
- ListIterator<ResultSet> listItr = resSetVal.getSubResultSet().listIterator();
- List<ResultSet> newSubSetList = new ArrayList<>();
- while( listItr.hasNext() ){
- ResultSet tmpSubResSet = pruneResultSet( listItr.next(), cutPointType, secFilterHash );
- if( tmpSubResSet.getVert() != null ){
- // This one wasn't pruned - so keep it.
- newSubSetList.add(tmpSubResSet);
- }
- }
- pResSet.setSubResultSet(newSubSetList);
- }
-
- return pResSet;
-
- }// End pruneResultSet()
-
-
- /**
- * Satisfies hash of filters.
- *
- * @param resSet the res set
- * @param filterHash the filter hash
- * @return true, if successful
- * @throws AAIException the AAI exception
- */
- public boolean satisfiesFilters(ResultSet resSet, Map<String,Object> filterHash )
- throws AAIException {
-
- if( filterHash.isEmpty() ){
- // Nothing to look for, so no, we didn't find it.
- return false;
- }
-
- Iterator <?> it = filterHash.entrySet().iterator();
- while( it.hasNext() ){
- Map.Entry<?,?> filtEntry = (Map.Entry<?,?>) it.next();
- String propNodeTypeDotName = (filtEntry.getKey()).toString();
- String fpv = (filtEntry.getValue()).toString();
-
- int periodLoc = propNodeTypeDotName.indexOf('.');
- if( periodLoc <= 0 ){
- String emsg = "Bad filter param key passed in: [" + propNodeTypeDotName + "]. Expected format = [nodeName.paramName]\n";
- throw new AAIException("AAI_6120", emsg);
- }
- else {
- String fnt = propNodeTypeDotName.substring(0,periodLoc);
- String fpn = propNodeTypeDotName.substring(periodLoc + 1);
- if( filterMetByThisSet( resSet, fnt, fpn, fpv ) ){
- //System.out.println(" DEBUG -- satisfied/matched filter: [" + fnt + "|" + fpn + "|" + fpv + "].");
- }
- else {
- //System.out.println(" DEBUG -- NOT satisfied/matched filter: [" + fnt + "|" + fpn + "|" + fpv + "].");
- return false;
- }
- }
- }
-
- // Made it through all the filters -- it found what we were looking for.
- return true;
-
- }// end of satisfiesFilters()
-
-
- /**
- * Filter met by this set.
- *
- * @param resSet the res set
- * @param filtNodeType the filt node type
- * @param filtPropName the filt prop name
- * @param filtPropVal the filt prop val
- * @return true, if successful
- */
- public boolean filterMetByThisSet(ResultSet resSet, String filtNodeType, String filtPropName, String filtPropVal ) {
+ private static Logger logger = LoggerFactory.getLogger(ModelBasedProcessing.class);
+ private static final int MAX_LEVELS = 50; // max depth allowed for our model - to protect
+ // against infinite loop problems
+
+ private TransactionalGraphEngine engine;
+ private Loader loader;
+ private DBSerializer serializer;
+ private DbMethHelper dbMethHelper;
+
+ protected ModelBasedProcessing() {
+
+ }
+
+ public ModelBasedProcessing(Loader loader, TransactionalGraphEngine engine,
+ DBSerializer serializer) {
+ this.loader = loader;
+ this.engine = engine;
+ this.serializer = serializer;
+ dbMethHelper = new DbMethHelper(loader, engine);
+ }
+
+ /**
+ * Gets the start nodes and model-ver's.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param passedModelVersionId the passed model-version-id -- optional (unique id for a
+ * model-ver)
+ * @param passedModelInvId the passed model-invariant-id -- optional
+ * @param passedModelName the passed model-name -- optional
+ * @param passedTopNodeType the passed top node type -- optional (needed if neither
+ * model=invariant-id nor model-version-id is passed)
+ * @param startNodeFilterArrayOfHashes the start node filter array of hashes -- optional (used
+ * to locate the first node(s) of instance data)
+ * @param apiVer the api ver
+ * @return HashMap of startNodes and their corresponding model-version-id's
+ * @throws AAIException the AAI exception
+ */
+ public Map<String, String> getStartNodesAndModVersionIds(String transId, String fromAppId,
+ String passedModelVersionId, String passedModelInvId, String passedModelName,
+ String passedTopNodeType, List<Map<String, Object>> startNodeFilterArrayOfHashes,
+ String apiVer) throws AAIException {
+ // ----------------------------------------------------------------------------------------------------
+ // Get a hash for all start-nodes (key = vtxId, val = modelVersionId that applies)
+ // If no start-node-key info is passed, then use either the passed modelVersion or
+ // the passed model-invariant-id or model-name to collect them.
+ // If start-node-key info is given, use it instead to look for start-nodes.
+ // Note: if ONLY start-node-key info is given, then it would have to map to nodes which
+ // have persona data. Otherwise we'd have no way to know what model to collect data with.
+ // ----------------------------------------------------------------------------------------------------
+
+ Iterator<Vertex> startVerts = null;
+ Map<String, String> startVertInfo = new HashMap<>();
+
+ if (startNodeFilterArrayOfHashes.isEmpty()) {
+ // Since they did not give any data to find start instances, we will have to find them
+ // using whatever model-info they provided so we can use it to map to persona-data in
+ // the db.
+ if ((passedModelVersionId == null || passedModelVersionId.equals(""))
+ && (passedModelInvId == null || passedModelInvId.equals(""))
+ && (passedModelName == null || passedModelName.equals(""))) {
+ throw new AAIException("AAI_6118",
+ "ModelInvariantId or ModelName or ModelVersionId required if no startNodeFilter data passed.");
+ } else {
+ // Use whatever model info they pass to find start-node instances
+ // Get the first/top named-query-element used by this query
+ if (passedModelVersionId != null && !passedModelVersionId.equals("")) {
+ // Need to look up the model-invariant-id and model-version to check against
+ // persona data
+ Vertex modVerVtx = getNodeUsingUniqueId(transId, fromAppId, "model-ver",
+ "model-version-id", passedModelVersionId);
+ Vertex modVtx = getModelGivenModelVer(modVerVtx, "");
+ String calcModId = modVtx.<String>property("model-invariant-id").orElse(null);
+ // Now we can look up instances that match this model's info
+ if (calcModId != null) {
+ startVerts = this.engine.asAdmin().getReadOnlyTraversalSource().V()
+ .has(addDBAliasedSuffix("model-invariant-id"), calcModId)
+ .has(addDBAliasedSuffix("model-version-id"), passedModelVersionId);
+ }
+ } else if (passedModelInvId != null && !passedModelInvId.equals("")) {
+ // They gave us the model-invariant-id
+ startVerts = this.engine.asAdmin().getReadOnlyTraversalSource().V()
+ .has(addDBAliasedSuffix("model-invariant-id"), passedModelInvId);
+ } else if (passedModelName != null && !passedModelName.equals("")) {
+ List<Vertex> modelVerVtxList =
+ getModelVersUsingName(transId, fromAppId, passedModelName);
+ List<Vertex> startVtxList = new ArrayList<>();
+ // Need to look up the model-inv-ids and model-versions to check against persona
+ // data
+ if (!modelVerVtxList.isEmpty()) {
+ for (int i = 0; i < modelVerVtxList.size(); i++) {
+ String calcModVerId = (modelVerVtxList.get(i))
+ .<String>property("model-version-id").orElse(null);
+ Vertex modVtx = getModelGivenModelVer(modelVerVtxList.get(i), "");
+ String calcModInvId =
+ modVtx.<String>property("model-invariant-id").orElse(null);
+ // Now we can look up instances that match this model's info
+ Iterator<Vertex> tmpStartIter =
+ this.engine.asAdmin().getReadOnlyTraversalSource().V()
+ .has(addDBAliasedSuffix("model-invariant-id"), calcModInvId)
+ .has(addDBAliasedSuffix("model-version-id"), calcModVerId);
+ while (tmpStartIter.hasNext()) {
+ Vertex tmpStartVert = tmpStartIter.next();
+ startVtxList.add(tmpStartVert);
+ }
+ }
+ }
+ if (!startVtxList.isEmpty()) {
+ startVerts = startVtxList.iterator();
+ }
+ }
+ }
+
+ if (startVerts != null) {
+ while (startVerts.hasNext()) {
+ Vertex tmpStartVert = startVerts.next();
+ String vid = tmpStartVert.id().toString();
+ // String tmpModId =
+ // tmpStartVert.<String>property(addDBAliasedSuffix("model-invariant-id")).orElse(null);
+ String tmpModVerId = tmpStartVert
+ .<String>property(addDBAliasedSuffix("model-version-id")).orElse(null);
+ startVertInfo.put(vid, tmpModVerId);
+ }
+ }
+ if (startVertInfo.isEmpty()) {
+ throw new AAIException("AAI_6114",
+ "Start Node(s) could not be found for model data passed. "
+ + "(modelVersionId = [" + passedModelVersionId + "], modelInvariantId = ["
+ + passedModelInvId + "], modelName = [" + passedModelName + "])");
+ }
+
+ return startVertInfo;
+ } else {
+ // Use start-node filter info to find start-node(s) - Note - there could also be model
+ // info passed that we'll need
+ // to use to trim down the set of start-nodes that we find based on the startNodeFilter
+ // data.
+ String modTopNodeType = "";
+ String modInfoStr = "";
+ if (passedModelVersionId != null && !passedModelVersionId.equals("")) {
+ modTopNodeType =
+ getModelVerTopWidgetType(transId, fromAppId, passedModelVersionId, "", "");
+ modInfoStr = "modelVersionId = (" + passedModelVersionId + ")";
+ } else if (passedModelInvId != null && !passedModelInvId.equals("")) {
+ modTopNodeType =
+ getModelVerTopWidgetType(transId, fromAppId, "", passedModelInvId, "");
+ modInfoStr = "modelId = (" + passedModelInvId + ")";
+ } else if (passedModelName != null && !passedModelName.equals("")) {
+ modTopNodeType =
+ getModelVerTopWidgetType(transId, fromAppId, "", "", passedModelName);
+ modInfoStr = "modelName = (" + passedModelName + ")";
+ }
+
+ if (modTopNodeType.equals("")) {
+ if ((passedTopNodeType == null) || passedTopNodeType.equals("")) {
+ String msg =
+ "Could not determine the top-node nodeType for this request. modelInfo: ["
+ + modInfoStr + "]";
+ throw new AAIException("AAI_6118", msg);
+ } else {
+ // We couldn't find a top-model-type based on passed in model info, but they
+ // gave us a type to use -- so use it.
+ modTopNodeType = passedTopNodeType;
+ }
+ } else {
+ // we did get a topNode type based on model info - make sure it doesn't contradict
+ // the passsed-in one (if there is one)
+ if (passedTopNodeType != null && !passedTopNodeType.equals("")
+ && !passedTopNodeType.equals(modTopNodeType)) {
+ throw new AAIException("AAI_6120",
+ "topNodeType passed in [" + passedTopNodeType
+ + "] does not match nodeType derived for model info passed in: ["
+ + modTopNodeType + "]");
+ }
+ }
+
+ List<String> modelVersionIds2Check = new ArrayList<>();
+ if ((passedModelName != null && !passedModelName.equals(""))) {
+ // They passed a modelName, so find all the model UUIDs (model-version-id's) that
+ // map to this
+ modelVersionIds2Check =
+ getModelVerIdsUsingName(transId, fromAppId, passedModelName);
+ }
+ if ((passedModelVersionId != null && !passedModelVersionId.equals(""))) {
+ // They passed in a modelNameVersionId
+ if (modelVersionIds2Check.isEmpty()) {
+ // There was no modelName passed, so we can use the passed modelNameVersionId
+ modelVersionIds2Check.add(passedModelVersionId);
+ } else if (modelVersionIds2Check.contains(passedModelVersionId)) {
+ // The passed in uuid does not conflict with what we got using the passed-in
+ // modelName.
+ // We'll just use the passed in uuid in this case.
+ // Hopefully they would not be passing strange combinations like this, but we'll
+ // try to deal with it.
+ modelVersionIds2Check = new ArrayList<>(); // Clear out what we had
+ modelVersionIds2Check.add(passedModelVersionId);
+ }
+ }
+
+ // We should now be OK with our topNodeType for this request, so we can look for the
+ // actual startNodes
+ for (int i = 0; i < startNodeFilterArrayOfHashes.size(); i++) {
+ // Locate the starting node which will be used to look which corresponds to this set
+ // of filter data
+ Vertex startVtx = null;
+ try {
+ Optional<Vertex> result = dbMethHelper.searchVertexByIdentityMap(modTopNodeType,
+ startNodeFilterArrayOfHashes.get(i));
+ if (!result.isPresent()) {
+ throw new AAIException("AAI_6114",
+ "No Node of type " + modTopNodeType + " found for properties");
+ }
+ startVtx = result.get();
+ } catch (AAIException e) {
+ String msg = "Could not find startNode of type = [" + modTopNodeType
+ + "], given these params: " + startNodeFilterArrayOfHashes.get(i)
+ + ". msg # from getUniqueNode() = " + e.getMessage();
+ throw new AAIException("AAI_6114", msg);
+ }
+
+ String vid = startVtx.id().toString();
+ String personaModInvId = startVtx
+ .<String>property(addDBAliasedSuffix("model-invariant-id")).orElse(null);
+ String personaModVerId =
+ startVtx.<String>property(addDBAliasedSuffix("model-version-id")).orElse(null);
+
+ // Either this start-node has persona info (which should not contradict any
+ // passed-in model info)
+ // or they should have passed in the model to use - so we'd just use that.
+ if (personaModVerId != null && !personaModVerId.equals("")) {
+ // There is persona data in this start-node. So make sure it doesn't contradict
+ // any "passed" stuff
+ if (modelVersionIds2Check.isEmpty()
+ && (passedModelInvId == null || passedModelInvId.equals(""))) {
+ // They didn't pass any model info, so use the persona one.
+ startVertInfo.put(vid, personaModVerId);
+ } else if (modelVersionIds2Check.isEmpty()
+ && (passedModelInvId != null && !passedModelInvId.equals(""))) {
+ // They passed in just the modelId - so check it
+ if (passedModelInvId.equals(personaModInvId)) {
+ startVertInfo.put(vid, personaModVerId);
+ }
+ } else if (!modelVersionIds2Check.isEmpty()
+ && (passedModelInvId == null || passedModelInvId.equals(""))) {
+ // They passed in just modelVersionId - so check
+ if (modelVersionIds2Check.contains(personaModVerId)) {
+ startVertInfo.put(vid, personaModVerId);
+ }
+ } else if (!modelVersionIds2Check.isEmpty()
+ && (passedModelInvId != null && !passedModelInvId.equals(""))) {
+ // We have BOTH a modelVersionIds and a modelId to check
+ if (passedModelInvId.equals(personaModInvId)
+ && modelVersionIds2Check.contains(personaModVerId)) {
+ startVertInfo.put(vid, personaModVerId);
+ }
+ }
+ } else {
+ // This start node did not have persona info -- so we will use the passed in
+ // model info if they passed one
+ if (passedModelVersionId != null && !passedModelVersionId.equals("")) {
+ // The model-version-id uniquely identifies a model-ver, so we can use it.
+ startVertInfo.put(vid, passedModelVersionId);
+ } else {
+ throw new AAIException("AAI_6118",
+ "Found startNode but since it does not have persona data, the "
+ + " model-version-id is required. ");
+ }
+ }
+ }
+ }
+
+ return startVertInfo;
+
+ }// end of getStartNodesAndModVersionIds()
+
+ /**
+ * Query by model. (really model-ver)
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param modelVersionId the model-version-id (unique id in model-ver)
+ * @param modelInvariantId the model-invariant-id (unique id in model)
+ * @param modelName the model name
+ * @param topNodeType - optional (needed if neither model-invariant-id nor model-version-id is
+ * passed)
+ * @param startNodeFilterArrayOfHashes the start node filter array of hashes -- optional (used
+ * to locate the first node(s) of instance data)
+ * @param apiVer the api ver
+ * @return resultSet
+ * @throws AAIException the AAI exception
+ */
+ public List<ResultSet> queryByModel(String transId, String fromAppId, String modelVersionId,
+ String modelInvariantId, String modelName, String topNodeType,
+ List<Map<String, Object>> startNodeFilterArrayOfHashes, String apiVer) throws AAIException {
+
+ final String transId_f = transId;
+ final String fromAppId_f = fromAppId;
+ final String modelVersionId_f = modelVersionId;
+ final String modelInvId_f = modelInvariantId;
+ final String modelName_f = modelName;
+ final String topNodeType_f = topNodeType;
+ final List<Map<String, Object>> startNodeFilterArrayOfHashes_f =
+ startNodeFilterArrayOfHashes;
+ final String apiVer_f = apiVer;
+
+ // Find out what our time-limit should be
+ int timeLimitSec = 0;
+ String timeLimitString = AAIConfig.get("aai.model.query.timeout.sec");
+ if (timeLimitString != null && !timeLimitString.equals("")) {
+ try {
+ timeLimitSec = Integer.parseInt(timeLimitString);
+ } catch (Exception nfe) {
+ // Don't worry, we will leave the limit as zero - which tells us not to use it.
+ }
+ }
+
+ if (timeLimitSec <= 0) {
+ // We will NOT be using a timer
+ return queryByModel_Timed(transId, fromAppId, modelVersionId, modelInvariantId,
+ modelName, topNodeType, startNodeFilterArrayOfHashes, apiVer);
+ }
+
+ List<ResultSet> resultList = new ArrayList<>();
+ TimeLimiter limiter = new SimpleTimeLimiter();
+ try {
+
+ resultList = limiter.callWithTimeout(new AaiCallable<List<ResultSet>>() {
+ public List<ResultSet> process() throws AAIException {
+ return queryByModel_Timed(transId_f, fromAppId_f, modelVersionId_f,
+ modelInvId_f, modelName_f, topNodeType_f, startNodeFilterArrayOfHashes_f,
+ apiVer_f);
+ }
+ }, timeLimitSec, TimeUnit.SECONDS, true);
+ } catch (AAIException ae) {
+ // Re-throw AAIException so we get can tell what happened internally
+ throw ae;
+ } catch (UncheckedTimeoutException ute) {
+ throw new AAIException("AAI_6140",
+ "Query Processing Limit exceeded. (limit = " + timeLimitSec + " seconds)");
+ } catch (Exception e) {
+ throw new AAIException("AAI_6128",
+ "Unexpected exception in queryByModel(): " + e.getMessage());
+ }
+
+ return resultList;
+ }
+
+ /**
+ * Query by model (model-ver) timed.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param modelVersionId the model-version-id (unique id in model-ver)
+ * @param modelInvariantId the model-invariant-id (unique id in model)
+ * @param modelName the model name
+ * @param topNodeType the top node type
+ * @param startNodeFilterArrayOfHashesVal the start node filter array of hashes
+ * @param apiVer the api ver
+ * @return the array list
+ * @throws AAIException the AAI exception
+ */
+ public List<ResultSet> queryByModel_Timed(String transId, String fromAppId,
+ String modelVersionId, String modelInvariantId, String modelName, String topNodeType,
+ List<Map<String, Object>> startNodeFilterArrayOfHashesVal, String apiVer)
+ throws AAIException {
+
+ List<ResultSet> resultArray = new ArrayList<>();
+
+ // NOTE: this method can be used for different styles of queries:
+ // a) They could pass neither a modelVersionId or a modelInvariantId but just pass a set of
+ // data defining start-nodes.
+ // Note - with no model info, we need them to pass the startNodeType for us to be able to
+ // use the
+ // start-node-filter data. We would look at each start node and ensure that each has
+ // persona-model info.
+ // Then use whatever model corresponds to each instance to pull that instance's data.
+ // b) They could pass a modelInvariantId, but no modelVersionId and no startNode info. In
+ // this case, we
+ // Would look in the database for all nodes that have a model-invariant-id-local that
+ // matches what was
+ // passed, and then for each of those instances, pull the data based on the corresponding
+ // model.
+ // c) They could pass a model-version-id, but no startNode info. We'd make sure that if a
+ // model-invariant-id was also passed, that it does not conflict - but it really should be
+ // null if they
+ // are passing a full model-version-id. Like case -b-, we'd do a query for all nodes
+ // that have persona info that corresponds to the model-version-id passed and then
+ // collect data for each one.
+ // d) They could pass either modelVersionId or modelInvariantId AND startNodeFilter info. In
+ // this case we
+ // would look at the model info to figure out what the top-node-type is, then look at the
+ // top-node instances based on the startNodeFilter. We'd only collect data for each instance
+ // if
+ // it's persona model info matches what was passed in.
+
+ // Sorry to do this, but code that gets called with an empty hash as the first array element
+ // was causing errors
+ List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
+ if (!startNodeFilterArrayOfHashesVal.isEmpty()) {
+ Map<String, Object> tmpH = startNodeFilterArrayOfHashesVal.get(0);
+ if (!tmpH.isEmpty()) {
+ for (int i = 0; i < startNodeFilterArrayOfHashesVal.size(); i++) {
+ startNodeFilterArrayOfHashes.add(startNodeFilterArrayOfHashesVal.get(i));
+ }
+ }
+ }
+
+ // ----------------------------------------------------------------------------------------------------------
+ // Get a Hash of all the start-nodes (top instance-data node for a model-ver where we will
+ // start collecting data) for startNode2ModelVerHash:
+ // key = vertex-id for the startNode,
+ // value = model-version-id for the corresponding model-ver
+ // ----------------------------------------------------------------------------------------------------------
+ Map<String, String> startNode2ModelVerHash =
+ getStartNodesAndModVersionIds(transId, fromAppId, modelVersionId, modelInvariantId,
+ modelName, topNodeType, startNodeFilterArrayOfHashes, apiVer);
+
+ // System.out.println("\nDEBUG -- Here's a dump of the startnodes/model-vers: " +
+ // startNode2ModelVerHash.toString());
+
+ // --------------------------------------------------------------------------------------------------------
+ // Figure out what-all models (model-ver nodes) we will be dealing with
+ // Note - Instances must all use the same type of start-node, but do not have to all use the
+ // same model-ver.
+ // --------------------------------------------------------------------------------------------------------
+ Map<String, Vertex> distinctModelVersHash = new HashMap<>();
+ // For distinctModelVersHash: key = modelVersionId, val= modelVerVertex
+ String startNodeType = "";
+ if (topNodeType != null && !topNodeType.equals("")) {
+ startNodeType = topNodeType;
+ }
+
+ List<String> skipModelVerIdList = new ArrayList<>();
+ List<String> skipStartVertVerIdList = new ArrayList<>();
+ Set<String> snKeySet = startNode2ModelVerHash.keySet();
+ Iterator<String> startNodeIterator = snKeySet.iterator();
+ while (startNodeIterator.hasNext()) {
+ String modVerIdKey = startNodeIterator.next();
+ String modVerId = startNode2ModelVerHash.get(modVerIdKey);
+ if (!distinctModelVersHash.containsKey(modVerId)) {
+ // First time seeing this model-version-id
+ Vertex modVerVtx = getNodeUsingUniqueId(transId, fromAppId, "model-ver",
+ "model-version-id", modVerId);
+ String tmpNodeType = "";
+ try {
+ tmpNodeType = getModelVerTopWidgetType(modVerVtx, "");
+ } catch (AAIException ae) {
+ // There must be some old bad data in the db - we will skip over this model-ver
+ // since its
+ // model is not good anymore - but will log that this is happening.
+ skipModelVerIdList.add(modVerId);
+ skipStartVertVerIdList.add(modVerIdKey);
+ System.out
+ .println(">>> WARNING - will not collect model data for this vertex since "
+ + "it uses an inconsistant model-ver model. Model-version-id = "
+ + modVerId);
+ }
+
+ if (tmpNodeType != null && !tmpNodeType.equals("")) {
+ if (startNodeType.equals("")) {
+ startNodeType = tmpNodeType;
+ } else if (!startNodeType.equals(tmpNodeType)) {
+ String msg = "Conflict between startNode types for models involved: ["
+ + startNodeType + "], [" + tmpNodeType + "]";
+ throw new AAIException("AAI_6125", msg);
+ }
+ distinctModelVersHash.put(modVerId, modVerVtx);
+ }
+ }
+ }
+
+ // System.out.println("\nDEBUG -- Here's a dump of the DISTINCT model-ver hash: " +
+ // distinctModelVersHash.toString() );
+
+ // ------------------------------------------------------------------------------------------------------
+ // Get the "valid-next-step" hash for each distinct model-ver
+ // While we're at it, get a mapping of model-invariant-id|model-version to model-version-id
+ // for
+ // the model-vers being used
+ // ------------------------------------------------------------------------------------------------------
+ Map<String, Multimap<String, String>> validNextStepHash = new HashMap<>();
+ // validNextStepHash: key = modelVerId, value = nextStepMap
+ Set<String> keySet = distinctModelVersHash.keySet();
+ Iterator<String> modelVerIterator = keySet.iterator();
+ while (modelVerIterator.hasNext()) {
+ String modVerKey = modelVerIterator.next();
+ if (!skipModelVerIdList.contains(modVerKey)) {
+ Vertex modelVerVtx = distinctModelVersHash.get(modVerKey);
+ Multimap<String, String> tmpTopoMap =
+ genTopoMap4ModelVer(transId, fromAppId, modelVerVtx, modVerKey);
+ validNextStepHash.put(modVerKey, tmpTopoMap);
+ }
+ }
+
+ // -------------------------------------------------------------------------------------------------
+ // Figure out what the "start-node" for each instance will be (plus the info we will use to
+ // represent that in our topology)
+ // -------------------------------------------------------------------------------------------------
+ List<String> failedPersonaCheckVids = new ArrayList<>();
+ Map<String, String> firstStepInfoHash = new HashMap<>();
+ // For firstStepInfoHash: key = startNodeVtxId, val=topNodeType plus personaData if
+ // applicable
+ // ie. the value is what we'd use as the "first-step" for this model.
+ if (!nodeTypeSupportsPersona(startNodeType)) {
+ // This node type doesn't have persona info, so we just use startNodeType for the
+ // first-step-info
+ snKeySet = startNode2ModelVerHash.keySet();
+ startNodeIterator = snKeySet.iterator();
+ while (startNodeIterator.hasNext()) {
+ String vtxKey = startNodeIterator.next();
+ firstStepInfoHash.put(vtxKey, startNodeType);
+ }
+ } else {
+ // Need to check that this node's persona data is good and if it is - use it for the
+ // first step info
+ snKeySet = startNode2ModelVerHash.keySet();
+ startNodeIterator = snKeySet.iterator();
+ while (startNodeIterator.hasNext()) {
+ String vtxKey = startNodeIterator.next();
+ Iterator<Vertex> vtxIterator =
+ this.engine.asAdmin().getReadOnlyTraversalSource().V(vtxKey);
+ Vertex tmpVtx = vtxIterator.next();
+ String thisVtxModelVerId = startNode2ModelVerHash.get(vtxKey);
+ if (skipModelVerIdList.contains(thisVtxModelVerId)) {
+ // Skip this vertex because it uses a model-ver that is bad
+ continue;
+ }
+ Vertex modelVerVtx = distinctModelVersHash.get(thisVtxModelVerId);
+ Vertex modelVtx = getModelGivenModelVer(modelVerVtx, "");
+ String modInvId = modelVtx.<String>property("model-invariant-id").orElse(null);
+ String personaModInvId =
+ tmpVtx.<String>property(addDBAliasedSuffix("model-invariant-id")).orElse(null);
+ String personaModVerId =
+ tmpVtx.<String>property(addDBAliasedSuffix("model-version-id")).orElse(null);
+ if (modInvId.equals(personaModInvId) && thisVtxModelVerId.equals(personaModVerId)) {
+ String tmpPersonaInfoStr =
+ startNodeType + "," + personaModInvId + "," + personaModVerId;
+ firstStepInfoHash.put(vtxKey, tmpPersonaInfoStr);
+ } else {
+ // we won't use this start node below when we collect data because it should
+ // have
+ // had persona data that matched it's model - but it did not.
+ failedPersonaCheckVids.add(vtxKey);
+ }
+ }
+ }
+
+ // System.out.println("\nDEBUG -- Here's a dump of the firstStepInfoHash hash: " +
+ // firstStepInfoHash.toString() );
+
+ // ------------------------------------------------------------------------------------------------
+ // Loop through each start-node, collect it's data using collectInstanceData() and put the
+ // resultSet onto the resultArray.
+ // ------------------------------------------------------------------------------------------------
+
+ // Make sure they're not bringing back too much data
+ String maxString = AAIConfig.get("aai.model.query.resultset.maxcount");
+ if (maxString != null && !maxString.equals("")) {
+ int maxSets = 0;
+ try {
+ maxSets = Integer.parseInt(maxString);
+ } catch (Exception nfe) {
+ // Don't worry, we will leave the max as zero - which tells us not to use it.
+ }
+
+ if (maxSets > 0 && (startNode2ModelVerHash.size() > maxSets)) {
+ String msg = " Query returns " + startNode2ModelVerHash.size()
+ + " resultSets. Max allowed is: " + maxSets;
+ throw new AAIException("AAI_6141", msg);
+ }
+ }
+
+ snKeySet = startNode2ModelVerHash.keySet();
+ startNodeIterator = snKeySet.iterator();
+ while (startNodeIterator.hasNext()) {
+ String topNodeVtxId = startNodeIterator.next();
+ if (failedPersonaCheckVids.contains(topNodeVtxId)
+ || skipStartVertVerIdList.contains(topNodeVtxId)) {
+ // Skip this vertex because it failed it's persona-data check above
+ // Skip this vertex because it uses a model-ver that is bad
+ continue;
+ }
+
+ Iterator<Vertex> vtxIterator =
+ this.engine.asAdmin().getReadOnlyTraversalSource().V(topNodeVtxId);
+ Vertex tmpStartVtx = vtxIterator.next();
+ String elementLocationTrail = firstStepInfoHash.get(topNodeVtxId);
+ String modelVerId = startNode2ModelVerHash.get(topNodeVtxId);
+ Multimap<String, String> validNextStepMap = validNextStepHash.get(modelVerId);
+
+ List<String> vidsTraversed = new ArrayList<>();
+ Map<String, String> emptyDelKeyHash = new HashMap<>();
+ Map<String, String> emptyNQElementHash = new HashMap<>(); // Only applies to Named
+ // Queries
+ ResultSet tmpResSet = collectInstanceData(transId, fromAppId, tmpStartVtx,
+ elementLocationTrail, validNextStepMap, vidsTraversed, 0, emptyDelKeyHash,
+ emptyNQElementHash, apiVer);
+
+ resultArray.add(tmpResSet);
+ }
+
+ return resultArray;
+
+ }// queryByModel_Timed()
+
+ /**
+ * Run delete by model-ver.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param modelVersionId the model version id -- unique id for a model-ver node
+ * @param topNodeTypeVal the top node type val -- required if no model-version-id is passed
+ * @param startNodeFilterHash the start node filter hash -- used to locate the first node of
+ * instance data
+ * @param apiVer the api ver
+ * @param resVersion the res version -- resourceVersion of the top/first widget in the model
+ * instance
+ * @return HashMap (keys = vertexIds that were deleted)
+ * @throws AAIException the AAI exception
+ */
+ public Map<String, String> runDeleteByModel(String transId, String fromAppId,
+ String modelVersionId, String topNodeTypeVal, Map<String, Object> startNodeFilterHash,
+ String apiVer, String resVersion) throws AAIException {
+
+ Map<String, String> retHash = new HashMap<>();
+
+ // Locate the Model-ver node to be used
+ Vertex modelVerVtx = null;
+ if (modelVersionId != null && !modelVersionId.equals("")) {
+ modelVerVtx = getNodeUsingUniqueId(transId, fromAppId, "model-ver", "model-version-id",
+ modelVersionId);
+ } else {
+ // if they didn't pass the modelVersionId, then we need to use the startNode to figure
+ // it out
+ // Locate the starting node based on the start node params
+ if (topNodeTypeVal == null || topNodeTypeVal.equals("")) {
+ throw new AAIException("AAI_6118",
+ "If no model info is passed, then topNodeType is required. ");
+ }
+
+ Optional<Vertex> result =
+ dbMethHelper.searchVertexByIdentityMap(topNodeTypeVal, startNodeFilterHash);
+ if (!result.isPresent()) {
+ throw new AAIException("AAI_6114",
+ "No Node of type " + topNodeTypeVal + " found for properties");
+ }
+ Vertex startVtx = result.get();
+
+ String startVertModVerId =
+ startVtx.<String>property(addDBAliasedSuffix("model-version-id")).orElse(null);
+ modelVerVtx = getNodeUsingUniqueId(transId, fromAppId, "model-ver", "model-version-id",
+ startVertModVerId);
+ }
+
+ if (modelVerVtx == null) {
+ throw new AAIException("AAI_6114",
+ "Could not determine the model-ver for the given input parameters. ");
+ }
+
+ String topNType = "unknown";
+ String modelType = getModelTypeFromModelVer(modelVerVtx, "");
+
+ if (modelType.equals("widget")) {
+ // If they want to delete using a widget-level model.. That is just a delete of the one
+ // instance of one of our nodes.
+ String widgModNodeType = modelVerVtx.<String>property("model-name").orElse(null);
+ if ((widgModNodeType == null) || widgModNodeType.equals("")) {
+ String msg =
+ "Could not find model-name for the widget model [" + modelVersionId + "].";
+ throw new AAIException("AAI_6132", msg);
+ }
+ Optional<Vertex> result =
+ dbMethHelper.locateUniqueVertex(widgModNodeType, startNodeFilterHash);
+ if (!result.isPresent()) {
+ throw new AAIException("AAI_6114",
+ "No Node of type " + topNType + " found for properties");
+ }
+ Vertex widgetVtx = result.get();
+ String widgId = widgetVtx.id().toString();
+ serializer.delete(widgetVtx, resVersion, true);
+ retHash.put(widgId, widgModNodeType);
+ return retHash;
+ }
+
+ // ---------------------------------------------------------------------------------
+ // If we got to here, this must be either a service or resource model.
+ // So, we'll need to get a Hash of which parts of the model to delete.
+ // NOTE- deleteByModel is deleting data based on one specific version of a model.
+ // ---------------------------------------------------------------------------------
+ String chkFirstNodePersonaModInvId = "";
+ String chkFirstNodePersonaModVerId = "";
+ String personaData = "";
+ Vertex firstModElementVertex = getTopElementForSvcOrResModelVer(modelVerVtx, "");
+ topNType = getModElementWidgetType(firstModElementVertex, "");
+ if ((topNType == null) || topNType.equals("")) {
+ String msg = "Could not determine the top-node nodeType for model-version-id: ["
+ + modelVersionId + "]";
+ throw new AAIException("AAI_6132", msg);
+ }
+ if (nodeTypeSupportsPersona(topNType)) {
+ Vertex modelVtx = getModelGivenModelVer(modelVerVtx, "");
+ chkFirstNodePersonaModInvId =
+ modelVtx.<String>property("model-invariant-id").orElse(null);
+ chkFirstNodePersonaModVerId =
+ modelVerVtx.<String>property("model-version-id").orElse(null);
+ personaData = "," + chkFirstNodePersonaModInvId + "," + chkFirstNodePersonaModVerId;
+ }
+
+ // Get the deleteKeyHash for this model
+ String incomingTrail = "";
+ Map<String, String> currentHash = new HashMap<>();
+ Map<String, Vertex> modConHash = new HashMap<>();
+ ArrayList<String> vidsTraversed = new ArrayList<>();
+ Map<String, String> delKeyHash = collectDeleteKeyHash(transId, fromAppId,
+ firstModElementVertex, incomingTrail, currentHash, vidsTraversed, 0, modConHash,
+ chkFirstNodePersonaModInvId, chkFirstNodePersonaModVerId);
+
+ System.out.println(
+ "\n ----DEBUG -----: Delete Hash for model: [" + modelVersionId + "] looks like: ");
+ for (Map.Entry<String, String> entry : delKeyHash.entrySet()) {
+ System.out.println("key = [" + entry.getKey() + "], val = [" + entry.getValue() + "]");
+ }
+ System.out.println("\n -----");
+ // Locate the starting node that we'll use to start looking for instance data
+ Optional<Vertex> result =
+ dbMethHelper.searchVertexByIdentityMap(topNType, startNodeFilterHash);
+ if (!result.isPresent()) {
+ throw new AAIException("AAI_6114",
+ "No Node of type " + topNType + " found for properties");
+ }
+ Vertex startVtx = result.get();
+ if (!chkFirstNodePersonaModInvId.equals("")) {
+ // NOTE: For Service or Resource models, if this is a nodeType that supports persona's,
+ // then
+ // we need to make sure that the start node matches the persona values.
+ String startVertPersonaModInvId =
+ startVtx.<String>property(addDBAliasedSuffix("model-invariant-id")).orElse(null);
+ String startVertPersonaModVerId =
+ startVtx.<String>property(addDBAliasedSuffix("model-version-id")).orElse(null);
+ if (!chkFirstNodePersonaModInvId.equals(startVertPersonaModInvId)
+ || !chkFirstNodePersonaModVerId.equals(startVertPersonaModVerId)) {
+ String msg = "Persona-Model data mismatch for start node (" + topNType + "), "
+ + startNodeFilterHash;
+ throw new AAIException("AAI_6114", msg);
+ }
+ }
+ String topVid = startVtx.id().toString();
+
+ // Read the model-ver into a Map for processing
+ Multimap<String, String> validNextStepMap =
+ genTopoMap4ModelVer(transId, fromAppId, modelVerVtx, modelVersionId);
+
+ // Collect the data
+ String elementLocationTrail = topNType + personaData;
+ vidsTraversed = new ArrayList<>();
+ Map<String, String> emptyHash = new HashMap<>();
+
+ // Pass emptyHash for the NQElement hash since that parameter only applies to Named Queries
+ ResultSet retResSet =
+ collectInstanceData(transId, fromAppId, startVtx, elementLocationTrail,
+ validNextStepMap, vidsTraversed, 0, delKeyHash, emptyHash, apiVer);
+
+ // Note: the new ResultSet will have each element tagged with the del flag so we'll know if
+ // it
+ // should be deleted or not - so loop through the results in a try-block since some things
+ // will get auto-deleted by parents before we get to them --- and try to remove each one.
+ String vidToResCheck = topVid;
+
+ retHash = deleteAsNeededFromResultSet(transId, fromAppId, retResSet, vidToResCheck, apiVer,
+ resVersion, emptyHash);
+ // String msgStr = "processed deletes for these vids: (\n"+ retHash.keySet().toString() +
+ // ").";
+
+ return retHash;
+
+ }// End of runDeleteByModel()
+
+ /**
+ * Delete as needed from result set.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param resSet the res set
+ * @param vidToResCheck -- this vertex will need to have its resource-version checked
+ * @param apiVer the api ver
+ * @param resVersion the res version
+ * @param hashSoFar the hash so far -- hash of what's been deleted so far
+ * @return String
+ * @throws AAIException the AAI exception
+ */
+ public Map<String, String> deleteAsNeededFromResultSet(String transId, String fromAppId,
+ ResultSet resSet, String vidToResCheck, String apiVer, String resVersion,
+ Map<String, String> hashSoFar) throws AAIException {
+ Map<String, String> retHash = new HashMap<>();
+ retHash.putAll(hashSoFar);
+ Boolean deleteIt = false;
+
+ if (resSet.getVert() == null) {
+ return retHash;
+ }
+
+ Vertex thisVtx = resSet.getVert();
+ String thisGuyId = "";
+ String thisNT = "";
+ String thisGuyStr = "";
+
+ Boolean gotVtxOK = false;
+ try {
+ if (thisVtx != null) {
+ thisGuyId = thisVtx.id().toString();
+ thisNT = thisVtx.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ thisGuyStr = thisGuyId + "[" + thisNT + " found at:"
+ + resSet.getLocationInModelSubGraph() + "]";
+
+ // NOTE -- will try to set the NodeType to itself to see if the node has been
+ // deleted already in
+ // this transaction. It lets you get properties from nodes being deleted where the
+ // delete hasn't been committed yet. This check used to be accomplished with a call
+ // to
+ // "vtx.isRemoved()" but that was a Titan-only feature and is not available anymore
+ // since
+ // we no longer use Titan vertices.
+ // If we don't do this check, we get errors later when we try to delete the node.
+ thisVtx.property(AAIProperties.NODE_TYPE, thisNT);
+ gotVtxOK = true;
+ }
+ } catch (Exception ex) {
+ // Sometimes things have already been deleted by the time we get to them - just log it.
+ AAIException aaiException =
+ new AAIException("AAI_6154", thisGuyStr + ". msg = " + ex.getMessage());
+ ErrorLogHelper.logException(aaiException);
+
+ }
+
+ if (!gotVtxOK) {
+ // The vertex must have already been removed. Just return.
+ // Note - We need to catch this because the DB sometimes can still have the vtx
+ // and be able to get its ID but it is flagged internally as removed already.
+ return retHash;
+ } else {
+ if (resSet.getNewDataDelFlag() != null && resSet.getNewDataDelFlag().equals("T")) {
+ logger.debug(">> will try to delete this one >> " + thisGuyStr);
+
+ try {
+ Boolean requireResourceVersion = false;
+ if (thisGuyId.equals(vidToResCheck)) {
+ // This is the one vertex that we want to check the resourceId before
+ // deleting
+ requireResourceVersion = true;
+ }
+ this.serializer.delete(thisVtx, resVersion, requireResourceVersion);
+ } catch (AAIException ae) {
+ String errorCode = ae.getErrorObject().getErrorCode();
+ if (errorCode.equals("6130") || errorCode.equals("6131")) {
+ // They didn't pass the correct resource-version for the top node.
+ throw ae;
+ } else {
+ ErrorLogHelper.logException(ae);
+ String errText = ae.getErrorObject().getErrorText();
+ String errDetail = ae.getMessage();
+ logger.debug("Exception when deleting " + thisGuyStr + ". ErrorCode = "
+ + errorCode + ", errorText = " + errText + ", details = " + errDetail);
+ }
+ } catch (Exception e) {
+ // We'd expect to get a "node not found" here sometimes depending on the order
+ // that
+ // the model has us finding / deleting nodes.
+ // Ignore the exception - but log it so we can see what happened.
+ AAIException aaiException =
+ new AAIException("AAI_6154", thisGuyStr + ". msg = " + e.getMessage());
+ ErrorLogHelper.logException(aaiException);
+
+ }
+
+ // We can't depend on a thrown exception to tell us if a node was deleted since it
+ // may
+ // have been auto=deleted before this removeAaiNode() call.
+ // --- Not sure if we would want to check anything here -- because the
+ // graph.commit() is done outside of this call.
+
+ deleteIt = true;
+ } else {
+ // --- DEBUG ----
+ System.out.println(">>>>>>> NOT DELETING THIS ONE >>>> " + thisGuyStr);
+ List<String> retArr = dbMethHelper.getVertexProperties(thisVtx);
+ for (String info : retArr) {
+ System.out.println(info);
+ }
+ // --- DEBUG ----
+ }
+ }
+
+ // Now call this routine for the sub-resultSets
+ List<ResultSet> subResultSetList = resSet.getSubResultSet();
+ Iterator<ResultSet> subResSetIter = subResultSetList.iterator();
+ while (subResSetIter.hasNext()) {
+ ResultSet tmpSubResSet = subResSetIter.next();
+ retHash = deleteAsNeededFromResultSet(transId, fromAppId, tmpSubResSet, vidToResCheck,
+ apiVer, resVersion, retHash);
+ }
+
+ if (deleteIt) {
+ retHash.put(thisGuyId, thisGuyStr);
+ }
+
+ return retHash;
+
+ }// deleteAsNeededFromResultSet()
+
+ /**
+ * Query by named query (old version).
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param namedQueryUuid the named query uuid
+ * @param startNodeFilterArrayOfHashes the start node filter array of hashes --used to locate
+ * the first nodes of instance data
+ * @param apiVer the api ver
+ * @return resultSet
+ * @throws AAIException the AAI exception
+ */
+ public List<ResultSet> queryByNamedQuery(String transId, String fromAppId,
+ String namedQueryUuid, List<Map<String, Object>> startNodeFilterArrayOfHashes,
+ String apiVer) throws AAIException {
+
+ String dummyCutPoint = null;
+ Map<String, Object> dummySecondaryFilterHash = null;
+
+ return queryByNamedQuery(transId, fromAppId, namedQueryUuid, startNodeFilterArrayOfHashes,
+ apiVer, dummyCutPoint, dummySecondaryFilterHash);
+ }
+
+ /**
+ * Query by named query.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param namedQueryUuid the named query uuid
+ * @param startNodeFilterArrayOfHashes the start node filter array of hashes --used to locate
+ * the first nodes of instance data
+ * @param apiVer the api ver
+ * @param secondaryFilterCutPoint nodeType where we will prune if secondary filter is not met
+ * @param secondaryFilterHash secondary filter params
+ * @return resultSet
+ * @throws AAIException the AAI exception
+ */
+ public List<ResultSet> queryByNamedQuery(String transId, String fromAppId,
+ String namedQueryUuid, List<Map<String, Object>> startNodeFilterArrayOfHashes,
+ String apiVer, String secondaryFilterCutPoint, Map<String, Object> secondaryFilterHash)
+ throws AAIException {
+
+ final String transId_f = transId;
+ final String fromAppId_f = fromAppId;
+ final String namedQueryUuid_f = namedQueryUuid;
+ final List<Map<String, Object>> startNodeFilterArrayOfHashes_f =
+ startNodeFilterArrayOfHashes;
+ final String apiVer_f = apiVer;
+ final String secondaryFilterCutPoint_f = secondaryFilterCutPoint;
+ final Map<String, Object> secondaryFilterHash_f = secondaryFilterHash;
+
+ // Find out what our time-limit should be
+ int timeLimitSec = 0;
+ String timeLimitString = AAIConfig.get("aai.model.query.timeout.sec");
+ if (timeLimitString != null && !timeLimitString.equals("")) {
+ try {
+ timeLimitSec = Integer.parseInt(timeLimitString);
+ } catch (Exception nfe) {
+ // Don't worry, we will leave the limit as zero - which tells us not to use it.
+ }
+ }
+
+ if (timeLimitSec <= 0) {
+ // We will NOT be using a timer
+ return queryByNamedQuery_Timed(transId, fromAppId, namedQueryUuid,
+ startNodeFilterArrayOfHashes, apiVer, secondaryFilterCutPoint_f,
+ secondaryFilterHash_f);
+ }
+
+ List<ResultSet> resultList = new ArrayList<>();
+ TimeLimiter limiter = new SimpleTimeLimiter();
+ try {
+ resultList = limiter.callWithTimeout(new AaiCallable<List<ResultSet>>() {
+ public List<ResultSet> process() throws AAIException {
+ return queryByNamedQuery_Timed(transId_f, fromAppId_f, namedQueryUuid_f,
+ startNodeFilterArrayOfHashes_f, apiVer_f, secondaryFilterCutPoint_f,
+ secondaryFilterHash_f);
+ }
+ }, timeLimitSec, TimeUnit.SECONDS, true);
+
+ } catch (AAIException ae) {
+ // Re-throw AAIException so we get can tell what happened internally
+ throw ae;
+ } catch (UncheckedTimeoutException ute) {
+ throw new AAIException("AAI_6140",
+ "Query Processing Limit exceeded. (limit = " + timeLimitSec + " seconds)");
+ } catch (Exception e) {
+ throw new AAIException("AAI_6128",
+ "Unexpected exception in queryByNamedQuery(): " + e.getMessage());
+ }
+
+ return resultList;
+ }
+
+ /**
+ * Query by named query timed.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param namedQueryUuid the named query uuid
+ * @param startNodeFilterArrayOfHashes the start node filter array of hashes --used to locate
+ * the first nodes of instance data
+ * @param apiVer the api ver
+ * @param secondaryFilterCutPoint the nodeType where we will parse for the secondary Filter
+ * @param secondaryFilterHash the secondary filter hash
+ * @return resultSet
+ * @throws AAIException the AAI exception
+ */
+ public List<ResultSet> queryByNamedQuery_Timed(String transId, String fromAppId,
+ String namedQueryUuid, List<Map<String, Object>> startNodeFilterArrayOfHashes,
+ String apiVer, String secondaryFilterCutPoint, Map<String, Object> secondaryFilterHash)
+ throws AAIException {
+
+ // Locate the Query to be used
+ Vertex queryVtx = getNodeUsingUniqueId(transId, fromAppId, "named-query",
+ "named-query-uuid", namedQueryUuid);
+
+ // Get the first/top named-query-element used by this query
+ Iterator<Vertex> vertI =
+ this.traverseIncidentEdges(EdgeType.TREE, queryVtx, "named-query-element");
+ Vertex firstNqElementVert = null;
+ int count = 0;
+ String topNType = "";
+ while (vertI != null && vertI.hasNext()) {
+ firstNqElementVert = vertI.next();
+ count++;
+ topNType = getNqElementWidgetType(transId, fromAppId, firstNqElementVert, "");
+ }
+
+ if (count < 1) {
+ // A named query must start with a single top element
+ throw new AAIException("AAI_6133",
+ "No top-node defined for named-query-uuid = [" + namedQueryUuid + "]");
+ } else if (count > 1) {
+ // A named query should start with a single top element
+ throw new AAIException("AAI_6133",
+ "More than one top-node defined for named-query-uuid = [" + namedQueryUuid + "]");
+ }
+ if ((topNType == null) || topNType.equals("")) {
+ String msg = "Could not determine the top-node nodeType for Named Query: ["
+ + namedQueryUuid + "]";
+ throw new AAIException("AAI_6133", msg);
+ }
+
+ // Read the topology into a hash for processing
+ Multimap<String, String> validNextStepMap =
+ genTopoMap4NamedQ(transId, fromAppId, queryVtx, namedQueryUuid);
+
+ List<Vertex> startVertList = new ArrayList<>();
+ if (startNodeFilterArrayOfHashes.size() == 1) {
+ // If there is only one set of startFilter info given, then allow it to possibly not be
+ // defining just one start node.
+ Map<String, Object> tmpHash = startNodeFilterArrayOfHashes.get(0);
+ Set<String> propKeySet = tmpHash.keySet();
+ Iterator<String> propIter = propKeySet.iterator();
+ Introspector obj = loader.introspectorFromName(topNType);
+ Set<String> keys = obj.getKeys();
+ boolean foundIndexedField = false;
+ int propertiesSet = 0;
+ while (propIter.hasNext()) {
+ String oldVtxKey = propIter.next();
+ String newKey = oldVtxKey;
+ String[] parts = oldVtxKey.split("\\.");
+ if (parts.length == 2) {
+ newKey = parts[1];
+ }
+ Object obVal = tmpHash.get(oldVtxKey);
+ if (obj.hasProperty(newKey)) {
+ if (keys.contains(newKey)) {
+ foundIndexedField = true;
+ }
+ obj.setValue(newKey, obVal);
+ propertiesSet++;
+ }
+ }
+ // we found all the properties in the startNodeType
+ if (propertiesSet == propKeySet.size()) {
+ if (foundIndexedField) {
+ QueryBuilder builder = this.engine.getQueryBuilder().exactMatchQuery(obj);
+ startVertList = builder.toList();
+ } else {
+ // force a filter from aai-node-type
+ QueryBuilder builder = this.engine.getQueryBuilder().createContainerQuery(obj)
+ .exactMatchQuery(obj);
+ startVertList = builder.toList();
+ }
+ } else {
+ Optional<Vertex> tmpVtx = dbMethHelper.searchVertexByIdentityMap(topNType,
+ startNodeFilterArrayOfHashes.get(0));
+ // Only found one, so just use it.
+ if (tmpVtx.isPresent()) {
+ startVertList.add(tmpVtx.get());
+ }
+ }
+ } else {
+ // Since they give an array of startNodeFilterHash info, we expect each one
+ // to just point to one node.
+ for (int i = 0; i < startNodeFilterArrayOfHashes.size(); i++) {
+ // Locate the starting node for each set of data
+ Optional<Vertex> tmpVtx = dbMethHelper.searchVertexByIdentityMap(topNType,
+ startNodeFilterArrayOfHashes.get(i));
+ if (tmpVtx.isPresent()) {
+ startVertList.add(tmpVtx.get());
+ }
+ }
+ }
+
+ if (startVertList.isEmpty()) {
+ throw new AAIException("AAI_6114",
+ "No Node of type " + topNType + " found for properties");
+ }
+ // Make sure they're not bringing back too much data
+ String maxString = AAIConfig.get("aai.model.query.resultset.maxcount");
+ if (maxString != null && !maxString.equals("")) {
+ int maxSets = Integer.parseInt(maxString);
+ if (startVertList.size() > maxSets) {
+ String msg = " Query returns " + startVertList.size()
+ + " resultSets. Max allowed is: " + maxSets;
+ throw new AAIException("AAI_6141", msg);
+ }
+ }
+
+ // Loop through each start node and get its data
+ List<ResultSet> resSetList = new ArrayList<>();
+ for (int i = 0; i < startVertList.size(); i++) {
+ Vertex startVtx = startVertList.get(i);
+ // Collect the data
+ String elementLocationTrail = topNType;
+ ArrayList<String> vidsTraversed = new ArrayList<>();
+ Map<String, String> emptyDelKeyHash = new HashMap<>(); // Does not apply to Named
+ // Queries
+
+ // Get the mapping of namedQuery elements to our widget topology for this namedQuery
+ String incomingTrail = "";
+ Map<String, String> currentHash = new HashMap<>();
+
+ Map<String, String> namedQueryElementHash = collectNQElementHash(transId, fromAppId,
+ firstNqElementVert, incomingTrail, currentHash, vidsTraversed, 0);
+
+ vidsTraversed = new ArrayList<>();
+ ResultSet tmpResSet = collectInstanceData(transId, fromAppId, startVtx,
+ elementLocationTrail, validNextStepMap, vidsTraversed, 0, emptyDelKeyHash,
+ namedQueryElementHash, apiVer);
+ resSetList.add(tmpResSet);
+ }
+
+ // If a secondary filter was defined, we will prune the collected instance data result
+ // set(s) based on it.
+ List<ResultSet> prunedResSetList = new ArrayList<>();
+ if (resSetList != null && !resSetList.isEmpty()) {
+ for (int i = 0; i < resSetList.size(); i++) {
+ if (secondaryFilterCutPoint == null || secondaryFilterCutPoint.equals("")
+ || secondaryFilterHash == null) {
+ // They didn't want to do any pruning, so just use the results we already had
+ prunedResSetList.add(resSetList.get(i));
+ } else {
+ ResultSet tmpResSet = pruneResultSet(resSetList.get(i), secondaryFilterCutPoint,
+ secondaryFilterHash);
+ if (tmpResSet != null) {
+ prunedResSetList.add(tmpResSet);
+ }
+ }
+ }
+ }
+
+ // Since a NamedQuery can mark some nodes as "do-not-display", we need to collapse our
+ // resultSet so
+ // does not display those nodes.
+ List<ResultSet> collapsedResSetList = new ArrayList<>();
+ if (prunedResSetList != null && !prunedResSetList.isEmpty()) {
+ for (int i = 0; i < prunedResSetList.size(); i++) {
+ // Note - a single resultSet could be collapsed into many smaller ones if they
+ // marked all the "top" node-elements as do-not-output. Ie. the query may
+ // have had a top-node of "generic-vnf" which joins down to different l-interfaces.
+ // If they only want to see the l-interfaces, then a single result set
+ // would be "collapsed" into many separate resultSets - each of which is
+ // just a single l-interface.
+ List<ResultSet> tmpResSetList = collapseForDoNotOutput(prunedResSetList.get(i));
+ if (tmpResSetList != null && !tmpResSetList.isEmpty()) {
+ for (int x = 0; x < tmpResSetList.size(); x++) {
+ // showResultSet( tmpResSetList.get(x), 0 ); //DEBUG-- this was just for
+ // testing
+ collapsedResSetList.add(tmpResSetList.get(x));
+ }
+ }
+ }
+ }
+
+ return collapsedResSetList;
+
+ }// End of queryByNamedQuery()
+
+ /**
+ * Prune a result set as per a secondary filter.
+ *
+ * @param resSetVal the res set val
+ * @param cutPointType the nodeType where the trim will happen
+ * @param secFilterHash hash of properties and values to use as the secondary filter
+ * @return pruned result set
+ * @throws AAIException the AAI exception
+ */
+ public ResultSet pruneResultSet(ResultSet resSetVal, String cutPointType,
+ Map<String, Object> secFilterHash) throws AAIException {
+
+ // Given a ResultSet and some secondary filter info, do pruning as needed
+ ResultSet pResSet = new ResultSet();
+
+ // For this ResultSet, we will see if we are on a node of the type that is our cutPoint;
+ // then only keep it if we peek "below" and see a match for our filter.
+
+ String nt = resSetVal.getVert().<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ if (nt != null && nt.equals(cutPointType)) {
+ // We are on the type of node that may need to be "pruned" along with it's sub-results
+ if (!satisfiesFilters(resSetVal, secFilterHash)) {
+ // Return an empty result set since we are pruning at this level.
+ return pResSet;
+ }
+ }
+
+ // If we made it to here, we will not be pruning at this level, so we will
+ // be returning a copy of this resultSet that has it's subResults pruned (as needed).
+ pResSet.setVert(resSetVal.getVert());
+ pResSet.setDoNotOutputFlag(resSetVal.getDoNotOutputFlag());
+ pResSet.setExtraPropertyHash(resSetVal.getExtraPropertyHash());
+ pResSet.setLocationInModelSubGraph(resSetVal.getLocationInModelSubGraph());
+ pResSet.setNewDataDelFlag(resSetVal.getNewDataDelFlag());
+ pResSet.setPropertyLimitDesc(resSetVal.getPropertyLimitDesc());
+ pResSet.setPropertyOverRideHash(resSetVal.getPropertyOverRideHash());
+
+ if (!resSetVal.getSubResultSet().isEmpty()) {
+ ListIterator<ResultSet> listItr = resSetVal.getSubResultSet().listIterator();
+ List<ResultSet> newSubSetList = new ArrayList<>();
+ while (listItr.hasNext()) {
+ ResultSet tmpSubResSet =
+ pruneResultSet(listItr.next(), cutPointType, secFilterHash);
+ if (tmpSubResSet.getVert() != null) {
+ // This one wasn't pruned - so keep it.
+ newSubSetList.add(tmpSubResSet);
+ }
+ }
+ pResSet.setSubResultSet(newSubSetList);
+ }
+
+ return pResSet;
+
+ }// End pruneResultSet()
+
+ /**
+ * Satisfies hash of filters.
+ *
+ * @param resSet the res set
+ * @param filterHash the filter hash
+ * @return true, if successful
+ * @throws AAIException the AAI exception
+ */
+ public boolean satisfiesFilters(ResultSet resSet, Map<String, Object> filterHash)
+ throws AAIException {
+
+ if (filterHash.isEmpty()) {
+ // Nothing to look for, so no, we didn't find it.
+ return false;
+ }
+
+ Iterator<?> it = filterHash.entrySet().iterator();
+ while (it.hasNext()) {
+ Map.Entry<?, ?> filtEntry = (Map.Entry<?, ?>) it.next();
+ String propNodeTypeDotName = (filtEntry.getKey()).toString();
+ String fpv = (filtEntry.getValue()).toString();
+
+ int periodLoc = propNodeTypeDotName.indexOf('.');
+ if (periodLoc <= 0) {
+ String emsg = "Bad filter param key passed in: [" + propNodeTypeDotName
+ + "]. Expected format = [nodeName.paramName]\n";
+ throw new AAIException("AAI_6120", emsg);
+ } else {
+ String fnt = propNodeTypeDotName.substring(0, periodLoc);
+ String fpn = propNodeTypeDotName.substring(periodLoc + 1);
+ if (filterMetByThisSet(resSet, fnt, fpn, fpv)) {
+ // System.out.println(" DEBUG -- satisfied/matched filter: [" + fnt + "|" + fpn
+ // + "|" + fpv + "].");
+ } else {
+ // System.out.println(" DEBUG -- NOT satisfied/matched filter: [" + fnt + "|" +
+ // fpn + "|" + fpv + "].");
+ return false;
+ }
+ }
+ }
+
+ // Made it through all the filters -- it found what we were looking for.
+ return true;
+
+ }// end of satisfiesFilters()
+
+ /**
+ * Filter met by this set.
+ *
+ * @param resSet the res set
+ * @param filtNodeType the filt node type
+ * @param filtPropName the filt prop name
+ * @param filtPropVal the filt prop val
+ * @return true, if successful
+ */
+ public boolean filterMetByThisSet(ResultSet resSet, String filtNodeType, String filtPropName,
+ String filtPropVal) {
// Note - we are just looking for a positive match for one filter for this resultSet
- // NOTE: we're expecting the filter to have a format like this: "nodeType.parameterName:parameterValue"
-
- Vertex vert = resSet.getVert();
- if( vert == null ){
- return false;
- }
- else {
- String nt = resSet.getVert().<String>property(AAIProperties.NODE_TYPE).orElse(null);
- if( nt.equals( filtNodeType ) ){
- if( filtPropName.equals("vertex-id") ){
- // vertex-id can't be gotten the same way as other properties
- String thisVtxId = vert.id().toString();
- if( thisVtxId.equals(filtPropVal) ){
- return true;
- }
- }
- else {
- Object thisValObj = vert.property(filtPropName).orElse(null);
- if( thisValObj != null ){
- String thisVal = thisValObj.toString();
- if( thisVal.equals(filtPropVal) ){
- return true;
- }
- }
- }
- }
- }
-
- // Didn't find a match at the this level, so check the sets below it meet the criteria
- if( resSet.getSubResultSet() != null ){
- ListIterator<ResultSet> listItr = resSet.getSubResultSet().listIterator();
- while( listItr.hasNext() ){
- if( filterMetByThisSet(listItr.next(), filtNodeType, filtPropName, filtPropVal) ){
- return true;
- }
- }
- }
-
- return false;
-
- }// end of filterMetByThisSet()
-
-
-
- /**
- * Collapse for do not output.
- *
- * @param resSetVal the res set val
- * @return the array list
- * @throws AAIException the AAI exception
- */
- public List<ResultSet> collapseForDoNotOutput(ResultSet resSetVal )
- throws AAIException {
-
- // Given a ResultSet -- if it is tagged to NOT be output, then replace it with
- // it's sub-ResultSets if it has any.
- List<ResultSet> colResultSet = new ArrayList<>();
-
- if( resSetVal.getDoNotOutputFlag().equals("true") ){
- // This ResultSet isn't to be displayed, so replace it with it's sub-ResultSets
- List<ResultSet> subResList = resSetVal.getSubResultSet();
- for( int k = 0; k < subResList.size(); k++ ){
- List<ResultSet> newSubResList = collapseForDoNotOutput(subResList.get(k));
- colResultSet.addAll(newSubResList);
- }
- }
- else {
- // This set will be displayed
- colResultSet.add(resSetVal);
- }
-
- // For each result set now at this level, call this same routine to collapse their sub-resultSets
- for( int i = 0; i < colResultSet.size(); i++ ){
- List<ResultSet> newSubSet = new ArrayList<>();
- List<ResultSet> subResList = colResultSet.get(i).getSubResultSet();
- for( int n = 0; n < subResList.size(); n++ ){
- List<ResultSet> newSubResList = collapseForDoNotOutput(subResList.get(n));
- newSubSet.addAll(newSubResList);
- }
- // Replace the old subResultSet with the collapsed set
- colResultSet.get(i).setSubResultSet(newSubSet);
- }
-
- return colResultSet;
-
- }// End collapseForDoNotOutput()
-
-
-
- /**
- * Collect instance data.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param thisLevelElemVtx the element vtx at this level
- * @param thisVertsTrail the this verts trail
- * @param validNextStepMap the valid next step map -- hash of valid next steps (node types) for this model
- * @param vidsTraversed the vids traversed -- ArrayList of vertexId's that we traversed to get to this point
- * @param levelCounter the level counter
- * @param delKeyHash -- hashMap of which spots on our topology should be deleted during a modelDelete
- * @param namedQueryElementHash - hashMap which maps each spot in our widget topology to the NamedQueryElemment that it maps to
- * @param apiVer the api ver
- * @return resultSet
- * @throws AAIException the AAI exception
- */
- public ResultSet collectInstanceData(String transId, String fromAppId,
- Vertex thisLevelElemVtx,
- String thisVertsTrail,
- Multimap<String,String> validNextStepMap,
- List<String> vidsTraversed,
- int levelCounter,
- Map<String,String> delKeyHash, // only applies when collecting data using the default model for delete
- Map<String,String> namedQueryElementHash, // only applies to named-query data collecting
- String apiVer
- ) throws AAIException {
-
- levelCounter++;
-
- String thisElemVid = thisLevelElemVtx.id().toString();
-
- if( levelCounter > MAX_LEVELS ) {
- throw new AAIException("AAI_6125", "collectInstanceData() has looped across more levels than allowed: " + MAX_LEVELS + ". ");
- }
-
- ResultSet rs = new ResultSet();
- if( namedQueryElementHash.containsKey(thisVertsTrail) ){
- // We're collecting data for a named-query, so need to see if we need to do anything special
- String nqElUuid = namedQueryElementHash.get(thisVertsTrail);
- Vertex nqElementVtx = getNodeUsingUniqueId(transId, fromAppId, "named-query-element",
- "named-query-element-uuid", nqElUuid);
-
- String tmpDoNotShow = nqElementVtx.<String>property("do-not-output").orElse(null);
- if( tmpDoNotShow != null && tmpDoNotShow.equals("true") ){
- rs.setDoNotOutputFlag("true");
- }
-
- if( namedQueryConstraintSaysStop(transId, fromAppId, nqElementVtx, thisLevelElemVtx, apiVer) ){
- // There was a property constraint which says they do not want to collect this vertex or whatever
- // might be below it. Just return the empty rs here.
- return rs;
- }
-
- String propLimDesc = nqElementVtx.<String>property("property-limit-desc").orElse(null);
- if( (propLimDesc != null) && !propLimDesc.equals("") ){
- if (propLimDesc.equalsIgnoreCase("show-all")) {
- rs.setPropertyLimitDesc(PropertyLimitDesc.SHOW_ALL);
- } else if (propLimDesc.equalsIgnoreCase("show-none")) {
- rs.setPropertyLimitDesc(PropertyLimitDesc.SHOW_NONE);
- }else if (propLimDesc.equalsIgnoreCase("name-and-keys-only")) {
- rs.setPropertyLimitDesc(PropertyLimitDesc.SHOW_NAME_AND_KEYS_ONLY);
- }
- }
-
- // Look to see if we need to use an Override of the normal properties
- Map<String,Object> tmpPropertyOverRideHash = getNamedQueryPropOverRide(transId, fromAppId, nqElementVtx, thisLevelElemVtx, apiVer);
- //System.out.println(" DEBUG --- USING this propertyOverride data set on ResSet [" + tmpPropertyOverRideHash.toString() + "]");
- rs.setPropertyOverRideHash(tmpPropertyOverRideHash);
-
- // See if we need to look up any "unconnected" data that needs to be associated with this result set
- Map<String,Object> tmpExtraPropHash = getNamedQueryExtraDataLookup(transId, fromAppId, nqElementVtx, thisLevelElemVtx, apiVer);
- //System.out.println(" DEBUG --- ADDING this EXTRA Lookup data to the ResSet [" + tmpExtraPropHash.toString() + "]");
- rs.setExtraPropertyHash(tmpExtraPropHash);
- }
-
- rs.setVert(thisLevelElemVtx);
- rs.setLocationInModelSubGraph(thisVertsTrail);
- if( delKeyHash.containsKey(thisVertsTrail) && delKeyHash.get(thisVertsTrail).equals("T") ){
- rs.setNewDataDelFlag("T");
- }
- else {
- rs.setNewDataDelFlag("F");
- }
-
- // Use Gremlin-pipeline to just look for edges that go to a valid "next-steps"
- Collection <String> validNextStepColl = validNextStepMap.get(thisVertsTrail);
-
- // Because of how we process linkage-points, we may have duplicate node-types in our next-stepMap (for one step)
- // So, to keep from looking (and bringing back) the same data twice, we need to make sure our next-steps are unique
- Set<String> validNextStepHashSet = new HashSet<>();
- Iterator <String> ntcItr = validNextStepColl.iterator();
- while( ntcItr.hasNext() ){
- String targetStepStr = ntcItr.next();
- validNextStepHashSet.add(targetStepStr);
- }
-
- List<String> tmpVidsTraversedList = new ArrayList<>();
- tmpVidsTraversedList.addAll(vidsTraversed);
- tmpVidsTraversedList.add(thisElemVid);
-
- Iterator <String> ntItr = validNextStepHashSet.iterator();
- while( ntItr.hasNext() ){
- String targetStep = ntItr.next();
- // NOTE: NextSteps can either be just a nodeType, or can be a nodeType plus
- // model-invariant-id-local and model-version-id-local (the two persona properties)
- // if those need to be checked also.
- // When the persona stuff is part of the step, it is a comma separated string.
- // Ie. "nodeType,model-inv-id-local,model-version-id-local" (the two "persona" props)
- //
- String targetNodeType = "";
- String pmid = "";
- String pmv = "";
- Boolean stepIsJustNT = true;
- if( targetStep.contains(",") ){
- stepIsJustNT = false;
- String[] pieces = targetStep.split(",");
- if( pieces.length != 3 ){
- throw new AAIException("AAI_6128", "Unexpected format for nextStep in model processing = ["
- + targetStep + "]. ");
- }
- else {
- targetNodeType = pieces[0];
- pmid = pieces[1];
- pmv = pieces[2];
- }
- }
- else {
- // It's just the nodeType with no other info
- targetNodeType = targetStep;
- }
-
- GraphTraversal<Vertex, Vertex> modPipe = null;
- if( stepIsJustNT ){
- modPipe = this.engine.asAdmin().getReadOnlyTraversalSource().V(thisLevelElemVtx).both().has(AAIProperties.NODE_TYPE, targetNodeType);
- }
- else {
- modPipe = this.engine.asAdmin().getReadOnlyTraversalSource().V(thisLevelElemVtx).both().has(AAIProperties.NODE_TYPE, targetNodeType).has(addDBAliasedSuffix("model-invariant-id"),pmid).has(addDBAliasedSuffix("model-version-id"),pmv);
- }
-
- if( modPipe == null || !modPipe.hasNext() ){
- //System.out.println("DEBUG - didn't find any [" + targetStep + "] connected to this guy (which is ok)");
- }
- else {
- while( modPipe.hasNext() ){
- Vertex tmpVert = modPipe.next();
- String tmpVid = tmpVert.id().toString();
- String tmpTrail = thisVertsTrail + "|" + targetStep;
- if( !vidsTraversed.contains(tmpVid) ){
- // This is one we would like to use - so we'll include the result set we get for it
- ResultSet tmpResSet = collectInstanceData( transId, fromAppId,
- tmpVert, tmpTrail,
- validNextStepMap, tmpVidsTraversedList,
- levelCounter, delKeyHash, namedQueryElementHash, apiVer );
-
- rs.getSubResultSet().add(tmpResSet);
- }
- }
- }
- }
-
- return rs;
-
- } // End of collectInstanceData()
-
-
- /**
- * Gen topo map 4 model.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param modelVerVertex the model-ver vertex
- * @param modelVerId the model-version-id
- * @return MultiMap of valid next steps for each potential model-element
- * @throws AAIException the AAI exception
- */
- public Multimap<String, String> genTopoMap4ModelVer(String transId, String fromAppId,
- Vertex modelVerVertex, String modelVerId)
- throws AAIException {
-
- if( modelVerVertex == null ){
- throw new AAIException("AAI_6114", "null modelVerVertex passed to genTopoMap4ModelVer()");
- }
-
- Multimap<String, String> initialEmptyMap = ArrayListMultimap.create();
- List<String> vidsTraversed = new ArrayList<>();
- String modelType = getModelTypeFromModelVer( modelVerVertex, "" );
- if( modelType.equals("widget") ){
- // A widget model by itself does not have a topoplogy. That is - it has no "model-elements" which
- // define how it is connected to other things. All it has is a name which ties it to
- // an aai-node-type
- Iterator<Vertex> vertI= this.traverseIncidentEdges(EdgeType.TREE, modelVerVertex, "model-element");
- if( vertI != null && vertI.hasNext() ){
- throw new AAIException("AAI_6132", "Bad Model Definition: Widget Model has a startsWith edge to a model-element. "
- + " model-version-id = " + modelVerId);
- }
- else {
- return initialEmptyMap;
- }
- }
-
- String firstModelVerId = modelVerVertex.<String>property("model-version-id").orElse(null);
- String firstModelVersion = modelVerVertex.<String>property("model-version").orElse(null);
- if( firstModelVerId == null || firstModelVerId.equals("") || firstModelVersion == null || firstModelVersion.equals("") ){
- throw new AAIException("AAI_6132", "Bad Model Definition: Bad model-version-id or model-version. model-version-id = "
- + modelVerId);
- }
-
- Vertex firstElementVertex = getTopElementForSvcOrResModelVer( modelVerVertex, "" );
- Vertex firstEleModVerVtx = getModelVerThatElementRepresents( firstElementVertex, "" );
- String firstElemModelType = getModelTypeFromModelVer( firstEleModVerVtx, "" );
- if( ! firstElemModelType.equals("widget") ){
- throw new AAIException("AAI_6132", "Bad Model Definition: First element must correspond to a widget type model. Model UUID = "
- + modelVerId);
- }
-
- Vertex firstModVtx = getModelGivenModelVer( modelVerVertex, "" );
- String firstModelInvId = firstModVtx.<String>property("model-invariant-id").orElse(null);
- if( firstModelInvId == null || firstModelInvId.equals("") ){
- throw new AAIException("AAI_6132", "Bad Model Definition: Could not find model.model-invariant-id given model-ver.model-version-id = "
- + modelVerId);
- }
-
- return collectTopology4ModelVer( transId, fromAppId,
- firstElementVertex, "", initialEmptyMap, vidsTraversed, 0, null, firstModelInvId, firstModelVersion );
- } // End of genTopoMap4ModelVer()
-
-
- public List<String> makeSureItsAnArrayList( String listStringVal ){
- // We're sometimes getting a String back on db properties that should be ArrayList<String>
- // Seems to be how they're defined in OXM - whether they use a "xml-wrapper" or not
- // Need to translate them into ArrayLists sometimes...
-
- List<String> retArrList = new ArrayList<>();
- String listString = listStringVal;
- listString = listString.replace(" ", "");
- listString = listString.replace("\"", "");
- listString = listString.replace("[", "");
- listString = listString.replace("]", "");
- String [] pieces = listString.split(",");
- if(pieces.length > 0){
- retArrList.addAll(Arrays.asList(pieces));
- }
- return retArrList;
- }
-
-
- /**
- * Gets the mod constraint hash.
- *
- * @param modelElementVtx the model element vtx
- * @param currentHash -- the current ModelConstraint's that this routine will add to if it finds any.
- * @return HashMap of model-constraints that will be looked at for this model-element and what's "below" it.
- * @throws AAIException the AAI exception
- */
- public Map<String, Vertex> getModConstraintHash(Vertex modelElementVtx, Map<String, Vertex> currentHash )
- throws AAIException {
-
- // For a given model-element vertex, look to see if there are any "model-constraint" elements that is has
- // an OUT "uses" edge to. If it does, then get any "constrained-element-set" nodes that are pointed to
- // by the "model-constraint". That will be the replacement "constrained-element-set". The UUID of the
- // "constrained-element-set" that it is supposed to replace is found in the property:
- // model-constraint.constrained-element-set-uuid-to-replace
- //
- // For now, that is the only type of model-constraint allowed, so that is all we will look for.
- // Pass back any of these "constrained-element-set" nodes along with any that were passed in by
- // the "currentHash" parameter.
-
- if( modelElementVtx == null ){
- String msg = " null modelElementVtx passed to getModConstraintHash() ";
- throw new AAIException("AAI_6114", msg);
- }
-
- String modelType = modelElementVtx.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- if( modelType == null || (!modelType.equals("model-element")) ){
- String msg = " getModConstraintHash() called with wrong type model: [" + modelType + "]. ";
- throw new AAIException("AAI_6114", msg);
- }
-
- Map<String, Vertex> thisHash = new HashMap<>();
- if( currentHash != null ){
- thisHash.putAll(currentHash);
- }
-
- int count = 0;
- List<Vertex> modelConstraintArray = new ArrayList<>();
- Iterator<Vertex> vertI = this.traverseIncidentEdges(EdgeType.TREE, modelElementVtx, "model-constraint");
- while( vertI != null && vertI.hasNext() ){
- Vertex tmpVert = vertI.next();
- String connectToType = tmpVert.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- if( (connectToType != null) && connectToType.equals("model-constraint") ){
- // We need to find the constrained element set pointed to by this and add it to the Hash to return
- modelConstraintArray.add(tmpVert);
- count++;
- }
- }
-
- if( count > 0 ) {
- for( int i = 0; i < count; i++ ){
- Vertex vtxOfModelConstraint = modelConstraintArray.get(i);
- String uuidOfTheOneToBeReplaced = vtxOfModelConstraint.<String>property("constrained-element-set-uuid-2-replace").orElse(null);
- // We have the UUID of the constrained-element-set that will be superseded, now find the
- // constrained-element-set to use in its place
- Iterator<Vertex> mvertI = this.traverseIncidentEdges(EdgeType.TREE, vtxOfModelConstraint, "constrained-element-set");
- while( mvertI != null && mvertI.hasNext() ){
- // There better only be one...
- Vertex tmpVert = mvertI.next();
- String connectToType = tmpVert.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- if( (connectToType != null) && connectToType.equals("constrained-element-set") ){
- // This is the "constrained-element-set" that we want to use as the Replacement
- thisHash.put(uuidOfTheOneToBeReplaced, tmpVert );
- }
- }
- }
- return thisHash;
- }
- else {
- // Didn't find anything to add, so just return what they passed in.
- return currentHash;
- }
-
- } // End of getModConstraintHash()
-
-
- /**
- * Gets the top element vertex for service or resource model.
- *
- * @param modelVerVtx the model-ver vertex
- * @return first element pointed to by this model-ver
- * @throws AAIException the AAI exception
- */
- public Vertex getTopElementForSvcOrResModelVer(Vertex modelVerVtx, String trail )
- throws AAIException {
-
- // For a "resource" or "service" type model, return the "top" element in that model
- if( modelVerVtx == null ){
- String msg = " null modelVertex passed to getTopoElementForSvcOrResModelVer() at [" + trail + "]. ";
- throw new AAIException("AAI_6114", msg);
- }
-
- String modelVerId = modelVerVtx.<String>property("model-version-id").orElse(null);
- if( modelVerId == null ){
- String nt = modelVerVtx.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- if( nt != null && !nt.equals("model-ver") ){
- String msg = "Illegal model defined: model element pointing to nodeType: ["
- + nt + "], should be pointing to: [model-ver] at [" + trail + "]. ";
- throw new AAIException("AAI_6132", msg);
- }
- }
-
- Vertex firstElementVertex = null;
-
- Iterator<Vertex> vertI = this.traverseIncidentEdges(EdgeType.TREE, modelVerVtx, "model-element");
- int elCount = 0;
- while( vertI != null && vertI.hasNext() ){
- elCount++;
- firstElementVertex = vertI.next();
- }
-
- if( elCount > 1 ){
- String msg = "Illegal model defined: More than one first element defined for model-ver-id = " +
- modelVerId + " at [" + trail + "]. ";
- throw new AAIException("AAI_6132", msg);
- }
-
- if( firstElementVertex == null ){
- String msg = "Could not find first model element for model-ver-id = "
- + modelVerId + " at [" + trail + "]. ";
- throw new AAIException("AAI_6132", msg);
- }
-
- return firstElementVertex;
-
- } // End of getTopElementForSvcOrResModelVer()
-
-
-
- /**
- * Gets the named query prop over ride.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param namedQueryElementVertex the named query element vertex
- * @param instanceVertex the instance vertex
- * @param apiVer the api ver
- * @return HashMap of alternate properties to return for this element
- * @throws AAIException the AAI exception
- */
- public Map<String,Object> getNamedQueryPropOverRide(String transId, String fromAppId,
- Vertex namedQueryElementVertex, Vertex instanceVertex, String apiVer )
- throws AAIException {
-
- // If this model-element says that they want an alternative set of properties returned, then pull that
- // data out of the instance vertex.
-
- Map<String,Object> altPropHash = new HashMap<>();
-
- if( namedQueryElementVertex == null ){
- String msg = " null namedQueryElementVertex passed to getNamedQueryPropOverRide() ";
- throw new AAIException("AAI_6114", msg);
- }
-
- List<String> propCollectList = new ArrayList<>();
- Iterator <VertexProperty<Object>> vpI = namedQueryElementVertex.properties("property-collect-list");
- while( vpI.hasNext() ){
- propCollectList.add((String)vpI.next().value());
- }
-
- for( int i = 0; i < propCollectList.size(); i++ ){
- String thisPropName = propCollectList.get(i);
- Object instanceVal = instanceVertex.<Object>property(thisPropName).orElse(null);
- altPropHash.put(thisPropName, instanceVal);
- }
-
- return altPropHash;
-
- } // End of getNamedQueryPropOverRide()
-
-
- /**
- * Named query constraint says stop.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param namedQueryElementVertex the named query element vertex
- * @param instanceVertex the instance vertex
- * @param apiVer the api ver
- * @return true - if a constraint was defined that has not been met by the passed instanceVertex
- * @throws AAIException the AAI exception
- */
- public Boolean namedQueryConstraintSaysStop(String transId, String fromAppId,
- Vertex namedQueryElementVertex, Vertex instanceVertex, String apiVer )
- throws AAIException {
-
- // For each (if any) property-constraint defined for this named-query-element, we will evaluate if
- // the constraint is met or not-met. if there are constraints and any are not-met, then
- // we return "true".
-
- if( namedQueryElementVertex == null ){
- String msg = " null namedQueryElementVertex passed to namedQueryConstraintSaysStop() ";
- throw new AAIException("AAI_6114", msg);
- }
- if( instanceVertex == null ){
- String msg = " null instanceVertex passed to namedQueryConstraintSaysStop() ";
- throw new AAIException("AAI_6114", msg);
- }
-
- Iterator<Vertex> constrPipe = this.traverseIncidentEdges(EdgeType.TREE, namedQueryElementVertex, "property-constraint");
- if( constrPipe == null || !constrPipe.hasNext() ){
- // There's no "property-constraint" defined for this named-query-element. No problem.
- return false;
- }
-
- while( constrPipe.hasNext() ){
- Vertex constrVtx = constrPipe.next();
- // We found a property constraint that we will need to check
- String conType = constrVtx.<String>property("constraint-type").orElse(null);
- if( (conType == null) || conType.equals("")){
- String msg = " Bad property-constraint (constraint-type) found in Named Query definition. ";
- throw new AAIException("AAI_6133", msg);
- }
- String propName = constrVtx.<String>property("property-name").orElse(null);
- if( (propName == null) || propName.equals("")){
- String msg = " Bad property-constraint (property-name) found in Named Query definition. ";
- throw new AAIException("AAI_6133", msg);
- }
- String propVal = constrVtx.<String>property("property-value").orElse(null);
- if( (propVal == null) || propVal.equals("")){
- String msg = " Bad property-constraint (propVal) found in Named Query definition. ";
- throw new AAIException("AAI_6133", msg);
- }
-
- // See if that constraint is met or not
- String val = instanceVertex.<String>property(propName).orElse(null);
- if( val == null ){
- val = "";
- }
-
- if( conType.equals("EQUALS") ){
- if( !val.equals(propVal) ){
- // This constraint was not met
- return true;
- }
- }
- else if( conType.equals("NOT-EQUALS") ){
- if( val.equals(propVal) ){
- // This constraint was not met
- return true;
- }
- }
- else {
- String msg = " Bad property-constraint (constraint-type) found in Named Query definition. ";
- throw new AAIException("AAI_6133", msg);
- }
- }
-
- return false;
-
- } // End of namedQueryConstraintSaysStop()
-
-
- /**
- * Gets the named query extra data lookup.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param namedQueryElementVertex the named query element vertex
- * @param instanceVertex the instance vertex
- * @param apiVer the api ver
- * @return HashMap of alternate properties to return for this element
- * @throws AAIException the AAI exception
- */
- public Map<String,Object> getNamedQueryExtraDataLookup(String transId, String fromAppId,
- Vertex namedQueryElementVertex, Vertex instanceVertex, String apiVer )
- throws AAIException {
-
- // For each (if any) related-lookup defined for this named-query-element, we will go and
- // and try to find it. All the related-lookup data will get put in a hash and returned.
-
- if( namedQueryElementVertex == null ){
- String msg = " null namedQueryElementVertex passed to getNamedQueryExtraDataLookup() ";
- throw new AAIException("AAI_6114", msg);
- }
- if( instanceVertex == null ){
- String msg = " null instanceVertex passed to getNamedQueryExtraDataLookup() ";
- throw new AAIException("AAI_6114", msg);
- }
-
- Map<String,Object> retHash = new HashMap<>();
-
- Iterator<Vertex> lookPipe = this.traverseIncidentEdges(EdgeType.TREE, namedQueryElementVertex, "related-lookup");
- if( lookPipe == null || !lookPipe.hasNext() ){
- // There's no "related-lookup" defined for this named-query-element. No problem.
- return retHash;
- }
-
- while( lookPipe.hasNext() ){
- Vertex relLookupVtx = lookPipe.next();
- // We found a related-lookup record to try and use
- String srcProp = relLookupVtx.<String>property("source-node-property").orElse(null);
- String srcNodeType = relLookupVtx.<String>property("source-node-type").orElse(null);
- srcProp = getPropNameWithAliasIfNeeded(srcNodeType, srcProp);
-
- if( (srcProp == null) || srcProp.equals("")){
- String msg = " Bad related-lookup (source-node-property) found in Named Query definition. ";
- throw new AAIException("AAI_6133", msg);
- }
- String targetNodeType = relLookupVtx.<String>property("target-node-type").orElse(null);
- if( (targetNodeType == null) || targetNodeType.equals("")){
- String msg = " Bad related-lookup (targetNodeType) found in Named Query definition. ";
- throw new AAIException("AAI_6133", msg);
- }
- String targetProp = relLookupVtx.<String>property("target-node-property").orElse(null);
- targetProp = getPropNameWithAliasIfNeeded(targetNodeType, targetProp);
-
- if( (targetProp == null) || targetProp.equals("")){
- String msg = " Bad related-lookup (target-node-property) found in Named Query definition. ";
- throw new AAIException("AAI_6133", msg);
- }
-
- List<String> propCollectList = new ArrayList<>();
- Iterator <VertexProperty<Object>> vpI = relLookupVtx.properties("property-collect-list");
- while( vpI.hasNext() ){
- propCollectList.add((String)vpI.next().value());
- }
-
- // Use the value from the source to see if we can find ONE target record using the
- // value from the source
- String valFromInstance = instanceVertex.<String>property(srcProp).orElse(null);
- if( valFromInstance == null ){
- // if there is no key to use to go look up something, we should end it here and just
- // note what happened - no need to try to look something up by an empty key
- logger.debug("WARNING - the instance data node of type [" + srcNodeType
- + "] did not have a value for property [" + srcProp
- + "], so related-lookup is being abandoned.");
- return retHash;
- }
-
- Map<String,Object> propHash = new HashMap<>();
- propHash.put(targetProp, valFromInstance);
-
- Optional<Vertex> result = dbMethHelper.locateUniqueVertex(targetNodeType, propHash);
- if (!result.isPresent()) {
- // If it can't find the lookup node, don't fail, just log that it couldn't be found ---
+ // NOTE: we're expecting the filter to have a format like this:
+ // "nodeType.parameterName:parameterValue"
+
+ Vertex vert = resSet.getVert();
+ if (vert == null) {
+ return false;
+ } else {
+ String nt = resSet.getVert().<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ if (nt.equals(filtNodeType)) {
+ if (filtPropName.equals("vertex-id")) {
+ // vertex-id can't be gotten the same way as other properties
+ String thisVtxId = vert.id().toString();
+ if (thisVtxId.equals(filtPropVal)) {
+ return true;
+ }
+ } else {
+ Object thisValObj = vert.property(filtPropName).orElse(null);
+ if (thisValObj != null) {
+ String thisVal = thisValObj.toString();
+ if (thisVal.equals(filtPropVal)) {
+ return true;
+ }
+ }
+ }
+ }
+ }
+
+ // Didn't find a match at the this level, so check the sets below it meet the criteria
+ if (resSet.getSubResultSet() != null) {
+ ListIterator<ResultSet> listItr = resSet.getSubResultSet().listIterator();
+ while (listItr.hasNext()) {
+ if (filterMetByThisSet(listItr.next(), filtNodeType, filtPropName, filtPropVal)) {
+ return true;
+ }
+ }
+ }
+
+ return false;
+
+ }// end of filterMetByThisSet()
+
+ /**
+ * Collapse for do not output.
+ *
+ * @param resSetVal the res set val
+ * @return the array list
+ * @throws AAIException the AAI exception
+ */
+ public List<ResultSet> collapseForDoNotOutput(ResultSet resSetVal) throws AAIException {
+
+ // Given a ResultSet -- if it is tagged to NOT be output, then replace it with
+ // it's sub-ResultSets if it has any.
+ List<ResultSet> colResultSet = new ArrayList<>();
+
+ if (resSetVal.getDoNotOutputFlag().equals("true")) {
+ // This ResultSet isn't to be displayed, so replace it with it's sub-ResultSets
+ List<ResultSet> subResList = resSetVal.getSubResultSet();
+ for (int k = 0; k < subResList.size(); k++) {
+ List<ResultSet> newSubResList = collapseForDoNotOutput(subResList.get(k));
+ colResultSet.addAll(newSubResList);
+ }
+ } else {
+ // This set will be displayed
+ colResultSet.add(resSetVal);
+ }
+
+ // For each result set now at this level, call this same routine to collapse their
+ // sub-resultSets
+ for (int i = 0; i < colResultSet.size(); i++) {
+ List<ResultSet> newSubSet = new ArrayList<>();
+ List<ResultSet> subResList = colResultSet.get(i).getSubResultSet();
+ for (int n = 0; n < subResList.size(); n++) {
+ List<ResultSet> newSubResList = collapseForDoNotOutput(subResList.get(n));
+ newSubSet.addAll(newSubResList);
+ }
+ // Replace the old subResultSet with the collapsed set
+ colResultSet.get(i).setSubResultSet(newSubSet);
+ }
+
+ return colResultSet;
+
+ }// End collapseForDoNotOutput()
+
+ /**
+ * Collect instance data.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param thisLevelElemVtx the element vtx at this level
+ * @param thisVertsTrail the this verts trail
+ * @param validNextStepMap the valid next step map -- hash of valid next steps (node types) for
+ * this model
+ * @param vidsTraversed the vids traversed -- ArrayList of vertexId's that we traversed to get
+ * to this point
+ * @param levelCounter the level counter
+ * @param delKeyHash -- hashMap of which spots on our topology should be deleted during a
+ * modelDelete
+ * @param namedQueryElementHash - hashMap which maps each spot in our widget topology to the
+ * NamedQueryElemment that it maps to
+ * @param apiVer the api ver
+ * @return resultSet
+ * @throws AAIException the AAI exception
+ */
+ public ResultSet collectInstanceData(String transId, String fromAppId, Vertex thisLevelElemVtx,
+ String thisVertsTrail, Multimap<String, String> validNextStepMap,
+ List<String> vidsTraversed, int levelCounter, Map<String, String> delKeyHash, // only
+ // applies
+ // when
+ // collecting
+ // data using
+ // the default
+ // model for
+ // delete
+ Map<String, String> namedQueryElementHash, // only applies to named-query data collecting
+ String apiVer) throws AAIException {
+
+ levelCounter++;
+
+ String thisElemVid = thisLevelElemVtx.id().toString();
+
+ if (levelCounter > MAX_LEVELS) {
+ throw new AAIException("AAI_6125",
+ "collectInstanceData() has looped across more levels than allowed: " + MAX_LEVELS
+ + ". ");
+ }
+
+ ResultSet rs = new ResultSet();
+ if (namedQueryElementHash.containsKey(thisVertsTrail)) {
+ // We're collecting data for a named-query, so need to see if we need to do anything
+ // special
+ String nqElUuid = namedQueryElementHash.get(thisVertsTrail);
+ Vertex nqElementVtx = getNodeUsingUniqueId(transId, fromAppId, "named-query-element",
+ "named-query-element-uuid", nqElUuid);
+
+ String tmpDoNotShow = nqElementVtx.<String>property("do-not-output").orElse(null);
+ if (tmpDoNotShow != null && tmpDoNotShow.equals("true")) {
+ rs.setDoNotOutputFlag("true");
+ }
+
+ if (namedQueryConstraintSaysStop(transId, fromAppId, nqElementVtx, thisLevelElemVtx,
+ apiVer)) {
+ // There was a property constraint which says they do not want to collect this
+ // vertex or whatever
+ // might be below it. Just return the empty rs here.
+ return rs;
+ }
+
+ String propLimDesc = nqElementVtx.<String>property("property-limit-desc").orElse(null);
+ if ((propLimDesc != null) && !propLimDesc.equals("")) {
+ if (propLimDesc.equalsIgnoreCase("show-all")) {
+ rs.setPropertyLimitDesc(PropertyLimitDesc.SHOW_ALL);
+ } else if (propLimDesc.equalsIgnoreCase("show-none")) {
+ rs.setPropertyLimitDesc(PropertyLimitDesc.SHOW_NONE);
+ } else if (propLimDesc.equalsIgnoreCase("name-and-keys-only")) {
+ rs.setPropertyLimitDesc(PropertyLimitDesc.SHOW_NAME_AND_KEYS_ONLY);
+ }
+ }
+
+ // Look to see if we need to use an Override of the normal properties
+ Map<String, Object> tmpPropertyOverRideHash = getNamedQueryPropOverRide(transId,
+ fromAppId, nqElementVtx, thisLevelElemVtx, apiVer);
+ // System.out.println(" DEBUG --- USING this propertyOverride data set on ResSet [" +
+ // tmpPropertyOverRideHash.toString() + "]");
+ rs.setPropertyOverRideHash(tmpPropertyOverRideHash);
+
+ // See if we need to look up any "unconnected" data that needs to be associated with
+ // this result set
+ Map<String, Object> tmpExtraPropHash = getNamedQueryExtraDataLookup(transId, fromAppId,
+ nqElementVtx, thisLevelElemVtx, apiVer);
+ // System.out.println(" DEBUG --- ADDING this EXTRA Lookup data to the ResSet [" +
+ // tmpExtraPropHash.toString() + "]");
+ rs.setExtraPropertyHash(tmpExtraPropHash);
+ }
+
+ rs.setVert(thisLevelElemVtx);
+ rs.setLocationInModelSubGraph(thisVertsTrail);
+ if (delKeyHash.containsKey(thisVertsTrail) && delKeyHash.get(thisVertsTrail).equals("T")) {
+ rs.setNewDataDelFlag("T");
+ } else {
+ rs.setNewDataDelFlag("F");
+ }
+
+ // Use Gremlin-pipeline to just look for edges that go to a valid "next-steps"
+ Collection<String> validNextStepColl = validNextStepMap.get(thisVertsTrail);
+
+ // Because of how we process linkage-points, we may have duplicate node-types in our
+ // next-stepMap (for one step)
+ // So, to keep from looking (and bringing back) the same data twice, we need to make sure
+ // our next-steps are unique
+ Set<String> validNextStepHashSet = new HashSet<>();
+ Iterator<String> ntcItr = validNextStepColl.iterator();
+ while (ntcItr.hasNext()) {
+ String targetStepStr = ntcItr.next();
+ validNextStepHashSet.add(targetStepStr);
+ }
+
+ List<String> tmpVidsTraversedList = new ArrayList<>();
+ tmpVidsTraversedList.addAll(vidsTraversed);
+ tmpVidsTraversedList.add(thisElemVid);
+
+ Iterator<String> ntItr = validNextStepHashSet.iterator();
+ while (ntItr.hasNext()) {
+ String targetStep = ntItr.next();
+ // NOTE: NextSteps can either be just a nodeType, or can be a nodeType plus
+ // model-invariant-id-local and model-version-id-local (the two persona properties)
+ // if those need to be checked also.
+ // When the persona stuff is part of the step, it is a comma separated string.
+ // Ie. "nodeType,model-inv-id-local,model-version-id-local" (the two "persona" props)
+ //
+ String targetNodeType = "";
+ String pmid = "";
+ String pmv = "";
+ Boolean stepIsJustNT = true;
+ if (targetStep.contains(",")) {
+ stepIsJustNT = false;
+ String[] pieces = targetStep.split(",");
+ if (pieces.length != 3) {
+ throw new AAIException("AAI_6128",
+ "Unexpected format for nextStep in model processing = [" + targetStep
+ + "]. ");
+ } else {
+ targetNodeType = pieces[0];
+ pmid = pieces[1];
+ pmv = pieces[2];
+ }
+ } else {
+ // It's just the nodeType with no other info
+ targetNodeType = targetStep;
+ }
+
+ GraphTraversal<Vertex, Vertex> modPipe = null;
+ if (stepIsJustNT) {
+ modPipe = this.engine.asAdmin().getReadOnlyTraversalSource().V(thisLevelElemVtx)
+ .both().has(AAIProperties.NODE_TYPE, targetNodeType);
+ } else {
+ modPipe = this.engine.asAdmin().getReadOnlyTraversalSource().V(thisLevelElemVtx)
+ .both().has(AAIProperties.NODE_TYPE, targetNodeType)
+ .has(addDBAliasedSuffix("model-invariant-id"), pmid)
+ .has(addDBAliasedSuffix("model-version-id"), pmv);
+ }
+
+ if (modPipe == null || !modPipe.hasNext()) {
+ // System.out.println("DEBUG - didn't find any [" + targetStep + "] connected to
+ // this guy (which is ok)");
+ } else {
+ while (modPipe.hasNext()) {
+ Vertex tmpVert = modPipe.next();
+ String tmpVid = tmpVert.id().toString();
+ String tmpTrail = thisVertsTrail + "|" + targetStep;
+ if (!vidsTraversed.contains(tmpVid)) {
+ // This is one we would like to use - so we'll include the result set we get
+ // for it
+ ResultSet tmpResSet = collectInstanceData(transId, fromAppId, tmpVert,
+ tmpTrail, validNextStepMap, tmpVidsTraversedList, levelCounter,
+ delKeyHash, namedQueryElementHash, apiVer);
+
+ rs.getSubResultSet().add(tmpResSet);
+ }
+ }
+ }
+ }
+
+ return rs;
+
+ } // End of collectInstanceData()
+
+ /**
+ * Gen topo map 4 model.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param modelVerVertex the model-ver vertex
+ * @param modelVerId the model-version-id
+ * @return MultiMap of valid next steps for each potential model-element
+ * @throws AAIException the AAI exception
+ */
+ public Multimap<String, String> genTopoMap4ModelVer(String transId, String fromAppId,
+ Vertex modelVerVertex, String modelVerId) throws AAIException {
+
+ if (modelVerVertex == null) {
+ throw new AAIException("AAI_6114",
+ "null modelVerVertex passed to genTopoMap4ModelVer()");
+ }
+
+ Multimap<String, String> initialEmptyMap = ArrayListMultimap.create();
+ List<String> vidsTraversed = new ArrayList<>();
+ String modelType = getModelTypeFromModelVer(modelVerVertex, "");
+ if (modelType.equals("widget")) {
+ // A widget model by itself does not have a topoplogy. That is - it has no
+ // "model-elements" which
+ // define how it is connected to other things. All it has is a name which ties it to
+ // an aai-node-type
+ Iterator<Vertex> vertI =
+ this.traverseIncidentEdges(EdgeType.TREE, modelVerVertex, "model-element");
+ if (vertI != null && vertI.hasNext()) {
+ throw new AAIException("AAI_6132",
+ "Bad Model Definition: Widget Model has a startsWith edge to a model-element. "
+ + " model-version-id = " + modelVerId);
+ } else {
+ return initialEmptyMap;
+ }
+ }
+
+ String firstModelVerId = modelVerVertex.<String>property("model-version-id").orElse(null);
+ String firstModelVersion = modelVerVertex.<String>property("model-version").orElse(null);
+ if (firstModelVerId == null || firstModelVerId.equals("") || firstModelVersion == null
+ || firstModelVersion.equals("")) {
+ throw new AAIException("AAI_6132",
+ "Bad Model Definition: Bad model-version-id or model-version. model-version-id = "
+ + modelVerId);
+ }
+
+ Vertex firstElementVertex = getTopElementForSvcOrResModelVer(modelVerVertex, "");
+ Vertex firstEleModVerVtx = getModelVerThatElementRepresents(firstElementVertex, "");
+ String firstElemModelType = getModelTypeFromModelVer(firstEleModVerVtx, "");
+ if (!firstElemModelType.equals("widget")) {
+ throw new AAIException("AAI_6132",
+ "Bad Model Definition: First element must correspond to a widget type model. Model UUID = "
+ + modelVerId);
+ }
+
+ Vertex firstModVtx = getModelGivenModelVer(modelVerVertex, "");
+ String firstModelInvId = firstModVtx.<String>property("model-invariant-id").orElse(null);
+ if (firstModelInvId == null || firstModelInvId.equals("")) {
+ throw new AAIException("AAI_6132",
+ "Bad Model Definition: Could not find model.model-invariant-id given model-ver.model-version-id = "
+ + modelVerId);
+ }
+
+ return collectTopology4ModelVer(transId, fromAppId, firstElementVertex, "", initialEmptyMap,
+ vidsTraversed, 0, null, firstModelInvId, firstModelVersion);
+ } // End of genTopoMap4ModelVer()
+
+ public List<String> makeSureItsAnArrayList(String listStringVal) {
+ // We're sometimes getting a String back on db properties that should be ArrayList<String>
+ // Seems to be how they're defined in OXM - whether they use a "xml-wrapper" or not
+ // Need to translate them into ArrayLists sometimes...
+
+ List<String> retArrList = new ArrayList<>();
+ String listString = listStringVal;
+ listString = listString.replace(" ", "");
+ listString = listString.replace("\"", "");
+ listString = listString.replace("[", "");
+ listString = listString.replace("]", "");
+ String[] pieces = listString.split(",");
+ if (pieces.length > 0) {
+ retArrList.addAll(Arrays.asList(pieces));
+ }
+ return retArrList;
+ }
+
+ /**
+ * Gets the mod constraint hash.
+ *
+ * @param modelElementVtx the model element vtx
+ * @param currentHash -- the current ModelConstraint's that this routine will add to if it finds
+ * any.
+ * @return HashMap of model-constraints that will be looked at for this model-element and what's
+ * "below" it.
+ * @throws AAIException the AAI exception
+ */
+ public Map<String, Vertex> getModConstraintHash(Vertex modelElementVtx,
+ Map<String, Vertex> currentHash) throws AAIException {
+
+ // For a given model-element vertex, look to see if there are any "model-constraint"
+ // elements that is has
+ // an OUT "uses" edge to. If it does, then get any "constrained-element-set" nodes that are
+ // pointed to
+ // by the "model-constraint". That will be the replacement "constrained-element-set". The
+ // UUID of the
+ // "constrained-element-set" that it is supposed to replace is found in the property:
+ // model-constraint.constrained-element-set-uuid-to-replace
+ //
+ // For now, that is the only type of model-constraint allowed, so that is all we will look
+ // for.
+ // Pass back any of these "constrained-element-set" nodes along with any that were passed in
+ // by
+ // the "currentHash" parameter.
+
+ if (modelElementVtx == null) {
+ String msg = " null modelElementVtx passed to getModConstraintHash() ";
+ throw new AAIException("AAI_6114", msg);
+ }
+
+ String modelType = modelElementVtx.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ if (modelType == null || (!modelType.equals("model-element"))) {
+ String msg =
+ " getModConstraintHash() called with wrong type model: [" + modelType + "]. ";
+ throw new AAIException("AAI_6114", msg);
+ }
+
+ Map<String, Vertex> thisHash = new HashMap<>();
+ if (currentHash != null) {
+ thisHash.putAll(currentHash);
+ }
+
+ int count = 0;
+ List<Vertex> modelConstraintArray = new ArrayList<>();
+ Iterator<Vertex> vertI =
+ this.traverseIncidentEdges(EdgeType.TREE, modelElementVtx, "model-constraint");
+ while (vertI != null && vertI.hasNext()) {
+ Vertex tmpVert = vertI.next();
+ String connectToType = tmpVert.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ if ((connectToType != null) && connectToType.equals("model-constraint")) {
+ // We need to find the constrained element set pointed to by this and add it to the
+ // Hash to return
+ modelConstraintArray.add(tmpVert);
+ count++;
+ }
+ }
+
+ if (count > 0) {
+ for (int i = 0; i < count; i++) {
+ Vertex vtxOfModelConstraint = modelConstraintArray.get(i);
+ String uuidOfTheOneToBeReplaced = vtxOfModelConstraint
+ .<String>property("constrained-element-set-uuid-2-replace").orElse(null);
+ // We have the UUID of the constrained-element-set that will be superseded, now find
+ // the
+ // constrained-element-set to use in its place
+ Iterator<Vertex> mvertI = this.traverseIncidentEdges(EdgeType.TREE,
+ vtxOfModelConstraint, "constrained-element-set");
+ while (mvertI != null && mvertI.hasNext()) {
+ // There better only be one...
+ Vertex tmpVert = mvertI.next();
+ String connectToType =
+ tmpVert.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ if ((connectToType != null)
+ && connectToType.equals("constrained-element-set")) {
+ // This is the "constrained-element-set" that we want to use as the
+ // Replacement
+ thisHash.put(uuidOfTheOneToBeReplaced, tmpVert);
+ }
+ }
+ }
+ return thisHash;
+ } else {
+ // Didn't find anything to add, so just return what they passed in.
+ return currentHash;
+ }
+
+ } // End of getModConstraintHash()
+
+ /**
+ * Gets the top element vertex for service or resource model.
+ *
+ * @param modelVerVtx the model-ver vertex
+ * @return first element pointed to by this model-ver
+ * @throws AAIException the AAI exception
+ */
+ public Vertex getTopElementForSvcOrResModelVer(Vertex modelVerVtx, String trail)
+ throws AAIException {
+
+ // For a "resource" or "service" type model, return the "top" element in that model
+ if (modelVerVtx == null) {
+ String msg = " null modelVertex passed to getTopoElementForSvcOrResModelVer() at ["
+ + trail + "]. ";
+ throw new AAIException("AAI_6114", msg);
+ }
+
+ String modelVerId = modelVerVtx.<String>property("model-version-id").orElse(null);
+ if (modelVerId == null) {
+ String nt = modelVerVtx.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ if (nt != null && !nt.equals("model-ver")) {
+ String msg = "Illegal model defined: model element pointing to nodeType: [" + nt
+ + "], should be pointing to: [model-ver] at [" + trail + "]. ";
+ throw new AAIException("AAI_6132", msg);
+ }
+ }
+
+ Vertex firstElementVertex = null;
+
+ Iterator<Vertex> vertI =
+ this.traverseIncidentEdges(EdgeType.TREE, modelVerVtx, "model-element");
+ int elCount = 0;
+ while (vertI != null && vertI.hasNext()) {
+ elCount++;
+ firstElementVertex = vertI.next();
+ }
+
+ if (elCount > 1) {
+ String msg =
+ "Illegal model defined: More than one first element defined for model-ver-id = "
+ + modelVerId + " at [" + trail + "]. ";
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ if (firstElementVertex == null) {
+ String msg = "Could not find first model element for model-ver-id = " + modelVerId
+ + " at [" + trail + "]. ";
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ return firstElementVertex;
+
+ } // End of getTopElementForSvcOrResModelVer()
+
+ /**
+ * Gets the named query prop over ride.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param namedQueryElementVertex the named query element vertex
+ * @param instanceVertex the instance vertex
+ * @param apiVer the api ver
+ * @return HashMap of alternate properties to return for this element
+ * @throws AAIException the AAI exception
+ */
+ public Map<String, Object> getNamedQueryPropOverRide(String transId, String fromAppId,
+ Vertex namedQueryElementVertex, Vertex instanceVertex, String apiVer) throws AAIException {
+
+ // If this model-element says that they want an alternative set of properties returned, then
+ // pull that
+ // data out of the instance vertex.
+
+ Map<String, Object> altPropHash = new HashMap<>();
+
+ if (namedQueryElementVertex == null) {
+ String msg = " null namedQueryElementVertex passed to getNamedQueryPropOverRide() ";
+ throw new AAIException("AAI_6114", msg);
+ }
+
+ List<String> propCollectList = new ArrayList<>();
+ Iterator<VertexProperty<Object>> vpI =
+ namedQueryElementVertex.properties("property-collect-list");
+ while (vpI.hasNext()) {
+ propCollectList.add((String) vpI.next().value());
+ }
+
+ for (int i = 0; i < propCollectList.size(); i++) {
+ String thisPropName = propCollectList.get(i);
+ Object instanceVal = instanceVertex.<Object>property(thisPropName).orElse(null);
+ altPropHash.put(thisPropName, instanceVal);
+ }
+
+ return altPropHash;
+
+ } // End of getNamedQueryPropOverRide()
+
+ /**
+ * Named query constraint says stop.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param namedQueryElementVertex the named query element vertex
+ * @param instanceVertex the instance vertex
+ * @param apiVer the api ver
+ * @return true - if a constraint was defined that has not been met by the passed instanceVertex
+ * @throws AAIException the AAI exception
+ */
+ public Boolean namedQueryConstraintSaysStop(String transId, String fromAppId,
+ Vertex namedQueryElementVertex, Vertex instanceVertex, String apiVer) throws AAIException {
+
+ // For each (if any) property-constraint defined for this named-query-element, we will
+ // evaluate if
+ // the constraint is met or not-met. if there are constraints and any are not-met, then
+ // we return "true".
+
+ if (namedQueryElementVertex == null) {
+ String msg = " null namedQueryElementVertex passed to namedQueryConstraintSaysStop() ";
+ throw new AAIException("AAI_6114", msg);
+ }
+ if (instanceVertex == null) {
+ String msg = " null instanceVertex passed to namedQueryConstraintSaysStop() ";
+ throw new AAIException("AAI_6114", msg);
+ }
+
+ Iterator<Vertex> constrPipe = this.traverseIncidentEdges(EdgeType.TREE,
+ namedQueryElementVertex, "property-constraint");
+ if (constrPipe == null || !constrPipe.hasNext()) {
+ // There's no "property-constraint" defined for this named-query-element. No problem.
+ return false;
+ }
+
+ while (constrPipe.hasNext()) {
+ Vertex constrVtx = constrPipe.next();
+ // We found a property constraint that we will need to check
+ String conType = constrVtx.<String>property("constraint-type").orElse(null);
+ if ((conType == null) || conType.equals("")) {
+ String msg =
+ " Bad property-constraint (constraint-type) found in Named Query definition. ";
+ throw new AAIException("AAI_6133", msg);
+ }
+ String propName = constrVtx.<String>property("property-name").orElse(null);
+ if ((propName == null) || propName.equals("")) {
+ String msg =
+ " Bad property-constraint (property-name) found in Named Query definition. ";
+ throw new AAIException("AAI_6133", msg);
+ }
+ String propVal = constrVtx.<String>property("property-value").orElse(null);
+ if ((propVal == null) || propVal.equals("")) {
+ String msg = " Bad property-constraint (propVal) found in Named Query definition. ";
+ throw new AAIException("AAI_6133", msg);
+ }
+
+ // See if that constraint is met or not
+ String val = instanceVertex.<String>property(propName).orElse(null);
+ if (val == null) {
+ val = "";
+ }
+
+ if (conType.equals("EQUALS")) {
+ if (!val.equals(propVal)) {
+ // This constraint was not met
+ return true;
+ }
+ } else if (conType.equals("NOT-EQUALS")) {
+ if (val.equals(propVal)) {
+ // This constraint was not met
+ return true;
+ }
+ } else {
+ String msg =
+ " Bad property-constraint (constraint-type) found in Named Query definition. ";
+ throw new AAIException("AAI_6133", msg);
+ }
+ }
+
+ return false;
+
+ } // End of namedQueryConstraintSaysStop()
+
+ /**
+ * Gets the named query extra data lookup.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param namedQueryElementVertex the named query element vertex
+ * @param instanceVertex the instance vertex
+ * @param apiVer the api ver
+ * @return HashMap of alternate properties to return for this element
+ * @throws AAIException the AAI exception
+ */
+ public Map<String, Object> getNamedQueryExtraDataLookup(String transId, String fromAppId,
+ Vertex namedQueryElementVertex, Vertex instanceVertex, String apiVer) throws AAIException {
+
+ // For each (if any) related-lookup defined for this named-query-element, we will go and
+ // and try to find it. All the related-lookup data will get put in a hash and returned.
+
+ if (namedQueryElementVertex == null) {
+ String msg = " null namedQueryElementVertex passed to getNamedQueryExtraDataLookup() ";
+ throw new AAIException("AAI_6114", msg);
+ }
+ if (instanceVertex == null) {
+ String msg = " null instanceVertex passed to getNamedQueryExtraDataLookup() ";
+ throw new AAIException("AAI_6114", msg);
+ }
+
+ Map<String, Object> retHash = new HashMap<>();
+
+ Iterator<Vertex> lookPipe =
+ this.traverseIncidentEdges(EdgeType.TREE, namedQueryElementVertex, "related-lookup");
+ if (lookPipe == null || !lookPipe.hasNext()) {
+ // There's no "related-lookup" defined for this named-query-element. No problem.
+ return retHash;
+ }
+
+ while (lookPipe.hasNext()) {
+ Vertex relLookupVtx = lookPipe.next();
+ // We found a related-lookup record to try and use
+ String srcProp = relLookupVtx.<String>property("source-node-property").orElse(null);
+ String srcNodeType = relLookupVtx.<String>property("source-node-type").orElse(null);
+ srcProp = getPropNameWithAliasIfNeeded(srcNodeType, srcProp);
+
+ if ((srcProp == null) || srcProp.equals("")) {
+ String msg =
+ " Bad related-lookup (source-node-property) found in Named Query definition. ";
+ throw new AAIException("AAI_6133", msg);
+ }
+ String targetNodeType = relLookupVtx.<String>property("target-node-type").orElse(null);
+ if ((targetNodeType == null) || targetNodeType.equals("")) {
+ String msg =
+ " Bad related-lookup (targetNodeType) found in Named Query definition. ";
+ throw new AAIException("AAI_6133", msg);
+ }
+ String targetProp = relLookupVtx.<String>property("target-node-property").orElse(null);
+ targetProp = getPropNameWithAliasIfNeeded(targetNodeType, targetProp);
+
+ if ((targetProp == null) || targetProp.equals("")) {
+ String msg =
+ " Bad related-lookup (target-node-property) found in Named Query definition. ";
+ throw new AAIException("AAI_6133", msg);
+ }
+
+ List<String> propCollectList = new ArrayList<>();
+ Iterator<VertexProperty<Object>> vpI = relLookupVtx.properties("property-collect-list");
+ while (vpI.hasNext()) {
+ propCollectList.add((String) vpI.next().value());
+ }
+
+ // Use the value from the source to see if we can find ONE target record using the
+ // value from the source
+ String valFromInstance = instanceVertex.<String>property(srcProp).orElse(null);
+ if (valFromInstance == null) {
+ // if there is no key to use to go look up something, we should end it here and just
+ // note what happened - no need to try to look something up by an empty key
+ logger.debug("WARNING - the instance data node of type [" + srcNodeType
+ + "] did not have a value for property [" + srcProp
+ + "], so related-lookup is being abandoned.");
+ return retHash;
+ }
+
+ Map<String, Object> propHash = new HashMap<>();
+ propHash.put(targetProp, valFromInstance);
+
+ Optional<Vertex> result = dbMethHelper.locateUniqueVertex(targetNodeType, propHash);
+ if (!result.isPresent()) {
+ // If it can't find the lookup node, don't fail, just log that it couldn't be found
+ // ---
logger.debug("WARNING - Could not find lookup node that corresponds to nodeType ["
- + targetNodeType + "] propertyName = [" + srcProp
- + "], propVal = [" + valFromInstance
- + "] so related-lookup is being abandoned.");
- return retHash;
- }
- else {
- Vertex tmpVtx = result.get();
- // Pick up the properties from the target vertex that they wanted us to get
- for( int j = 0; j < propCollectList.size(); j++ ){
- String tmpPropName = propCollectList.get(j);
- tmpPropName = getPropNameWithAliasIfNeeded(targetNodeType, tmpPropName);
- Object valObj = tmpVtx.<Object>property(tmpPropName).orElse(null);
- String lookupKey = targetNodeType + "." + tmpPropName;
- retHash.put(lookupKey, valObj);
-
- }
- }
- }
-
- return retHash;
-
- } // End of getNamedQueryExtraDataLookup()
-
- /**
- * Collect NQ element hash.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param thisLevelElemVtx the element verrtx for this level
- * @param incomingTrail the incoming trail -- trail of nodeTypes that got us here (this nq-element vertex) from the top
- * @param currentHash the current hash
- * @param vidsTraversed the vids traversed -- ArrayList of vertexId's that we traversed to get to this point
- * @param levelCounter the level counter
- * @return HashMap of all widget-points on a namedQuery topology with the value being the "named-query-element-uuid" for that spot.
- * @throws AAIException the AAI exception
- */
- public Map<String, String> collectNQElementHash(String transId, String fromAppId,
- Vertex thisLevelElemVtx, String incomingTrail,
- Map<String,String> currentHash, List <String> vidsTraversed,
- int levelCounter ) throws AAIException {
-
- levelCounter++;
-
- Map<String, String> thisHash = new HashMap<>();
- thisHash.putAll(currentHash);
-
- if( levelCounter > MAX_LEVELS ) {
- throw new AAIException("AAI_6125", "collectNQElementHash() has looped across more levels than allowed: " + MAX_LEVELS + ". ");
- }
- String thisGuysTrail = "";
- String thisElemVid = thisLevelElemVtx.id().toString();
-
- // Find out what widget (and thereby what aai-node-type) this element represents.
- String thisElementNodeType = getNqElementWidgetType( transId, fromAppId, thisLevelElemVtx, incomingTrail );
-
- if( incomingTrail == null || incomingTrail.equals("") ){
- // This is the first one
- thisGuysTrail = thisElementNodeType;
- }
- else {
- thisGuysTrail = incomingTrail + "|" + thisElementNodeType;
- }
- vidsTraversed.add(thisElemVid);
-
- String nqElementUuid = thisLevelElemVtx.<String>property("named-query-element-uuid").orElse(null);
- if( nqElementUuid == null || nqElementUuid.equals("") ){
- String msg = " named-query element UUID not found at trail = [" + incomingTrail + "].";
- throw new AAIException("AAI_6133", msg);
- }
- thisHash.put(thisGuysTrail, nqElementUuid );
-
- // Now go "down" and look at the sub-elements pointed to so we can get their data.
- Iterator<Vertex> vertI = this.traverseIncidentEdges(EdgeType.TREE, thisLevelElemVtx, "named-query-element");
- while( vertI != null && vertI.hasNext() ){
- Vertex tmpVert = vertI.next();
- String vid = tmpVert.id().toString();
- Map<String,Object> elementHash = new HashMap();
-
- String connectToType = tmpVert.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- if( connectToType != null && connectToType.equals("named-query-element") ){
- // This is what we would expect
- elementHash.put(vid, tmpVert);
- }
- else {
- String msg = " named query element has [connectedTo] edge to improper nodeType= ["
- + connectToType + "] trail = [" + incomingTrail + "].";
- throw new AAIException("AAI_6133", msg);
- }
- for( Map.Entry<String, Object> entry : elementHash.entrySet() ){
- Vertex elVert = (Vertex)(entry.getValue());
- String tmpElVid = elVert.id().toString();
- if( !vidsTraversed.contains(tmpElVid) ){
- // This is one we would like to use - so we'll recursively get it's result set to add to ours
- Map<String, String> tmpHash = collectNQElementHash( transId, fromAppId,
- elVert, thisGuysTrail, currentHash, vidsTraversed, levelCounter);
- thisHash.putAll(tmpHash);
- }
- }
- }
- return thisHash;
-
- } // End of collectNQElementHash()
-
-
- /**
- * Collect delete key hash.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param thisLevelElemVtx the element vertex at this level
- * @param incomingTrail the incoming trail -- trail of nodeTypes that got us here (this vertex) from the top
- * @param currentHash the current hash
- * @param vidsTraversed the vids traversed ---- ArrayList of vertexId's that we traversed to get to this point
- * @param levelCounter the level counter
- * @param modConstraintHash the mod constraint hash
- * @param overRideModelId the over ride model id
- * @param overRideModelVersionId the over ride model version id
- * @return HashMap of all widget-points on a model topology with the value being the "newDataDelFlag" for that spot.
- * @throws AAIException the AAI exception
- */
- public Map<String, String> collectDeleteKeyHash(String transId, String fromAppId,
- Vertex thisLevelElemVtx, String incomingTrail,
- Map<String,String> currentHash, List <String> vidsTraversed,
- int levelCounter, Map<String, Vertex> modConstraintHash,
- String overRideModelId, String overRideModelVersionId )
- throws AAIException {
-
- levelCounter++;
-
- Map<String, String> thisHash = new HashMap<>();
- thisHash.putAll(currentHash);
-
- if( levelCounter > MAX_LEVELS ) {
- throw new AAIException("AAI_6125", "collectDeleteKeyHash() has looped across more levels than allowed: " + MAX_LEVELS + ". ");
- }
- String thisGuysTrail = "";
- String thisElemVid = thisLevelElemVtx.id().toString();
- Map<String, Vertex> modConstraintHash2Use = null;
-
- // If this element represents a resource or service model, then we will replace this element with
- // the "top" element of that resource or service model. That model-element already points to its
- // topology, so it will graft in that model's topology.
- // EXCEPT - if this element has "linkage-points" defined, then we need to do some extra
- // processing for how we join to that model and will not try to go any "deeper".
- List<String> linkagePtList = new ArrayList<>();
- Iterator <VertexProperty<Object>> vpI = thisLevelElemVtx.properties("linkage-points");
-
- // I am not sure why, but since "linkage-points" is an xml-element-wrapper in the OXM definition,
- // we get back the whole array of Strings in one String - but still use the "vtx.properties()" to
- // get it - but only look at the first thing returned by the iterator.
- if( vpI.hasNext() ){
- String tmpLinkageThing = (String)vpI.next().value();
- linkagePtList = makeSureItsAnArrayList( tmpLinkageThing );
- }
-
- if( linkagePtList != null && !linkagePtList.isEmpty() ){
- // Whatever this element is - we are connecting to it via a linkage-point
- // We will figure out what to do and then return without going any deeper
- String elemFlag = thisLevelElemVtx.<String>property("new-data-del-flag").orElse(null);
-
- Set<String> linkageConnectNodeTypes = getLinkageConnectNodeTypes( linkagePtList );
- Iterator <?> linkNtIter = linkageConnectNodeTypes.iterator();
- String incTrail = "";
- if( incomingTrail != null && !incomingTrail.equals("") ){
- incTrail = incomingTrail + "|";
- }
-
- while( linkNtIter.hasNext() ){
- // The 'trail' (or trails) for this element should just be the to the first-contact on the linkage point
- String linkTrail = incTrail + linkNtIter.next();
- Boolean alreadyTaggedFalse = false;
- if( thisHash.containsKey(linkTrail) && thisHash.get(linkTrail).equals("F") ){
- // some other path with a matching trail has the deleteFlag set to "F", so we do not want
- // to override that since our model code only uses nodeTypes to know where it is - and we
- // would rather do less deleting than needed instead of too much deleting.
- alreadyTaggedFalse = true;
- }
- if( elemFlag != null && elemFlag.equals("T") && !alreadyTaggedFalse ){
- // This trail should be marked with an "T"
- thisHash.put(linkTrail, "T");
- }
- else {
- thisHash.put(linkTrail, "F");
- }
- }
- return thisHash;
- }
-
- // ----------------------------------------------------------------------------
- // If we got to here, then this was not an element that used a linkage-point
- // ----------------------------------------------------------------------------
-
- // Find out what widget-model (and thereby what aai-node-type) this element represents.
- // Even if this element is pointing to a service or resource model, it must have a
- // first element which is a single widget-type model.
- String thisElementNodeType = getModElementWidgetType( thisLevelElemVtx, incomingTrail );
- String firstElementModelInfo = "";
-
- vidsTraversed.add(thisElemVid);
- Vertex elementVtxForThisLevel = null;
- Vertex thisElementsModelVerVtx = getModelVerThatElementRepresents( thisLevelElemVtx, incomingTrail );
- Vertex thisElementsModelVtx = getModelGivenModelVer( thisElementsModelVerVtx, incomingTrail );
- String modType = getModelTypeFromModel( thisElementsModelVtx, incomingTrail );
- String subModelFirstModInvId = thisElementsModelVtx.<String>property("model-invariant-id").orElse(null);
- String subModelFirstVerId = thisElementsModelVerVtx.<String>property("model-version-id").orElse(null);
- if( modType.equals("widget") ){
- if( overRideModelId != null && !overRideModelId.equals("") ){
- // Note - this is just to catch the correct model for the TOP node in a model since
- // it will have an element which will always be a widget even though the model
- // could be a resource or service model.
- firstElementModelInfo = "," + overRideModelId + "," + overRideModelVersionId;
- }
- }
- else if( nodeTypeSupportsPersona(thisElementNodeType) ){
- firstElementModelInfo = "," + subModelFirstModInvId + "," + subModelFirstVerId;
- }
-
- if( incomingTrail.equals("") ){
- // This is the first one
- thisGuysTrail = thisElementNodeType + firstElementModelInfo;
- }
- else {
- thisGuysTrail = incomingTrail + "|" + thisElementNodeType + firstElementModelInfo;
- }
-
- String tmpFlag = "F";
- Boolean stoppedByASvcOrResourceModelElement = false;
- if( modType.equals("widget") ){
- elementVtxForThisLevel = thisLevelElemVtx;
- // For the element-model for the widget at this level, record it's delete flag
- tmpFlag = elementVtxForThisLevel.<String>property("new-data-del-flag").orElse(null);
- }
- else {
- // For an element that is referring to a resource or service model, we replace
- // this element with the "top" element for that resource/service model so that the
- // topology of that resource/service model will be included in this topology.
- String modelVerId = thisElementsModelVerVtx.<String>property("model-version-id").orElse(null);
- if( subModelFirstModInvId == null || subModelFirstModInvId.equals("")
- || subModelFirstVerId == null || subModelFirstVerId.equals("") ){
- throw new AAIException("AAI_6132", "Bad Model Definition: Bad model-invariant-id or model-version-id. Model-version-id = " +
- modelVerId + ", at [" + incomingTrail + "]");
- }
-
- // BUT -- if the model-element HERE at the resource/service level does NOT have
- // it's new-data-del-flag set to "T", then we do not need to go down into the
- // sub-model looking for delete-able things.
-
- tmpFlag = thisLevelElemVtx.<String>property("new-data-del-flag").orElse(null);
- elementVtxForThisLevel = getTopElementForSvcOrResModelVer(thisElementsModelVerVtx, thisGuysTrail);
- if( tmpFlag != null && tmpFlag.equals("T") ){
- modConstraintHash2Use = getModConstraintHash( thisLevelElemVtx, modConstraintHash );
- }
- else {
- stoppedByASvcOrResourceModelElement = true;
- }
- // For the element-model for the widget at this level, record it's delete flag
- tmpFlag = elementVtxForThisLevel.<String>property("new-data-del-flag").orElse(null);
- }
-
- String flag2Use = "F"; // by default we'll use "F" for the delete flag
- if( ! stoppedByASvcOrResourceModelElement ){
- // Since we haven't been stopped by a resource/service level "F", we can look at the lower level flag
- if( thisHash.containsKey(thisGuysTrail) ){
- // We've seen this spot in the topology before - do not override the delete flag if the older one is "F"
- // We will only over-ride it if the old one was "T" and the new one is "F" (anything but "T")
- String oldFlag = thisHash.get(thisGuysTrail);
- if( oldFlag.equals("T") && (tmpFlag != null) && tmpFlag.equals("T") ){
- // The old flag was "T" and the new flag is also "T"
- flag2Use = "T";
- }
- else {
- // the old flag was not "F" - so don't override it
- flag2Use = "F";
- }
- }
- else if( (tmpFlag != null) && tmpFlag.equals("T") ){
- // We have not seen this one, so we can set it to "T" if that's what it is.
- flag2Use = "T";
- }
- }
-
- thisHash.put(thisGuysTrail, flag2Use);
- if( ! stoppedByASvcOrResourceModelElement ){
- // Since we haven't been stopped by a resource/service level "F", we will continue to
- // go "down" and look at the elements pointed to so we can get their data.
- Iterator<Vertex> vertI = this.traverseIncidentEdges(EdgeType.TREE, elementVtxForThisLevel, "model-element", "constrained-element-set");
- while( vertI != null && vertI.hasNext() ){
- Vertex tmpVert = vertI.next();
- String vid = tmpVert.id().toString();
- Map<String,Object> elementHash = new HashMap<>();
-
- String connectToType = tmpVert.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- if( connectToType != null && connectToType.equals("model-element") ){
- // A nice, regular old model-element
- elementHash.put(vid, tmpVert);
- }
- else if( (connectToType != null) && connectToType.equals("constrained-element-set") ){
- // translate the constrained-element-set into a hash of model-element Vertex's
- String constrainedElementSetUuid = tmpVert.<String>property("constrained-element-set-uuid").orElse(null);
- if( (modConstraintHash2Use != null) && modConstraintHash2Use.containsKey(constrainedElementSetUuid) ){
- // This constrained-element-set is being superseded by a different one
- Vertex replacementConstraintVert = modConstraintHash.get(constrainedElementSetUuid);
- elementHash = getNextStepElementsFromSet( replacementConstraintVert );
- // Now that we've found and used the replacement constraint, we don't need to carry it along any farther
- modConstraintHash.remove(constrainedElementSetUuid);
- }
- else {
- elementHash = getNextStepElementsFromSet( tmpVert );
- }
- }
- else {
- String msg = " model-element has [connectedTo] edge to improper nodeType= ["
- + connectToType + "] trail = [" + incomingTrail + "].";
- throw new AAIException("AAI_6132", msg);
- }
-
- for( Map.Entry<String, Object> entry : elementHash.entrySet() ){
- Vertex elVert = (Vertex)(entry.getValue());
- String tmpElVid = elVert.id().toString();
- String tmpElNT = getModElementWidgetType( elVert, thisGuysTrail );
- check4EdgeRule(tmpElNT, thisElementNodeType);
- if( !vidsTraversed.contains(tmpElVid) ){
- // This is one we would like to use - so we'll recursively get it's result set to add to ours
- Map<String, String> tmpHash = collectDeleteKeyHash( transId, fromAppId,
- elVert, thisGuysTrail,
- currentHash, vidsTraversed, levelCounter, modConstraintHash2Use,
- "", "" );
- thisHash.putAll(tmpHash);
- }
- }
- }
- }
- return thisHash;
-
- } // End of collectDeleteKeyHash()
-
-
- /**
- * Gets the linkage connect node types.
- *
- * @param linkagePtList the linkage pt list
- * @return the linkage connect node types
- * @throws AAIException the AAI exception
- */
- public Set<String> getLinkageConnectNodeTypes(List<String> linkagePtList )
- throws AAIException {
- // linkage points are a path from the top of a model to where we link in.
- // This method wants to just bring back a list of distinct last items.
- // Ie: for the input with these two: "pserver|lag-link|l-interface" and "pserver|p-interface|l-interface"
- // it would just return a single item, "l-interface" since both linkage points end in that same node-type.
-
- Set<String> linkPtSet = new HashSet<>();
-
- if( linkagePtList == null ){
- String detail = " Bad (null) linkagePtList passed to getLinkageConnectNodeTypes() ";
- throw new AAIException("AAI_6125", detail);
- }
-
- for( int i = 0; i < linkagePtList.size(); i++ ){
- String [] trailSteps = linkagePtList.get(i).split("\\|");
- if( trailSteps == null || trailSteps.length == 0 ){
- String detail = " Bad incomingTrail passed to getLinkageConnectNodeTypes(): [" + linkagePtList + "] ";
- throw new AAIException("AAI_6125", detail);
- }
- String lastStepNT = trailSteps[trailSteps.length - 1];
- linkPtSet.add(lastStepNT);
- }
-
- return linkPtSet;
-
- }// End getLinkageConnectNodeTypes()
-
-
- /**
- * Collect topology for model-ver.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param thisLevelElemVtx vertex to collect for
- * @param incomingTrail the incoming trail -- trail of nodeTypes/personaInfo that got us here (this vertex) from the top
- * @param currentMap the current map -- map that got us to this point (that we will use as the base of the map we will return)
- * @param vidsTraversed the vids traversed -- ArrayList of vertexId's that we traversed to get to this point
- * @param levelCounter the level counter
- * @param modConstraintHash the mod constraint hash
- * @param overRideModelInvId the override model-invariant-id
- * @param overRideModelVersionId the override model-version-id
- * @return Map of the topology
- * @throws AAIException the AAI exception
- */
- public Multimap<String, String> collectTopology4ModelVer(String transId, String fromAppId,
- Vertex thisLevelElemVtx, String incomingTrail,
- Multimap<String,String> currentMap, List<String> vidsTraversed,
- int levelCounter, Map<String, Vertex> modConstraintHash,
- String overRideModelInvId, String overRideModelVersionId )
- throws AAIException {
-
- levelCounter++;
-
- Multimap<String, String> thisMap = ArrayListMultimap.create();
- thisMap.putAll(currentMap);
-
- if( levelCounter > MAX_LEVELS ) {
- throw new AAIException("AAI_6125", "collectTopology4ModelVer() has looped across more levels than allowed: " + MAX_LEVELS + ". ");
- }
- String thisGuysTrail = "";
- String thisElemVid = thisLevelElemVtx.id().toString();
- Map<String, Vertex> modConstraintHash2Use = null;
-
- // If this element represents a resource or service model, then we will replace this element with
- // the "top" element of that resource or service model. That model-element already points to its
- // topology, so it will graft in that model's topology.
- // EXCEPT - if this element defines "linkage-points" defined, then we need to do some extra
- // processing for how we join to that model.
-
- // Find out what widget-model (and thereby what aai-node-type) this element represents.
- // Even if this element is pointing to a service or resource model, it must have a
- // first element which is a single widget-type model.
- String firstElementModelInfo = "";
- String thisElementNodeType = getModElementWidgetType( thisLevelElemVtx, incomingTrail );
- if( nodeTypeSupportsPersona(thisElementNodeType) && overRideModelInvId != null && !overRideModelInvId.equals("") ){
- firstElementModelInfo = "," + overRideModelInvId + "," + overRideModelVersionId;
- }
-
- Vertex elementVtxForThisLevel = null;
- Vertex thisElementsModelVerVtx = getModelVerThatElementRepresents( thisLevelElemVtx, incomingTrail );
- String subModelFirstModInvId = "";
- String subModelFirstModVerId = "";
- String modInfo4Trail = "";
- String modType = getModelTypeFromModelVer( thisElementsModelVerVtx, incomingTrail );
- if( modType.equals("resource") || modType.equals("service") ){
- // For an element that is referring to a resource or service model, we replace this
- // this element with the "top" element for that resource/service model so that the
- // topology of that resource/service model gets included in this topology.
- // -- Note - since that top element of a service or resource model will point to a widget model,
- // we have to track what modelId/version it really maps so we can make our recursive call
- Vertex thisElementsModelVtx = getModelGivenModelVer(thisElementsModelVerVtx, incomingTrail);
- subModelFirstModInvId = thisElementsModelVtx.<String>property("model-invariant-id").orElse(null);
- subModelFirstModVerId = thisElementsModelVerVtx.<String>property("model-version-id").orElse(null);
-
- if( nodeTypeSupportsPersona(thisElementNodeType) ){
- modInfo4Trail = "," + subModelFirstModInvId + "," + subModelFirstModVerId;
- }
- String modelVerId = thisElementsModelVerVtx.<String>property("model-version-id").orElse(null);
- if( subModelFirstModInvId == null || subModelFirstModInvId.equals("") || subModelFirstModVerId == null || subModelFirstModVerId.equals("") ){
- throw new AAIException("AAI_6132", "Bad Model Definition: Bad model-invariant-id or model-version-id. Model-ver-id = " + modelVerId);
- }
-
- elementVtxForThisLevel = getTopElementForSvcOrResModelVer(thisElementsModelVerVtx, incomingTrail);
- modConstraintHash2Use = getModConstraintHash( thisLevelElemVtx, modConstraintHash );
- }
- else {
- elementVtxForThisLevel = thisLevelElemVtx;
- }
-
- if( incomingTrail.equals("") ){
- // This is the first one
- thisGuysTrail = thisElementNodeType + firstElementModelInfo;
- }
- else {
- thisGuysTrail = incomingTrail + "|" + thisElementNodeType + modInfo4Trail;
- }
-
- // We only want to ensure that a particular element does not repeat on a single "branch".
- // It could show up on other branches in the case where it is a sub-model which is being
- // used in more than one place.
- //
- List<String> thisTrailsVidsTraversed = new ArrayList<>(vidsTraversed);
- thisTrailsVidsTraversed.add(thisElemVid);
-
- // Look at the elements pointed to at this level and add on their data
- Iterator<Vertex> vertI = this.traverseIncidentEdges(EdgeType.TREE, elementVtxForThisLevel, "model-element", "constrained-element-set");
-
- while( vertI != null && vertI.hasNext() ){
- Vertex tmpVert = vertI.next();
- String vid = tmpVert.id().toString();
- Map<String,Object> elementHash = new HashMap<>();
- String connectToType = tmpVert.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- if( connectToType != null && connectToType.equals("model-element") ){
- // A nice, regular old model-element
- elementHash.put(vid, tmpVert);
- }
- else if( (connectToType != null) && connectToType.equals("constrained-element-set") ){
- // translate the constrained-element-set into a hash of model-element Vertex's
- String constrainedElementSetUuid = tmpVert.<String>property("constrained-element-set-uuid").orElse(null);
- if( (modConstraintHash2Use != null) && modConstraintHash2Use.containsKey(constrainedElementSetUuid) ){
- // This constrained-element-set is being superseded by a different one
- Vertex replacementConstraintVert = modConstraintHash.get(constrainedElementSetUuid);
- elementHash = getNextStepElementsFromSet( replacementConstraintVert );
- // Now that we've found and used the replacement constraint, we don't need to carry it along any farther
- modConstraintHash.remove(constrainedElementSetUuid);
- }
- else {
- elementHash = getNextStepElementsFromSet( tmpVert );
- }
- }
- else {
- String msg = " model element has [connectedTo] edge to improper nodeType= ["
- + connectToType + "] trail = [" + incomingTrail + "].";
- throw new AAIException("AAI_6132", msg);
- }
-
- for( Map.Entry<String, Object> entry : elementHash.entrySet() ){
- Vertex elVert = (Vertex)(entry.getValue());
- String tmpElVid = elVert.id().toString();
- String tmpElNT = getModElementWidgetType( elVert, thisGuysTrail );
- String tmpElStepName = getModelElementStepName( elVert, thisGuysTrail);
-
- List<String> linkagePtList = new ArrayList <>();
- Iterator <VertexProperty<Object>> vpI = elVert.properties("linkage-points");
-
- // I am not sure why, but since "linkage-points" is an xml-element-wrapper in the OXM definition,
- // we get back the whole array of Strings in one String - but still use the "vtx.properties()" to
- // get it - but only look at the first thing returned by the iterator.
- if( vpI.hasNext() ){
- String tmpLinkageThing = (String)vpI.next().value();
- linkagePtList = makeSureItsAnArrayList( tmpLinkageThing );
- }
-
- if( linkagePtList != null && !linkagePtList.isEmpty() ){
- // This is as far as we can go, we will use the linkage point info to define the
- // rest of this "trail"
- for( int i = 0; i < linkagePtList.size(); i++ ){
- Multimap<String, String> tmpMap = collectTopology4LinkagePoint( transId, fromAppId,
- linkagePtList.get(i), thisGuysTrail, currentMap);
- thisMap.putAll(tmpMap);
- }
- }
- else {
- check4EdgeRule(tmpElNT, thisElementNodeType);
- thisMap.put(thisGuysTrail, tmpElStepName);
- if( !thisTrailsVidsTraversed.contains(tmpElVid) ){
- // This is one we would like to use - so we'll recursively get it's result set to add to ours
- Multimap<String, String> tmpMap = collectTopology4ModelVer( transId, fromAppId,
- elVert, thisGuysTrail,
- currentMap, thisTrailsVidsTraversed, levelCounter,
- modConstraintHash2Use, subModelFirstModInvId, subModelFirstModVerId );
- thisMap.putAll(tmpMap);
- }
- else {
- String modelElementUuid = elVert.<String>property("model-element-uuid").orElse(null);
- String msg = "Bad Model Definition: looping model-element (model-element-uuid = [" +
- modelElementUuid + "]) found trying to add step: [" + tmpElStepName + "], " +
- " on trail = [" + thisGuysTrail + "]. ";
- System.out.println( msg );
- throw new AAIException("AAI_6132", msg);
- }
- }
- }
- }
-
- return thisMap;
-
- } // End of collectTopology4ModelVer()
-
-
- /**
- * Check 4 edge rule.
- *
- * @param nodeTypeA the node type A
- * @param nodeTypeB the node type B
- * @throws AAIException the AAI exception
- */
- public void check4EdgeRule( String nodeTypeA, String nodeTypeB) throws AAIException {
- // Throw an exception if there is no defined edge rule for this combination of nodeTypes in DbEdgeRules.
-
- final EdgeIngestor edgeRules = SpringContextAware.getApplicationContext().getBean(EdgeIngestor.class);
- //final EdgeRules edgeRules = EdgeRules.getInstance();
-
- EdgeRuleQuery.Builder baseQ = new EdgeRuleQuery.Builder(nodeTypeA, nodeTypeB);
- if (!edgeRules.hasRule(baseQ.build())) {
-
-
- /* if( !edgeRules.hasEdgeRule(nodeTypeA, nodeTypeB)
- && !edgeRules.hasEdgeRule(nodeTypeB, nodeTypeA) ){*/
- // There's no EdgeRule for this -- find out if one of the nodeTypes is invalid or if
- // they are valid, but there's just no edgeRule for them.
- try {
- loader.introspectorFromName(nodeTypeA);
- } catch (AAIUnknownObjectException e) {
- String emsg = " Unrecognized nodeType aa [" + nodeTypeA + "]\n";
- throw new AAIException("AAI_6115", emsg);
- }
- try {
- loader.introspectorFromName(nodeTypeB);
- } catch (AAIUnknownObjectException e) {
- String emsg = " Unrecognized nodeType bb [" + nodeTypeB + "]\n";
- throw new AAIException("AAI_6115", emsg);
- }
-
- String msg = " No Edge Rule found for this pair of nodeTypes (order does not matter) ["
- + nodeTypeA + "], [" + nodeTypeB + "].";
- throw new AAIException("AAI_6120", msg);
- }
-
-
- }
-
-
- /**
- * Collect topology 4 linkage point.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param linkagePointStrVal -- Note it is in reverse order from where we connect to it.
- * @param incomingTrail -- trail of nodeTypes that got us here (this vertex) from the top
- * @param currentMap the current map -- that got us to this point (that we will use as the base of the map we will return)
- * @return Map of the topology
- * @throws AAIException the AAI exception
- */
- public Multimap<String, String> collectTopology4LinkagePoint(String transId, String fromAppId,
- String linkagePointStrVal, String incomingTrail, Multimap<String,String> currentMap)
- throws AAIException {
-
- Multimap<String, String> thisMap = ArrayListMultimap.create();
- thisMap.putAll(currentMap);
- String thisGuysTrail = incomingTrail;
-
- // NOTE - "trails" can have multiple parts now since we track persona info for some.
- // We just want to look at the node type info - which would be the piece
- // before any commas (if there are any).
-
- String [] trailSteps = thisGuysTrail.split("\\|");
- if(trailSteps.length == 0){
- throw new AAIException("AAI_6125", "Bad incomingTrail passed to collectTopology4LinkagePoint(): [" + incomingTrail + "] ");
- }
- String lastStepString = trailSteps[trailSteps.length - 1];
- String [] stepPieces = lastStepString.split(",");
- String lastStepNT = stepPieces[0];
-
- // It is assumed that the linkagePoint string will be a pipe-delimited string where each
- // piece is an AAIProperties.NODE_TYPE. For now, the first thing to connect to is what is on the farthest right.
- // Example: linkagePoint = "pserver|p-interface|l-interface" would mean that we're connecting to the l-interface
- // but that after that, we connect to a p-interface followed by a pserver.
- // It might have been more clear to define it in the other direction, but for now, that is it. (16-07)
- String linkagePointStr = linkagePointStrVal;
-
- // We are getting these with more than linkage thing in one string.
- // Ie. "pserver|lag-interface|l-interface, pserver|p-interface|l-interface, vlan|l-interface"
- linkagePointStr = linkagePointStr.replace("[", "");
- linkagePointStr = linkagePointStr.replace("]", "");
- linkagePointStr = linkagePointStr.replace(" ", "");
-
- String [] linkage = linkagePointStr.split("\\,");
- for( int x = 0; x < linkage.length; x++ ){
- lastStepNT = stepPieces[0];
- String thisStepNT = "";
- String [] linkageSteps = linkage[x].split("\\|");
- if(linkageSteps.length == 0){
- throw new AAIException("AAI_6125", "Bad linkagePointStr passed to collectTopology4LinkagePoint(): [" + linkagePointStr + "] ");
- }
- for( int i=(linkageSteps.length - 1); i >= 0; i-- ){
- thisStepNT = linkageSteps[i];
- check4EdgeRule(lastStepNT, thisStepNT);
- thisMap.put(thisGuysTrail, thisStepNT);
- thisGuysTrail = thisGuysTrail + "|" + thisStepNT;
- lastStepNT = thisStepNT;
- }
- }
- return thisMap;
-
- } // End of collectTopology4LinkagePoint()
-
-
- /**
- * Gets the next step elements from set.
- *
- * @param constrElemSetVtx the constr elem set vtx
- * @return Hash of the set of model-elements this set represents
- * @throws AAIException the AAI exception
- */
- public Map<String,Object> getNextStepElementsFromSet( Vertex constrElemSetVtx )
- throws AAIException {
- // Take a constrained-element-set and figure out the total set of all the possible elements that it
- // represents and return them as a Hash.
-
- Map<String,Object> retElementHash = new HashMap<>();
-
- if( constrElemSetVtx == null ){
- String msg = " getNextStepElementsFromSet() called with null constrElemSetVtx ";
- throw new AAIException("AAI_6125", msg);
- }
-
- String constrNodeType = constrElemSetVtx.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- String constrElemSetUuid = constrElemSetVtx.<String>property("constrained-element-set-uuid").orElse(null);
- if( constrNodeType == null || !constrNodeType.equals("constrained-element-set") ){
- String msg = " getNextStepElementsFromSet() called with wrong type model: [" + constrNodeType + "]. ";
- throw new AAIException("AAI_6125", msg);
- }
-
- ArrayList <Vertex> choiceSetVertArray = new ArrayList<>();
- Iterator<Vertex> vertI = this.traverseIncidentEdges(EdgeType.TREE, constrElemSetVtx, "element-choice-set");
- int setCount = 0;
- while( vertI != null && vertI.hasNext() ){
- Vertex choiceSetVertex = vertI.next();
- String constrSetType = choiceSetVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- if( constrSetType != null && constrSetType.equals("element-choice-set") ){
- choiceSetVertArray.add(choiceSetVertex);
- setCount++;
- }
- }
-
- if( setCount == 0 ){
- String msg = "No element-choice-set found under constrained-element-set-uuid = " + constrElemSetUuid;
- throw new AAIException("AAI_6132", msg);
- }
-
- // Loop through each choice-set and grab the model-elements
- for( int i = 0; i < setCount; i++ ){
- Vertex choiceSetVert = choiceSetVertArray.get(i);
- Iterator<Vertex> mVertI = this.traverseIncidentEdges(EdgeType.TREE, choiceSetVert, "model-element");
- int elCount = 0;
- while( mVertI != null && mVertI.hasNext() ){
- Vertex tmpElVertex = mVertI.next();
- String elNodeType = tmpElVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- if( elNodeType != null && elNodeType.equals("model-element") ){
- String tmpVid = tmpElVertex.id().toString();
- retElementHash.put(tmpVid, tmpElVertex);
- elCount++;
- }
- else {
- // unsupported node type found for this choice-set
- String msg = "Unsupported nodeType (" + elNodeType
- + ") found under choice-set under constrained-element-set-uuid = " + constrElemSetUuid;
- throw new AAIException("AAI_6132", msg);
- }
- }
-
- if( elCount == 0 ){
- String msg = "No model-elements found in choice-set under constrained-element-set-uuid = " + constrElemSetUuid;
- throw new AAIException("AAI_6132", msg);
- }
-
- }
- return retElementHash;
-
- } // End of getNextStepElementsFromSet()
-
-
-
- /**
- * Gen topo map 4 named Q.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param queryVertex the query vertex
- * @param namedQueryUuid the named query uuid
- * @return MultiMap of valid next steps for each potential query-element
- * @throws AAIException the AAI exception
- */
- public Multimap<String, String> genTopoMap4NamedQ(String transId, String fromAppId,
- Vertex queryVertex, String namedQueryUuid )
- throws AAIException {
-
- if( queryVertex == null ){
- throw new AAIException("AAI_6125", "null queryVertex passed to genTopoMap4NamedQ()");
- }
-
- Multimap<String, String> initialEmptyMap = ArrayListMultimap.create();
- List<String> vidsTraversed = new ArrayList<>();
-
- Vertex firstElementVertex = null;
- Iterator<Vertex> vertI = this.traverseIncidentEdges(EdgeType.TREE, queryVertex, "named-query-element");
- int elCount = 0;
- while( vertI != null && vertI.hasNext() ){
- elCount++;
- firstElementVertex = vertI.next();
- }
-
- if( elCount > 1 ){
- throw new AAIException("AAI_6133", "Illegal query defined: More than one first element defined for = " + namedQueryUuid);
- }
-
- if( firstElementVertex == null ){
- throw new AAIException("AAI_6114", "Could not find first query element = " + namedQueryUuid);
- }
-
- Vertex modVtx = getModelThatNqElementRepresents( firstElementVertex, "" );
- String modelType = getModelTypeFromModel( modVtx, "" );
- if( ! modelType.equals("widget") ){
- throw new AAIException("AAI_6133", "Bad Named Query Definition: First element must correspond to a widget type model. Named Query UUID = "
- + namedQueryUuid);
- }
-
- return collectTopology4NamedQ( transId, fromAppId,
- firstElementVertex, "",
- initialEmptyMap, vidsTraversed, 0);
- } // End of genTopoMap4NamedQ()
-
-
-
- /**
- * Collect topology 4 named Q.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param thisLevelElemVtx the model element vertex for this level
- * @param levelCounter the level counter
- * @return resultSet
- * @throws AAIException the AAI exception
- */
- public Multimap<String, String> collectTopology4NamedQ(String transId, String fromAppId,
- Vertex thisLevelElemVtx, String incomingTrail,
- Multimap<String,String> currentMap, List<String> vidsTraversed, int levelCounter )
- throws AAIException {
-
- levelCounter++;
-
- Multimap<String, String> thisMap = ArrayListMultimap.create();
- thisMap.putAll(currentMap);
-
- String thisElemVid = thisLevelElemVtx.id().toString();
- if( levelCounter > MAX_LEVELS ) {
- throw new AAIException("AAI_6125", "collectModelStructure() has looped across more levels than allowed: " + MAX_LEVELS + ". ");
- }
- String thisGuysTrail = "";
-
- // find out what widget (and thereby what aai-node-type) this element represents
- String thisElementNodeType = getNqElementWidgetType( transId, fromAppId, thisLevelElemVtx, incomingTrail );
-
- if( incomingTrail.equals("") ){
- // This is the first one
- thisGuysTrail = thisElementNodeType;
- }
- else {
- thisGuysTrail = incomingTrail + "|" + thisElementNodeType;
- }
-
- vidsTraversed.add(thisElemVid);
-
- // Look at the elements pointed to at this level and add on their data
- Iterator<Vertex> vertI = this.traverseIncidentEdges(EdgeType.TREE, thisLevelElemVtx, "named-query-element");
- while( vertI != null && vertI.hasNext() ){
- Vertex tmpVert = vertI.next();
- String tmpVid = tmpVert.id().toString();
- String tmpElNT = getNqElementWidgetType( transId, fromAppId, tmpVert, thisGuysTrail );
- thisMap.put(thisGuysTrail, tmpElNT);
- if( !vidsTraversed.contains(tmpVid) ){
- // This is one we would like to use - so we'll recursively get it's result set to add to ours
- Multimap<String, String> tmpMap = collectTopology4NamedQ( transId, fromAppId,
- tmpVert, thisGuysTrail,
- currentMap, vidsTraversed, levelCounter);
- thisMap.putAll(tmpMap);
- }
- }
-
- return thisMap;
-
- } // End of collectTopology4NamedQ()
-
-
- /**
- * Gets the model that NamedQuery element represents.
- *
- * @param elementVtx the NQ element vtx
- * @param elementTrail the element trail
- * @return the model that element represents
- * @throws AAIException the AAI exception
- */
- public Vertex getModelThatNqElementRepresents(Vertex elementVtx, String elementTrail )
- throws AAIException {
-
- // Get the model that a named-query element represents
- Vertex modVtx = null;
- Iterator<Vertex> mvertI = this.traverseIncidentEdges(EdgeType.COUSIN, elementVtx, "model");
- int modCount = 0;
- while( mvertI != null && mvertI.hasNext() ){
- modCount++;
- modVtx = mvertI.next();
- }
-
- if( modCount > 1 ){
- String msg = "Illegal element defined: More than one model pointed to by a single named-query-element at [" +
- elementTrail + "].";
- throw new AAIException("AAI_6125", msg);
- }
-
- if( modVtx == null ){
- String msg = "Bad named-query definition: Could not find model for element. ";
- if( !elementTrail.equals("") ){
- msg = "Bad named-query definition: Could not find model for named-query-element at [" + elementTrail + "].";
- }
- throw new AAIException("AAI_6132", msg);
- }
-
- String nodeType = modVtx.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- if( (nodeType != null) && nodeType.equals("model") ){
- return modVtx;
- }
- else {
- String msg = "Illegal Named Query element defined: expecting a 'model', but found 'isA' edge pointing to nodeType = " +
- nodeType + "] at [" + elementTrail + "].";
- throw new AAIException("AAI_6125", msg);
- }
-
- }// getModelThatNqElementRepresents()
-
-
- /**
- * Gets the model-ver that element represents.
- *
- * @param elementVtx the element vtx
- * @param elementTrail the element trail
- * @return the model-ver that element represents
- * @throws AAIException the AAI exception
- */
- public Vertex getModelVerThatElementRepresents(Vertex elementVtx, String elementTrail )
- throws AAIException {
-
- // Get the model-ver that an element represents
- Vertex modVerVtx = null;
- Iterator<Vertex> mvertI = this.traverseIncidentEdges(EdgeType.COUSIN, elementVtx, "model-ver");
- int modCount = 0;
- while( mvertI != null && mvertI.hasNext() ){
- modCount++;
- modVerVtx = mvertI.next();
- }
-
- if( modCount > 1 ){
- String msg = "Illegal element defined: More than one model pointed to by a single element at [" +
- elementTrail + "].";
- throw new AAIException("AAI_6125", msg);
- }
-
- if( modVerVtx == null ){
- String msg = "Bad model definition: Could not find model-ver for model-element. ";
- if( !elementTrail.equals("") ){
- msg = "Bad model definition: Could not find model-VER for model-element at [" + elementTrail + "].";
- }
- throw new AAIException("AAI_6132", msg);
- }
-
- String nodeType = modVerVtx.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- if( (nodeType != null) && nodeType.equals("model-ver") ){
- return modVerVtx;
- }
- else {
- String msg = "Illegal model-element defined: expecting a 'model-ver', but found 'isA' edge pointing to nodeType = " +
- nodeType + "] at [" + elementTrail + "].";
- throw new AAIException("AAI_6125", msg);
- }
-
- }// getModelVerThatElementRepresents()
-
-
-
- /**
- * Gets the model that is parent to model-ver node.
- *
- * @param modVerVtx the model-ver vtx
- * @param elementTrail the element trail
- * @return the model that element represents
- * @throws AAIException the AAI exception
- */
- public Vertex getModelGivenModelVer(Vertex modVerVtx, String elementTrail )
- throws AAIException {
-
- // Get the parent model for this "model-ver" node
- Vertex modVtx = null;
- Iterator<Vertex> mvertI = this.traverseIncidentEdges(EdgeType.TREE, modVerVtx, "model");
- int modCount = 0;
- while( mvertI != null && mvertI.hasNext() ){
- modCount++;
- modVtx = mvertI.next();
- }
-
- if( modCount > 1 ){
- String msg = "Illegal model-ver node defined: More than one model points to it with a 'has' edge [" +
- elementTrail + "].";
- throw new AAIException("AAI_6125", msg);
- }
-
- if( modVtx == null ){
- String msg = "Bad model-ver node: Could not find parent model. ";
- if( !elementTrail.equals("") ){
- msg = "Bad model-ver node: Could not find parent model. [" + elementTrail + "].";
- }
- throw new AAIException("AAI_6132", msg);
- }
-
- String nodeType = modVtx.<String>property(AAIProperties.NODE_TYPE).orElse(null);
- if( (nodeType != null) && nodeType.equals("model") ){
- // Found what we were looking for.
- return modVtx;
- }
- else {
- // Something is amiss
- String msg = " Could not find parent model node for model-ver node at [" +
- elementTrail + "].";
- throw new AAIException("AAI_6125", msg);
- }
-
-
- }// getModelGivenModelVer()
-
-
-
- /**
- * Gets the model type.
- *
- * @param modelVtx the model vtx
- * @param elementTrail the element trail
- * @return the model type
- * @throws AAIException the AAI exception
- */
- public String getModelTypeFromModel(Vertex modelVtx, String elementTrail )
- throws AAIException {
-
- // Get the model-type from a model vertex
- if( modelVtx == null ){
- String msg = " null modelVtx passed to getModelTypeFromModel() ";
- throw new AAIException("AAI_6114", msg);
- }
-
- String modelType = modelVtx.<String>property("model-type").orElse(null);
- if( (modelType == null) || modelType.equals("") ){
- String msg = "Could not find model-type for model encountered at [" + elementTrail + "].";
- throw new AAIException("AAI_6132", msg);
- }
-
- if( !modelType.equals("widget") && !modelType.equals("resource") && !modelType.equals("service") ){
- String msg = "Unrecognized model-type, [" + modelType + "] for model pointed to by element at [" + elementTrail + "].";
- throw new AAIException("AAI_6132", msg);
- }
-
- return modelType;
-
- }// getModelTypeFromModel()
-
-
-
- /**
- * Gets the model type given model-ver
- *
- * @param modelVerVtx the model-ver vtx
- * @param elementTrail the element trail
- * @return the model type
- * @throws AAIException the AAI exception
- */
- public String getModelTypeFromModelVer(Vertex modelVerVtx, String elementTrail )
- throws AAIException {
-
- // Get the model-type given a model-ver vertex
- if( modelVerVtx == null ){
- String msg = " null modelVerVtx passed to getModelTypeFromModelVer() ";
- throw new AAIException("AAI_6114", msg);
- }
-
- Vertex modVtx = getModelGivenModelVer( modelVerVtx, elementTrail );
- String modelType = modVtx.<String>property("model-type").orElse(null);
- if( (modelType == null) || modelType.equals("") ){
- String msg = "Could not find model-type for model encountered at [" + elementTrail + "].";
- throw new AAIException("AAI_6132", msg);
- }
-
- if( !modelType.equals("widget") && !modelType.equals("resource") && !modelType.equals("service") ){
- String msg = "Unrecognized model-type, [" + modelType + "] for model pointed to by element at [" + elementTrail + "].";
- throw new AAIException("AAI_6132", msg);
- }
-
- return modelType;
-
- }// getModelTypeFromModelVer()
-
-
-
- /**
- * Gets the model-element step name.
- *
- * @param elementVtx the model-element vtx
- * @param elementTrail the element trail
- * @return the element step name
- * @throws AAIException the AAI exception
- */
- public String getModelElementStepName(Vertex elementVtx, String elementTrail)
- throws AAIException {
-
- // Get the "step name" for a model-element
- // Step names look like this for widget-models: AAIProperties.NODE_TYPE
- // Step names look like this for resource/service models: "aai-node-type,model-invariant-id,model-version-id"
- // NOTE -- if the element points to a resource or service model, then we'll return the
- // widget-type of the first element (crown widget) for that model.
- String thisElementNodeType = "?";
- Vertex modVerVtx = getModelVerThatElementRepresents( elementVtx, elementTrail );
- String modelType = getModelTypeFromModelVer( modVerVtx, elementTrail );
-
- if( modelType == null ){
- String msg = " could not determine modelType in getModelElementStepName(). elementTrail = [" + elementTrail + "].";
- throw new AAIException("AAI_6132", msg);
- }
-
- if( modelType.equals("widget") ){
- // NOTE: for models that have model-type = "widget", their "model-name" maps directly to aai-node-type
- thisElementNodeType = modVerVtx.<String>property("model-name").orElse(null);
- if( (thisElementNodeType == null) || thisElementNodeType.equals("") ){
- String msg = "Could not find model-name for the widget model pointed to by element at [" + elementTrail + "].";
- throw new AAIException("AAI_6132", msg);
- }
- return thisElementNodeType;
- }
- else if( modelType.equals("resource") || modelType.equals("service") ){
- Vertex modVtx = getModelGivenModelVer( modVerVtx, elementTrail );
- String modInvId = modVtx.<String>property("model-invariant-id").orElse(null);
- String modVerId = modVerVtx.<String>property("model-version-id").orElse(null);
- Vertex relatedTopElementModelVtx = getTopElementForSvcOrResModelVer( modVerVtx, elementTrail );
- Vertex relatedModelVtx = getModelVerThatElementRepresents( relatedTopElementModelVtx, elementTrail );
- thisElementNodeType = relatedModelVtx.<String>property("model-name").orElse(null);
-
- if( (thisElementNodeType == null) || thisElementNodeType.equals("") ){
- String msg = "Could not find model-name for the widget model pointed to by element at [" + elementTrail + "].";
- throw new AAIException("AAI_6132", msg);
- }
-
- String stepName = "";
- if( nodeTypeSupportsPersona(thisElementNodeType) ){
- // This nodeType that this resource or service model refers to does support persona-related fields, so
- // we will use model-invariant-id and model-version-id as part of the step name.
- stepName = thisElementNodeType + "," + modInvId + "," + modVerId;
- }
- else {
- stepName = thisElementNodeType;
- }
- return stepName;
- }
- else {
- String msg = " Unrecognized model-type = [" + modelType + "] pointed to by element at [" + elementTrail + "].";
- throw new AAIException("AAI_6132", msg);
- }
-
- }// getModelElementStepName()
-
-
-
- /**
- * Node type supports persona.
- *
- * @param nodeType the node type
- * @return the boolean
- * @throws AAIException the AAI exception
- */
- public Boolean nodeTypeSupportsPersona(String nodeType)
- throws AAIException {
-
- if( nodeType == null || nodeType.equals("") ){
- return false;
- }
- Introspector introspector = null;
- try {
- introspector = loader.introspectorFromName(nodeType);
- } catch (AAIUnknownObjectException e) {
- String emsg = " Unrecognized nodeType [" + nodeType + "]\n";
- throw new AAIException("AAI_6115", emsg);
- }
-
- Collection <String> props4ThisNT = introspector.getProperties();
- return props4ThisNT.contains(addDBAliasedSuffix("model-invariant-id")) && props4ThisNT.contains(addDBAliasedSuffix("model-version-id"));
-
- }// nodeTypeSupportsPersona()
-
-
- /**
- * Gets a Named Query element's widget type.
- *
- * @param elementVtx the named-query element vtx
- * @param elementTrail the element trail
- * @return the element widget type
- * @throws AAIException the AAI exception
- */
- public String getNqElementWidgetType(String transId, String fromAppId,
- Vertex elementVtx, String elementTrail )
- throws AAIException {
-
- String thisNqElementWidgetType = "";
- // Get the associated node-type for the model pointed to by a named-query-element.
- // NOTE -- if the element points to a resource or service model, then we'll return the
- // widget-type of the first element (crown widget) for that model.
- Vertex modVtx = getModelThatNqElementRepresents( elementVtx, elementTrail );
- String modelType = getModelTypeFromModel( modVtx, elementTrail );
-
- if( modelType == null || !modelType.equals("widget") ){
- String emsg = " Model Type must be 'widget' for NamedQuery elements. Found [" + modelType + "] at [" +
- elementTrail + "]\n";
- throw new AAIException("AAI_6132", emsg);
- }
- else {
- // For a Widget model, the nodeType is just mapped to the model-element.model-name
- List<Vertex> modVerVtxArr = getModVersUsingModel(transId, fromAppId, modVtx);
- if( modVerVtxArr != null && !modVerVtxArr.isEmpty() ){
- thisNqElementWidgetType = (modVerVtxArr.get(0)).<String>property("model-name").orElse(null);
- }
- if( thisNqElementWidgetType == null || thisNqElementWidgetType.equals("") ){
- String emsg = " Widget type could not be determined at [" + elementTrail + "]\n";
- throw new AAIException("AAI_6132", emsg);
- }
- else {
- return thisNqElementWidgetType;
- }
- }
-
-
- }// End getNqElementWidgetType()
-
-
- /**
- * Gets a model-element's top widget type.
- *
- * @param elementVtx the model element vtx
- * @param elementTrail the element trail
- * @return the element widget type
- * @throws AAIException the AAI exception
- */
- public String getModElementWidgetType(Vertex elementVtx, String elementTrail )
- throws AAIException {
-
- // Get the associated node-type for the model-ver pointed to by a model-element.
- // NOTE -- if the element points to a resource or service model, then we'll return the
- // widget-type of the first element (crown widget) for that model.
- Vertex modVerVtx = getModelVerThatElementRepresents( elementVtx, elementTrail );
- return getModelVerTopWidgetType( modVerVtx, elementTrail );
-
- }// End getModElementWidgetType()
-
-
- /**
- * Gets the node using unique identifier
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param nodeType the nodeType
- * @param idPropertyName the property name of the unique identifier
- * @param uniqueIdVal the UUID value
- * @return unique vertex found using UUID
- * @throws AAIException the AAI exception
- */
- public Vertex getNodeUsingUniqueId(String transId, String fromAppId,
- String nodeType, String idPropertyName, String uniqueIdVal )
- throws AAIException {
-
- // Given a unique identifier, get the Vertex
- if( uniqueIdVal == null || uniqueIdVal.equals("") ){
- String emsg = " Bad uniqueIdVal passed to getNodeUsingUniqueId(): ["
- + uniqueIdVal + "]\n";
- throw new AAIException("AAI_6118", emsg);
- }
-
- if( idPropertyName == null || idPropertyName.equals("") ){
- String emsg = " Bad idPropertyName passed to getNodeUsingUniqueId(): ["
- + idPropertyName + "]\n";
- throw new AAIException("AAI_6118", emsg);
- }
-
- if( nodeType == null || nodeType.equals("") ){
- String emsg = " Bad nodeType passed to getNodeUsingUniqueId(): ["
- + nodeType + "]\n";
- throw new AAIException("AAI_6118", emsg);
- }
-
- Vertex uniqVtx = null;
- Iterable <?> uniqVerts = null;
- uniqVerts = engine.asAdmin().getReadOnlyTraversalSource().V().has(AAIProperties.NODE_TYPE,nodeType).has(idPropertyName,uniqueIdVal).toList();
- if( uniqVerts == null ){
- String emsg = "Node could not be found for nodeType = [" + nodeType
- + "], propertyName = [" + idPropertyName
- + "], propertyValue = [" + uniqueIdVal + "]\n";
- throw new AAIException("AAI_6114", emsg);
- }
- else {
- int count = 0;
- Iterator <?> uniqVertsIter = uniqVerts.iterator();
- if( !uniqVertsIter.hasNext() ){
- String emsg = "Node could not be found for nodeType = [" + nodeType
- + "], propertyName = [" + idPropertyName
- + "], propertyValue = [" + uniqueIdVal + "]\n";
- throw new AAIException("AAI_6114", emsg);
- }
- else {
- while( uniqVertsIter.hasNext() ){
- count++;
- uniqVtx = (Vertex) uniqVertsIter.next();
- if( count > 1 ){
- String emsg = "More than one node found for nodeType = [" + nodeType
- + "], propertyName = [" + idPropertyName
- + "], propertyValue = [" + uniqueIdVal + "]\n";
- throw new AAIException("AAI_6132", emsg);
- }
- }
- }
- }
-
- return uniqVtx;
- }// End getNodeUsingUniqueId()
-
-
- /**
- * Gets the model-ver nodes using name.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param modelName the model name
- * @return the model-ver's that use this name
- * @throws AAIException the AAI exception
- */
- public List<Vertex> getModelVersUsingName(String transId, String fromAppId,
- String modelName )
- throws AAIException {
-
- // Given a "model-name", find the model-ver vertices that this maps to
- if( modelName == null || modelName.equals("") ){
- String emsg = " Bad modelName passed to getModelVersUsingName(): ["
- + modelName + "]\n";
- throw new AAIException("AAI_6118", emsg);
- }
-
- List<Vertex> retVtxArr = new ArrayList<>();
- Iterator<Vertex> modVertsIter = this.engine.asAdmin().getReadOnlyTraversalSource().V().has(AAIProperties.NODE_TYPE,"model-ver").has("model-name",modelName);
- if( !modVertsIter.hasNext() ){
- String emsg = "Model-ver record(s) could not be found for model-ver data passed. model-name = [" +
- modelName + "]\n";
- throw new AAIException("AAI_6132", emsg);
- }
- else {
- while( modVertsIter.hasNext() ){
- Vertex tmpModelVerVtx = modVertsIter.next();
- retVtxArr.add(tmpModelVerVtx);
- }
- }
-
- return retVtxArr;
-
- }// End getModelVersUsingName()
-
-
- /**
- * Gets the model-ver nodes using model-invariant-id.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param modelInvId-invariant-id (uniquely identifies a model)
- * @return the model-ver's defined for the corresponding model
- * @throws AAIException the AAI exception
- */
- public Iterator<Vertex> getModVersUsingModelInvId(String transId, String fromAppId,
- String modelInvId )
- throws AAIException {
-
- // Given a "model-invariant-id", find the model-ver nodes that this maps to
- if( modelInvId == null || modelInvId.equals("") ){
- String emsg = " Bad model-invariant-id passed to getModVersUsingModelInvId(): ["
- + modelInvId + "]\n";
- throw new AAIException("AAI_6118", emsg);
- }
-
- Vertex modVtx = getNodeUsingUniqueId(transId, fromAppId, "model", "model-invariant-id", modelInvId);
- List<Vertex> retVtxArr = getModVersUsingModel(transId, fromAppId, modVtx);
- if( retVtxArr == null || retVtxArr.isEmpty() ){
- String emsg = " Model-ver record(s) could not be found attached to model with model-invariant-id = [" +
- modelInvId + "]\n";
- throw new AAIException("AAI_6132", emsg);
- }
-
- return retVtxArr.iterator();
- }// End getModVersUsingModelInvId()
-
-
- /**
- * Gets the model-ver nodes using a model node.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param modVtx vertex
- * @return the model-ver's defined for the corresponding model
- * @throws AAIException the AAI exception
- */
- public List<Vertex> getModVersUsingModel(String transId, String fromAppId,
- Vertex modVtx )
- throws AAIException {
-
- if( modVtx == null ){
- String emsg = " Null model vertex passed to getModVersUsingModel(): ";
- throw new AAIException("AAI_6118", emsg);
- }
-
- List<Vertex> retVtxArr = new ArrayList<>();
- Iterator<Vertex> modVerVertsIter = this.traverseIncidentEdges(EdgeType.TREE, modVtx, "model-ver");
- if(!modVerVertsIter.hasNext()){
- String modelInvId = modVtx.<String>property("model-invariant-id").orElse(null);
- String emsg = "Model-ver record(s) could not be found attached to model with model-invariant-id = [" +
- modelInvId + "]\n";
- throw new AAIException("AAI_6132", emsg);
- }
- else {
- while( modVerVertsIter.hasNext() ){
- Vertex tmpModelVtx = modVerVertsIter.next();
- retVtxArr.add(tmpModelVtx);
- }
- }
-
- return retVtxArr;
-
- }// End getModVersUsingModel()
-
- /**
- * Gets the model-version-ids using model-name.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param modelName the model name
- * @return the model uuids using name
- * @throws AAIException the AAI exception
- */
- public List<String> getModelVerIdsUsingName( String transId, String fromAppId,
- String modelName )
- throws AAIException {
-
- // Given a model-name find the model-ver nodes that it maps to
- if( modelName == null || modelName.equals("") ){
- String emsg = " Bad modelName passed to getModelVerIdsUsingName(): ["
- + modelName + "]\n";
- throw new AAIException("AAI_6118", emsg);
- }
-
- List<String> retArr = new ArrayList<>();
- Iterator<Vertex> modVerVertsIter = this.engine.asAdmin().getReadOnlyTraversalSource().V().has(AAIProperties.NODE_TYPE,"model-ver").has("model-name",modelName);
- if( !modVerVertsIter.hasNext() ){
- String emsg = " model-ver record(s) could not be found for model data passed. model-name = [" +
- modelName + "]\n";
- throw new AAIException("AAI_6114", emsg);
- }
- else {
- while( modVerVertsIter.hasNext() ){
- Vertex modelVerVtx = modVerVertsIter.next();
- String tmpUuid = modelVerVtx.<String>property("model-version-id").orElse(null);
- if( (tmpUuid != null) && !tmpUuid.equals("") && !retArr.contains(tmpUuid) ){
- retArr.add(tmpUuid);
- }
- }
- }
-
- if( retArr.isEmpty() ){
- String emsg = "No model-ver record found for model-name = ["
- + modelName + "]\n";
- throw new AAIException("AAI_6132", emsg);
- }
-
- return retArr;
- }// End getModelVerIdsUsingName()
-
-
- /**
- * Gets the model top widget type.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param modelVersionId the model-version-id
- * @param modelInvId the model-invariant-id
- * @param modelName the model-name
- * @return the model top widget type
- * @throws AAIException the AAI exception
- */
- public String getModelVerTopWidgetType( String transId, String fromAppId,
- String modelVersionId, String modelInvId, String modelName )
- throws AAIException {
-
- // Could be given a model-ver's key info (model-version-id), OR, just a (non-unique) model-name,
- // Or just a model-invariant-id (which could have multiple model-ver records under it).
- // In any case, they should only map to one single "top" node-type for the first element.
-
- String nodeType = "?";
- Iterator<Vertex> modVerVertsIter;
-
- if( modelVersionId != null && !modelVersionId.equals("") ){
- // this would be the best - we can just look up the model-ver records directly
- modVerVertsIter = this.engine.asAdmin().getReadOnlyTraversalSource().V().has(AAIProperties.NODE_TYPE,"model-ver").has("model-version-id",modelVersionId);
- }
- else if( modelName != null && !modelName.equals("") ){
- modVerVertsIter = this.engine.asAdmin().getReadOnlyTraversalSource().V().has(AAIProperties.NODE_TYPE,"model-ver").has("model-name",modelName);
- }
- else if( modelInvId != null && !modelInvId.equals("") ){
- modVerVertsIter = getModVersUsingModelInvId(transId, fromAppId, modelInvId);
- }
- else {
- String msg = "Neither modelVersionId, modelInvariantId, nor modelName passed to: getModelVerTopWidgetType() ";
- throw new AAIException("AAI_6120", msg);
- }
-
- if( !modVerVertsIter.hasNext() ){
- String emsg = "model-ver record(s) could not be found for model data passed: modelInvariantId = [" + modelInvId +
- "], modeVersionId = [" + modelVersionId + "], modelName = [" + modelName + "]\n";
- throw new AAIException("AAI_6114", emsg);
- }
- else {
- String lastNT = "";
- if( !modVerVertsIter.hasNext() ){
- String emsg = "model-ver record(s) could not be found for model data passed: modelInvariantId = [" + modelInvId +
- "], modeVersionId = [" + modelVersionId + "], modelName = [" + modelName + "]\n";
- throw new AAIException("AAI_6114", emsg);
- }
- while( modVerVertsIter.hasNext() ){
- Vertex tmpModVerVtx = modVerVertsIter.next();
- String tmpNT = getModelVerTopWidgetType( tmpModVerVtx, "" );
- if( lastNT != null && !lastNT.equals("") ){
- if( !lastNT.equals(tmpNT) ){
- String emsg = "Different top-node-types (" + tmpNT + ", " + lastNT
- + ") found for model data passed. (" +
- " modelVersionId = [" + modelVersionId +
- "], modelId = [" + modelInvId +
- "], modelName = [" + modelName +
- "])\n";
- throw new AAIException("AAI_6114", emsg);
- }
- }
- lastNT = tmpNT;
- nodeType = tmpNT;
- }
- }
-
- return nodeType;
-
- }// End getModelVerTopWidgetType()
-
-
- /**
- * Gets the widget type that this model-ver starts with.
- *
- * @param modVerVtx the model-version vtx
- * @param elementTrail the element trail
- * @return the widget type of the starting node of this model
- * @throws AAIException the AAI exception
- */
- public String getModelVerTopWidgetType(Vertex modVerVtx, String elementTrail )
- throws AAIException {
- // Get the associated nodeType (Ie. aai-node-type / widget-type) for a model-ver.
- // NOTE -- if the element points to a resource or service model, then we'll return the
- // widget-type of the first element (crown widget) for that model.
- String modelType = getModelTypeFromModelVer( modVerVtx, elementTrail );
- if( modelType == null ){
- String msg = " Could not determine modelType in getModelVerTopWidgetType(). elementTrail = [" + elementTrail + "].";
- throw new AAIException("AAI_6132", msg);
- }
-
- String thisElementNodeType = "?";
- if( modelType.equals("widget") ){
- // NOTE: for models that have model-type = "widget", their child model-ver nodes will
- // have "model-name" which maps directly to aai-node-type (all model-ver's under one
- // model should start with the same widget-type, so we only need to look at one).
- thisElementNodeType = modVerVtx.<String>property("model-name").orElse(null);
- if( (thisElementNodeType == null) || thisElementNodeType.equals("") ){
- String msg = "Could not find model-name for the widget model pointed to by element at [" + elementTrail + "].";
- throw new AAIException("AAI_6132", msg);
- }
- }
- else if( modelType.equals("resource") || modelType.equals("service") ){
- Vertex relatedTopElementVtx = getTopElementForSvcOrResModelVer( modVerVtx, elementTrail );
- Vertex relatedModVerVtx = getModelVerThatElementRepresents( relatedTopElementVtx, elementTrail );
- thisElementNodeType = relatedModVerVtx.<String>property("model-name").orElse(null);
- if( (thisElementNodeType == null) || thisElementNodeType.equals("") ){
- String msg = "Could not find model-name for the widget model pointed to by element at [" + elementTrail + "].";
- throw new AAIException("AAI_6132", msg);
- }
- }
- else {
- String msg = " Unrecognized model-type = [" + modelType + "] pointed to by element at [" + elementTrail + "].";
- throw new AAIException("AAI_6132", msg);
- }
-
- return thisElementNodeType;
-
- }// getModelVerTopWidgetType()
-
-
- /**
- * Validate model.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param modelVersionIdVal the model name version id
- * @param apiVersion the api version
- * @throws AAIException the AAI exception
- */
- public void validateModel(String transId, String fromAppId, String modelVersionIdVal, String apiVersion )
- throws AAIException {
-
- // Note - this will throw an exception if the model either can't be found, or if
- // we can't figure out its topology map.
- Vertex modelVerVtx = getNodeUsingUniqueId(transId, fromAppId, "model-ver",
- "model-version-id", modelVersionIdVal);
- if( modelVerVtx == null ){
- String msg = " Could not find model-ver with modelVersionId = [" + modelVersionIdVal + "].";
- throw new AAIException("AAI_6114", msg);
- }
- else {
- Multimap<String, String> topoMap = genTopoMap4ModelVer( transId, fromAppId,
- modelVerVtx, modelVersionIdVal);
- String msg = " modelVer [" + modelVersionIdVal + "] topo multiMap looks like: \n[" + topoMap + "]";
- System.out.println("INFO -- " + msg );
- }
- }// End validateModel()
-
-
- /**
- * Validate named query.
- *
- * @param transId the trans id
- * @param fromAppId the from app id
- * @param namedQueryUuid the named query uuid
- * @param apiVersion the api version
- * @throws AAIException the AAI exception
- */
- public void validateNamedQuery(String transId, String fromAppId, String namedQueryUuid, String apiVersion )
- throws AAIException {
-
- // Note - this will throw an exception if the named query either can't be found, or if
- // we can't figure out its topology map.
- Vertex nqVtx = getNodeUsingUniqueId(transId, fromAppId, "named-query",
- "named-query-uuid", namedQueryUuid);
-
- if( nqVtx == null ){
- String msg = " Could not find named-query with namedQueryUuid = [" + namedQueryUuid + "].";
- throw new AAIException("AAI_6114", msg);
- }
- else {
- //Multimap<String, String> topoMap = genTopoMap4NamedQ( "junkTransId", "junkFromAppId",
- // graph, nqVtx, namedQueryUuid );
- //System.out.println("DEBUG -- for test only : --- ");
- //System.out.println("DEBUG -- topomap = [" + topoMap + "]");
- }
-
- }// End validateNamedQuery()
-
-
- /**
- * Show result set.
- *
- * @param resSet the res set
- * @param levelCount the level count
- */
- public void showResultSet(ResultSet resSet, int levelCount ) {
-
- levelCount++;
- String propsStr = "";
- for( int i= 1; i <= levelCount; i++ ){
- propsStr = propsStr + "-";
- }
- if( resSet.getVert() == null ){
- return;
- }
- String nt = resSet.getVert().<String>property(AAIProperties.NODE_TYPE).orElse(null);
- propsStr = propsStr + "[" + nt + "] ";
-
- //propsStr = propsStr + " newDataDelFlag = " + resSet.getNewDataDelFlag() + ", trail = " + resSet.getLocationInModelSubGraph();
- //propsStr = propsStr + "limitDesc = [" + resSet.getPropertyLimitDesc() + "]";
- propsStr = propsStr + " trail = " + resSet.getLocationInModelSubGraph();
-
- Map<String,Object> overrideHash = resSet.getPropertyOverRideHash();
- if( overrideHash != null && !overrideHash.isEmpty() ){
- for( Map.Entry<String, Object> entry : overrideHash.entrySet() ){
- String propName = entry.getKey();
- Object propVal = entry.getValue();
- propsStr = propsStr + " [" + propName + " = " + propVal + "]";
- }
- }
- else {
- Iterator<VertexProperty<Object>> pI = resSet.getVert().properties();
- while( pI.hasNext() ){
- VertexProperty<Object> tp = pI.next();
- if( ! tp.key().startsWith("aai")
- && ! tp.key().equals("source-of-truth")
- //&& ! tp.key().equals("resource-version")
- && ! tp.key().startsWith("last-mod")
- )
- {
- propsStr = propsStr + " [" + tp.key() + " = " + tp.value() + "]";
- }
- }
- }
- // Show the "extra" lookup values too
- Map<String,Object> extraPropHash = resSet.getExtraPropertyHash();
- if( extraPropHash != null && !extraPropHash.isEmpty() ){
- for( Map.Entry<String, Object> entry : extraPropHash.entrySet() ){
- String propName = entry.getKey();
- Object propVal = entry.getValue();
- propsStr = propsStr + " [" + propName + " = " + propVal.toString() + "]";
- }
- }
-
- System.out.println( propsStr );
- logger.info(propsStr);
-
- if( !resSet.getSubResultSet().isEmpty() ){
- ListIterator<ResultSet> listItr = resSet.getSubResultSet().listIterator();
- while( listItr.hasNext() ){
- showResultSet( listItr.next(), levelCount );
- }
- }
-
- }// end of showResultSet()
-
- private Iterator<Vertex> traverseIncidentEdges(EdgeType treeType, Vertex startV, String connectedNodeType) throws AAIException {
- return this.engine.getQueryBuilder(startV).createEdgeTraversal(treeType, startV, loader.introspectorFromName(connectedNodeType));
- }
-
- private Iterator<Vertex> traverseIncidentEdges(EdgeType treeType, Vertex startV, String... connectedNodeType) throws AAIException {
- QueryBuilder[] builders = new QueryBuilder[connectedNodeType.length];
- for (int i = 0; i < connectedNodeType.length; i++) {
- builders[i] = this.engine.getQueryBuilder(startV).createEdgeTraversal(EdgeType.TREE, startV, loader.introspectorFromName(connectedNodeType[i]));
- }
- return this.engine.getQueryBuilder(startV).union(builders);
- }
-
- private String addDBAliasedSuffix(String propName) {
- return propName + AAIProperties.DB_ALIAS_SUFFIX;
- }
-
- protected String getPropNameWithAliasIfNeeded(String nodeType, String propName) throws AAIUnknownObjectException {
-
- String retPropName = propName;
- if( loader.introspectorFromName(nodeType).getPropertyMetadata(propName, PropertyMetadata.DB_ALIAS).isPresent() ){
- return propName + AAIProperties.DB_ALIAS_SUFFIX;
- }
- return retPropName;
- }
-
-}
+ + targetNodeType + "] propertyName = [" + srcProp + "], propVal = ["
+ + valFromInstance + "] so related-lookup is being abandoned.");
+ return retHash;
+ } else {
+ Vertex tmpVtx = result.get();
+ // Pick up the properties from the target vertex that they wanted us to get
+ for (int j = 0; j < propCollectList.size(); j++) {
+ String tmpPropName = propCollectList.get(j);
+ tmpPropName = getPropNameWithAliasIfNeeded(targetNodeType, tmpPropName);
+ Object valObj = tmpVtx.<Object>property(tmpPropName).orElse(null);
+ String lookupKey = targetNodeType + "." + tmpPropName;
+ retHash.put(lookupKey, valObj);
+
+ }
+ }
+ }
+
+ return retHash;
+
+ } // End of getNamedQueryExtraDataLookup()
+
+ /**
+ * Collect NQ element hash.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param thisLevelElemVtx the element verrtx for this level
+ * @param incomingTrail the incoming trail -- trail of nodeTypes that got us here (this
+ * nq-element vertex) from the top
+ * @param currentHash the current hash
+ * @param vidsTraversed the vids traversed -- ArrayList of vertexId's that we traversed to get
+ * to this point
+ * @param levelCounter the level counter
+ * @return HashMap of all widget-points on a namedQuery topology with the value being the
+ * "named-query-element-uuid" for that spot.
+ * @throws AAIException the AAI exception
+ */
+ public Map<String, String> collectNQElementHash(String transId, String fromAppId,
+ Vertex thisLevelElemVtx, String incomingTrail, Map<String, String> currentHash,
+ List<String> vidsTraversed, int levelCounter) throws AAIException {
+
+ levelCounter++;
+
+ Map<String, String> thisHash = new HashMap<>();
+ thisHash.putAll(currentHash);
+
+ if (levelCounter > MAX_LEVELS) {
+ throw new AAIException("AAI_6125",
+ "collectNQElementHash() has looped across more levels than allowed: " + MAX_LEVELS
+ + ". ");
+ }
+ String thisGuysTrail = "";
+ String thisElemVid = thisLevelElemVtx.id().toString();
+
+ // Find out what widget (and thereby what aai-node-type) this element represents.
+ String thisElementNodeType =
+ getNqElementWidgetType(transId, fromAppId, thisLevelElemVtx, incomingTrail);
+
+ if (incomingTrail == null || incomingTrail.equals("")) {
+ // This is the first one
+ thisGuysTrail = thisElementNodeType;
+ } else {
+ thisGuysTrail = incomingTrail + "|" + thisElementNodeType;
+ }
+ vidsTraversed.add(thisElemVid);
+
+ String nqElementUuid =
+ thisLevelElemVtx.<String>property("named-query-element-uuid").orElse(null);
+ if (nqElementUuid == null || nqElementUuid.equals("")) {
+ String msg = " named-query element UUID not found at trail = [" + incomingTrail + "].";
+ throw new AAIException("AAI_6133", msg);
+ }
+ thisHash.put(thisGuysTrail, nqElementUuid);
+
+ // Now go "down" and look at the sub-elements pointed to so we can get their data.
+ Iterator<Vertex> vertI =
+ this.traverseIncidentEdges(EdgeType.TREE, thisLevelElemVtx, "named-query-element");
+ while (vertI != null && vertI.hasNext()) {
+ Vertex tmpVert = vertI.next();
+ String vid = tmpVert.id().toString();
+ Map<String, Object> elementHash = new HashMap();
+
+ String connectToType = tmpVert.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ if (connectToType != null && connectToType.equals("named-query-element")) {
+ // This is what we would expect
+ elementHash.put(vid, tmpVert);
+ } else {
+ String msg = " named query element has [connectedTo] edge to improper nodeType= ["
+ + connectToType + "] trail = [" + incomingTrail + "].";
+ throw new AAIException("AAI_6133", msg);
+ }
+ for (Map.Entry<String, Object> entry : elementHash.entrySet()) {
+ Vertex elVert = (Vertex) (entry.getValue());
+ String tmpElVid = elVert.id().toString();
+ if (!vidsTraversed.contains(tmpElVid)) {
+ // This is one we would like to use - so we'll recursively get it's result set
+ // to add to ours
+ Map<String, String> tmpHash = collectNQElementHash(transId, fromAppId, elVert,
+ thisGuysTrail, currentHash, vidsTraversed, levelCounter);
+ thisHash.putAll(tmpHash);
+ }
+ }
+ }
+ return thisHash;
+
+ } // End of collectNQElementHash()
+
+ /**
+ * Collect delete key hash.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param thisLevelElemVtx the element vertex at this level
+ * @param incomingTrail the incoming trail -- trail of nodeTypes that got us here (this vertex)
+ * from the top
+ * @param currentHash the current hash
+ * @param vidsTraversed the vids traversed ---- ArrayList of vertexId's that we traversed to get
+ * to this point
+ * @param levelCounter the level counter
+ * @param modConstraintHash the mod constraint hash
+ * @param overRideModelId the over ride model id
+ * @param overRideModelVersionId the over ride model version id
+ * @return HashMap of all widget-points on a model topology with the value being the
+ * "newDataDelFlag" for that spot.
+ * @throws AAIException the AAI exception
+ */
+ public Map<String, String> collectDeleteKeyHash(String transId, String fromAppId,
+ Vertex thisLevelElemVtx, String incomingTrail, Map<String, String> currentHash,
+ List<String> vidsTraversed, int levelCounter, Map<String, Vertex> modConstraintHash,
+ String overRideModelId, String overRideModelVersionId) throws AAIException {
+
+ levelCounter++;
+
+ Map<String, String> thisHash = new HashMap<>();
+ thisHash.putAll(currentHash);
+
+ if (levelCounter > MAX_LEVELS) {
+ throw new AAIException("AAI_6125",
+ "collectDeleteKeyHash() has looped across more levels than allowed: " + MAX_LEVELS
+ + ". ");
+ }
+ String thisGuysTrail = "";
+ String thisElemVid = thisLevelElemVtx.id().toString();
+ Map<String, Vertex> modConstraintHash2Use = null;
+
+ // If this element represents a resource or service model, then we will replace this element
+ // with
+ // the "top" element of that resource or service model. That model-element already points to
+ // its
+ // topology, so it will graft in that model's topology.
+ // EXCEPT - if this element has "linkage-points" defined, then we need to do some extra
+ // processing for how we join to that model and will not try to go any "deeper".
+ List<String> linkagePtList = new ArrayList<>();
+ Iterator<VertexProperty<Object>> vpI = thisLevelElemVtx.properties("linkage-points");
+
+ // I am not sure why, but since "linkage-points" is an xml-element-wrapper in the OXM
+ // definition,
+ // we get back the whole array of Strings in one String - but still use the
+ // "vtx.properties()" to
+ // get it - but only look at the first thing returned by the iterator.
+ if (vpI.hasNext()) {
+ String tmpLinkageThing = (String) vpI.next().value();
+ linkagePtList = makeSureItsAnArrayList(tmpLinkageThing);
+ }
+
+ if (linkagePtList != null && !linkagePtList.isEmpty()) {
+ // Whatever this element is - we are connecting to it via a linkage-point
+ // We will figure out what to do and then return without going any deeper
+ String elemFlag = thisLevelElemVtx.<String>property("new-data-del-flag").orElse(null);
+
+ Set<String> linkageConnectNodeTypes = getLinkageConnectNodeTypes(linkagePtList);
+ Iterator<?> linkNtIter = linkageConnectNodeTypes.iterator();
+ String incTrail = "";
+ if (incomingTrail != null && !incomingTrail.equals("")) {
+ incTrail = incomingTrail + "|";
+ }
+
+ while (linkNtIter.hasNext()) {
+ // The 'trail' (or trails) for this element should just be the to the first-contact
+ // on the linkage point
+ String linkTrail = incTrail + linkNtIter.next();
+ Boolean alreadyTaggedFalse = false;
+ if (thisHash.containsKey(linkTrail) && thisHash.get(linkTrail).equals("F")) {
+ // some other path with a matching trail has the deleteFlag set to "F", so we do
+ // not want
+ // to override that since our model code only uses nodeTypes to know where it is
+ // - and we
+ // would rather do less deleting than needed instead of too much deleting.
+ alreadyTaggedFalse = true;
+ }
+ if (elemFlag != null && elemFlag.equals("T") && !alreadyTaggedFalse) {
+ // This trail should be marked with an "T"
+ thisHash.put(linkTrail, "T");
+ } else {
+ thisHash.put(linkTrail, "F");
+ }
+ }
+ return thisHash;
+ }
+
+ // ----------------------------------------------------------------------------
+ // If we got to here, then this was not an element that used a linkage-point
+ // ----------------------------------------------------------------------------
+
+ // Find out what widget-model (and thereby what aai-node-type) this element represents.
+ // Even if this element is pointing to a service or resource model, it must have a
+ // first element which is a single widget-type model.
+ String thisElementNodeType = getModElementWidgetType(thisLevelElemVtx, incomingTrail);
+ String firstElementModelInfo = "";
+
+ vidsTraversed.add(thisElemVid);
+ Vertex elementVtxForThisLevel = null;
+ Vertex thisElementsModelVerVtx =
+ getModelVerThatElementRepresents(thisLevelElemVtx, incomingTrail);
+ Vertex thisElementsModelVtx = getModelGivenModelVer(thisElementsModelVerVtx, incomingTrail);
+ String modType = getModelTypeFromModel(thisElementsModelVtx, incomingTrail);
+ String subModelFirstModInvId =
+ thisElementsModelVtx.<String>property("model-invariant-id").orElse(null);
+ String subModelFirstVerId =
+ thisElementsModelVerVtx.<String>property("model-version-id").orElse(null);
+ if (modType.equals("widget")) {
+ if (overRideModelId != null && !overRideModelId.equals("")) {
+ // Note - this is just to catch the correct model for the TOP node in a model since
+ // it will have an element which will always be a widget even though the model
+ // could be a resource or service model.
+ firstElementModelInfo = "," + overRideModelId + "," + overRideModelVersionId;
+ }
+ } else if (nodeTypeSupportsPersona(thisElementNodeType)) {
+ firstElementModelInfo = "," + subModelFirstModInvId + "," + subModelFirstVerId;
+ }
+
+ if (incomingTrail.equals("")) {
+ // This is the first one
+ thisGuysTrail = thisElementNodeType + firstElementModelInfo;
+ } else {
+ thisGuysTrail = incomingTrail + "|" + thisElementNodeType + firstElementModelInfo;
+ }
+
+ String tmpFlag = "F";
+ Boolean stoppedByASvcOrResourceModelElement = false;
+ if (modType.equals("widget")) {
+ elementVtxForThisLevel = thisLevelElemVtx;
+ // For the element-model for the widget at this level, record it's delete flag
+ tmpFlag = elementVtxForThisLevel.<String>property("new-data-del-flag").orElse(null);
+ } else {
+ // For an element that is referring to a resource or service model, we replace
+ // this element with the "top" element for that resource/service model so that the
+ // topology of that resource/service model will be included in this topology.
+ String modelVerId =
+ thisElementsModelVerVtx.<String>property("model-version-id").orElse(null);
+ if (subModelFirstModInvId == null || subModelFirstModInvId.equals("")
+ || subModelFirstVerId == null || subModelFirstVerId.equals("")) {
+ throw new AAIException("AAI_6132",
+ "Bad Model Definition: Bad model-invariant-id or model-version-id. Model-version-id = "
+ + modelVerId + ", at [" + incomingTrail + "]");
+ }
+
+ // BUT -- if the model-element HERE at the resource/service level does NOT have
+ // it's new-data-del-flag set to "T", then we do not need to go down into the
+ // sub-model looking for delete-able things.
+
+ tmpFlag = thisLevelElemVtx.<String>property("new-data-del-flag").orElse(null);
+ elementVtxForThisLevel =
+ getTopElementForSvcOrResModelVer(thisElementsModelVerVtx, thisGuysTrail);
+ if (tmpFlag != null && tmpFlag.equals("T")) {
+ modConstraintHash2Use = getModConstraintHash(thisLevelElemVtx, modConstraintHash);
+ } else {
+ stoppedByASvcOrResourceModelElement = true;
+ }
+ // For the element-model for the widget at this level, record it's delete flag
+ tmpFlag = elementVtxForThisLevel.<String>property("new-data-del-flag").orElse(null);
+ }
+
+ String flag2Use = "F"; // by default we'll use "F" for the delete flag
+ if (!stoppedByASvcOrResourceModelElement) {
+ // Since we haven't been stopped by a resource/service level "F", we can look at the
+ // lower level flag
+ if (thisHash.containsKey(thisGuysTrail)) {
+ // We've seen this spot in the topology before - do not override the delete flag if
+ // the older one is "F"
+ // We will only over-ride it if the old one was "T" and the new one is "F" (anything
+ // but "T")
+ String oldFlag = thisHash.get(thisGuysTrail);
+ if (oldFlag.equals("T") && (tmpFlag != null) && tmpFlag.equals("T")) {
+ // The old flag was "T" and the new flag is also "T"
+ flag2Use = "T";
+ } else {
+ // the old flag was not "F" - so don't override it
+ flag2Use = "F";
+ }
+ } else if ((tmpFlag != null) && tmpFlag.equals("T")) {
+ // We have not seen this one, so we can set it to "T" if that's what it is.
+ flag2Use = "T";
+ }
+ }
+
+ thisHash.put(thisGuysTrail, flag2Use);
+ if (!stoppedByASvcOrResourceModelElement) {
+ // Since we haven't been stopped by a resource/service level "F", we will continue to
+ // go "down" and look at the elements pointed to so we can get their data.
+ Iterator<Vertex> vertI = this.traverseIncidentEdges(EdgeType.TREE,
+ elementVtxForThisLevel, "model-element", "constrained-element-set");
+ while (vertI != null && vertI.hasNext()) {
+ Vertex tmpVert = vertI.next();
+ String vid = tmpVert.id().toString();
+ Map<String, Object> elementHash = new HashMap<>();
+
+ String connectToType =
+ tmpVert.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ if (connectToType != null && connectToType.equals("model-element")) {
+ // A nice, regular old model-element
+ elementHash.put(vid, tmpVert);
+ } else if ((connectToType != null)
+ && connectToType.equals("constrained-element-set")) {
+ // translate the constrained-element-set into a hash of model-element Vertex's
+ String constrainedElementSetUuid =
+ tmpVert.<String>property("constrained-element-set-uuid").orElse(null);
+ if ((modConstraintHash2Use != null)
+ && modConstraintHash2Use.containsKey(constrainedElementSetUuid)) {
+ // This constrained-element-set is being superseded by a different one
+ Vertex replacementConstraintVert =
+ modConstraintHash.get(constrainedElementSetUuid);
+ elementHash = getNextStepElementsFromSet(replacementConstraintVert);
+ // Now that we've found and used the replacement constraint, we don't need
+ // to carry it along any farther
+ modConstraintHash.remove(constrainedElementSetUuid);
+ } else {
+ elementHash = getNextStepElementsFromSet(tmpVert);
+ }
+ } else {
+ String msg = " model-element has [connectedTo] edge to improper nodeType= ["
+ + connectToType + "] trail = [" + incomingTrail + "].";
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ for (Map.Entry<String, Object> entry : elementHash.entrySet()) {
+ Vertex elVert = (Vertex) (entry.getValue());
+ String tmpElVid = elVert.id().toString();
+ String tmpElNT = getModElementWidgetType(elVert, thisGuysTrail);
+ check4EdgeRule(tmpElNT, thisElementNodeType);
+ if (!vidsTraversed.contains(tmpElVid)) {
+ // This is one we would like to use - so we'll recursively get it's result
+ // set to add to ours
+ Map<String, String> tmpHash = collectDeleteKeyHash(transId, fromAppId,
+ elVert, thisGuysTrail, currentHash, vidsTraversed, levelCounter,
+ modConstraintHash2Use, "", "");
+ thisHash.putAll(tmpHash);
+ }
+ }
+ }
+ }
+ return thisHash;
+
+ } // End of collectDeleteKeyHash()
+
+ /**
+ * Gets the linkage connect node types.
+ *
+ * @param linkagePtList the linkage pt list
+ * @return the linkage connect node types
+ * @throws AAIException the AAI exception
+ */
+ public Set<String> getLinkageConnectNodeTypes(List<String> linkagePtList) throws AAIException {
+ // linkage points are a path from the top of a model to where we link in.
+ // This method wants to just bring back a list of distinct last items.
+ // Ie: for the input with these two: "pserver|lag-link|l-interface" and
+ // "pserver|p-interface|l-interface"
+ // it would just return a single item, "l-interface" since both linkage points end in that
+ // same node-type.
+
+ Set<String> linkPtSet = new HashSet<>();
+
+ if (linkagePtList == null) {
+ String detail = " Bad (null) linkagePtList passed to getLinkageConnectNodeTypes() ";
+ throw new AAIException("AAI_6125", detail);
+ }
+
+ for (int i = 0; i < linkagePtList.size(); i++) {
+ String[] trailSteps = linkagePtList.get(i).split("\\|");
+ if (trailSteps == null || trailSteps.length == 0) {
+ String detail = " Bad incomingTrail passed to getLinkageConnectNodeTypes(): ["
+ + linkagePtList + "] ";
+ throw new AAIException("AAI_6125", detail);
+ }
+ String lastStepNT = trailSteps[trailSteps.length - 1];
+ linkPtSet.add(lastStepNT);
+ }
+
+ return linkPtSet;
+
+ }// End getLinkageConnectNodeTypes()
+
+ /**
+ * Collect topology for model-ver.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param thisLevelElemVtx vertex to collect for
+ * @param incomingTrail the incoming trail -- trail of nodeTypes/personaInfo that got us here
+ * (this vertex) from the top
+ * @param currentMap the current map -- map that got us to this point (that we will use as the
+ * base of the map we will return)
+ * @param vidsTraversed the vids traversed -- ArrayList of vertexId's that we traversed to get
+ * to this point
+ * @param levelCounter the level counter
+ * @param modConstraintHash the mod constraint hash
+ * @param overRideModelInvId the override model-invariant-id
+ * @param overRideModelVersionId the override model-version-id
+ * @return Map of the topology
+ * @throws AAIException the AAI exception
+ */
+ public Multimap<String, String> collectTopology4ModelVer(String transId, String fromAppId,
+ Vertex thisLevelElemVtx, String incomingTrail, Multimap<String, String> currentMap,
+ List<String> vidsTraversed, int levelCounter, Map<String, Vertex> modConstraintHash,
+ String overRideModelInvId, String overRideModelVersionId) throws AAIException {
+
+ levelCounter++;
+
+ Multimap<String, String> thisMap = ArrayListMultimap.create();
+ thisMap.putAll(currentMap);
+
+ if (levelCounter > MAX_LEVELS) {
+ throw new AAIException("AAI_6125",
+ "collectTopology4ModelVer() has looped across more levels than allowed: "
+ + MAX_LEVELS + ". ");
+ }
+ String thisGuysTrail = "";
+ String thisElemVid = thisLevelElemVtx.id().toString();
+ Map<String, Vertex> modConstraintHash2Use = null;
+
+ // If this element represents a resource or service model, then we will replace this element
+ // with
+ // the "top" element of that resource or service model. That model-element already points to
+ // its
+ // topology, so it will graft in that model's topology.
+ // EXCEPT - if this element defines "linkage-points" defined, then we need to do some extra
+ // processing for how we join to that model.
+
+ // Find out what widget-model (and thereby what aai-node-type) this element represents.
+ // Even if this element is pointing to a service or resource model, it must have a
+ // first element which is a single widget-type model.
+ String firstElementModelInfo = "";
+ String thisElementNodeType = getModElementWidgetType(thisLevelElemVtx, incomingTrail);
+ if (nodeTypeSupportsPersona(thisElementNodeType) && overRideModelInvId != null
+ && !overRideModelInvId.equals("")) {
+ firstElementModelInfo = "," + overRideModelInvId + "," + overRideModelVersionId;
+ }
+
+ Vertex elementVtxForThisLevel = null;
+ Vertex thisElementsModelVerVtx =
+ getModelVerThatElementRepresents(thisLevelElemVtx, incomingTrail);
+ String subModelFirstModInvId = "";
+ String subModelFirstModVerId = "";
+ String modInfo4Trail = "";
+ String modType = getModelTypeFromModelVer(thisElementsModelVerVtx, incomingTrail);
+ if (modType.equals("resource") || modType.equals("service")) {
+ // For an element that is referring to a resource or service model, we replace this
+ // this element with the "top" element for that resource/service model so that the
+ // topology of that resource/service model gets included in this topology.
+ // -- Note - since that top element of a service or resource model will point to a
+ // widget model,
+ // we have to track what modelId/version it really maps so we can make our recursive
+ // call
+ Vertex thisElementsModelVtx =
+ getModelGivenModelVer(thisElementsModelVerVtx, incomingTrail);
+ subModelFirstModInvId =
+ thisElementsModelVtx.<String>property("model-invariant-id").orElse(null);
+ subModelFirstModVerId =
+ thisElementsModelVerVtx.<String>property("model-version-id").orElse(null);
+
+ if (nodeTypeSupportsPersona(thisElementNodeType)) {
+ modInfo4Trail = "," + subModelFirstModInvId + "," + subModelFirstModVerId;
+ }
+ String modelVerId =
+ thisElementsModelVerVtx.<String>property("model-version-id").orElse(null);
+ if (subModelFirstModInvId == null || subModelFirstModInvId.equals("")
+ || subModelFirstModVerId == null || subModelFirstModVerId.equals("")) {
+ throw new AAIException("AAI_6132",
+ "Bad Model Definition: Bad model-invariant-id or model-version-id. Model-ver-id = "
+ + modelVerId);
+ }
+
+ elementVtxForThisLevel =
+ getTopElementForSvcOrResModelVer(thisElementsModelVerVtx, incomingTrail);
+ modConstraintHash2Use = getModConstraintHash(thisLevelElemVtx, modConstraintHash);
+ } else {
+ elementVtxForThisLevel = thisLevelElemVtx;
+ }
+
+ if (incomingTrail.equals("")) {
+ // This is the first one
+ thisGuysTrail = thisElementNodeType + firstElementModelInfo;
+ } else {
+ thisGuysTrail = incomingTrail + "|" + thisElementNodeType + modInfo4Trail;
+ }
+
+ // We only want to ensure that a particular element does not repeat on a single "branch".
+ // It could show up on other branches in the case where it is a sub-model which is being
+ // used in more than one place.
+ //
+ List<String> thisTrailsVidsTraversed = new ArrayList<>(vidsTraversed);
+ thisTrailsVidsTraversed.add(thisElemVid);
+
+ // Look at the elements pointed to at this level and add on their data
+ Iterator<Vertex> vertI = this.traverseIncidentEdges(EdgeType.TREE, elementVtxForThisLevel,
+ "model-element", "constrained-element-set");
+
+ while (vertI != null && vertI.hasNext()) {
+ Vertex tmpVert = vertI.next();
+ String vid = tmpVert.id().toString();
+ Map<String, Object> elementHash = new HashMap<>();
+ String connectToType = tmpVert.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ if (connectToType != null && connectToType.equals("model-element")) {
+ // A nice, regular old model-element
+ elementHash.put(vid, tmpVert);
+ } else if ((connectToType != null) && connectToType.equals("constrained-element-set")) {
+ // translate the constrained-element-set into a hash of model-element Vertex's
+ String constrainedElementSetUuid =
+ tmpVert.<String>property("constrained-element-set-uuid").orElse(null);
+ if ((modConstraintHash2Use != null)
+ && modConstraintHash2Use.containsKey(constrainedElementSetUuid)) {
+ // This constrained-element-set is being superseded by a different one
+ Vertex replacementConstraintVert =
+ modConstraintHash.get(constrainedElementSetUuid);
+ elementHash = getNextStepElementsFromSet(replacementConstraintVert);
+ // Now that we've found and used the replacement constraint, we don't need to
+ // carry it along any farther
+ modConstraintHash.remove(constrainedElementSetUuid);
+ } else {
+ elementHash = getNextStepElementsFromSet(tmpVert);
+ }
+ } else {
+ String msg = " model element has [connectedTo] edge to improper nodeType= ["
+ + connectToType + "] trail = [" + incomingTrail + "].";
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ for (Map.Entry<String, Object> entry : elementHash.entrySet()) {
+ Vertex elVert = (Vertex) (entry.getValue());
+ String tmpElVid = elVert.id().toString();
+ String tmpElNT = getModElementWidgetType(elVert, thisGuysTrail);
+ String tmpElStepName = getModelElementStepName(elVert, thisGuysTrail);
+
+ List<String> linkagePtList = new ArrayList<>();
+ Iterator<VertexProperty<Object>> vpI = elVert.properties("linkage-points");
+
+ // I am not sure why, but since "linkage-points" is an xml-element-wrapper in the
+ // OXM definition,
+ // we get back the whole array of Strings in one String - but still use the
+ // "vtx.properties()" to
+ // get it - but only look at the first thing returned by the iterator.
+ if (vpI.hasNext()) {
+ String tmpLinkageThing = (String) vpI.next().value();
+ linkagePtList = makeSureItsAnArrayList(tmpLinkageThing);
+ }
+
+ if (linkagePtList != null && !linkagePtList.isEmpty()) {
+ // This is as far as we can go, we will use the linkage point info to define the
+ // rest of this "trail"
+ for (int i = 0; i < linkagePtList.size(); i++) {
+ Multimap<String, String> tmpMap = collectTopology4LinkagePoint(transId,
+ fromAppId, linkagePtList.get(i), thisGuysTrail, currentMap);
+ thisMap.putAll(tmpMap);
+ }
+ } else {
+ check4EdgeRule(tmpElNT, thisElementNodeType);
+ thisMap.put(thisGuysTrail, tmpElStepName);
+ if (!thisTrailsVidsTraversed.contains(tmpElVid)) {
+ // This is one we would like to use - so we'll recursively get it's result
+ // set to add to ours
+ Multimap<String, String> tmpMap = collectTopology4ModelVer(transId,
+ fromAppId, elVert, thisGuysTrail, currentMap, thisTrailsVidsTraversed,
+ levelCounter, modConstraintHash2Use, subModelFirstModInvId,
+ subModelFirstModVerId);
+ thisMap.putAll(tmpMap);
+ } else {
+ String modelElementUuid =
+ elVert.<String>property("model-element-uuid").orElse(null);
+ String msg =
+ "Bad Model Definition: looping model-element (model-element-uuid = ["
+ + modelElementUuid + "]) found trying to add step: ["
+ + tmpElStepName + "], " + " on trail = [" + thisGuysTrail + "]. ";
+ System.out.println(msg);
+ throw new AAIException("AAI_6132", msg);
+ }
+ }
+ }
+ }
+
+ return thisMap;
+
+ } // End of collectTopology4ModelVer()
+
+ /**
+ * Check 4 edge rule.
+ *
+ * @param nodeTypeA the node type A
+ * @param nodeTypeB the node type B
+ * @throws AAIException the AAI exception
+ */
+ public void check4EdgeRule(String nodeTypeA, String nodeTypeB) throws AAIException {
+ // Throw an exception if there is no defined edge rule for this combination of nodeTypes in
+ // DbEdgeRules.
+
+ final EdgeIngestor edgeRules =
+ SpringContextAware.getApplicationContext().getBean(EdgeIngestor.class);
+ // final EdgeRules edgeRules = EdgeRules.getInstance();
+
+ EdgeRuleQuery.Builder baseQ = new EdgeRuleQuery.Builder(nodeTypeA, nodeTypeB);
+ if (!edgeRules.hasRule(baseQ.build())) {
+
+ /*
+ * if( !edgeRules.hasEdgeRule(nodeTypeA, nodeTypeB)
+ * && !edgeRules.hasEdgeRule(nodeTypeB, nodeTypeA) ){
+ */
+ // There's no EdgeRule for this -- find out if one of the nodeTypes is invalid or if
+ // they are valid, but there's just no edgeRule for them.
+ try {
+ loader.introspectorFromName(nodeTypeA);
+ } catch (AAIUnknownObjectException e) {
+ String emsg = " Unrecognized nodeType aa [" + nodeTypeA + "]\n";
+ throw new AAIException("AAI_6115", emsg);
+ }
+ try {
+ loader.introspectorFromName(nodeTypeB);
+ } catch (AAIUnknownObjectException e) {
+ String emsg = " Unrecognized nodeType bb [" + nodeTypeB + "]\n";
+ throw new AAIException("AAI_6115", emsg);
+ }
+
+ String msg = " No Edge Rule found for this pair of nodeTypes (order does not matter) ["
+ + nodeTypeA + "], [" + nodeTypeB + "].";
+ throw new AAIException("AAI_6120", msg);
+ }
+
+ }
+
+ /**
+ * Collect topology 4 linkage point.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param linkagePointStrVal -- Note it is in reverse order from where we connect to it.
+ * @param incomingTrail -- trail of nodeTypes that got us here (this vertex) from the top
+ * @param currentMap the current map -- that got us to this point (that we will use as the base
+ * of the map we will return)
+ * @return Map of the topology
+ * @throws AAIException the AAI exception
+ */
+ public Multimap<String, String> collectTopology4LinkagePoint(String transId, String fromAppId,
+ String linkagePointStrVal, String incomingTrail, Multimap<String, String> currentMap)
+ throws AAIException {
+
+ Multimap<String, String> thisMap = ArrayListMultimap.create();
+ thisMap.putAll(currentMap);
+ String thisGuysTrail = incomingTrail;
+
+ // NOTE - "trails" can have multiple parts now since we track persona info for some.
+ // We just want to look at the node type info - which would be the piece
+ // before any commas (if there are any).
+
+ String[] trailSteps = thisGuysTrail.split("\\|");
+ if (trailSteps.length == 0) {
+ throw new AAIException("AAI_6125",
+ "Bad incomingTrail passed to collectTopology4LinkagePoint(): [" + incomingTrail
+ + "] ");
+ }
+ String lastStepString = trailSteps[trailSteps.length - 1];
+ String[] stepPieces = lastStepString.split(",");
+ String lastStepNT = stepPieces[0];
+
+ // It is assumed that the linkagePoint string will be a pipe-delimited string where each
+ // piece is an AAIProperties.NODE_TYPE. For now, the first thing to connect to is what is on
+ // the farthest right.
+ // Example: linkagePoint = "pserver|p-interface|l-interface" would mean that we're
+ // connecting to the l-interface
+ // but that after that, we connect to a p-interface followed by a pserver.
+ // It might have been more clear to define it in the other direction, but for now, that is
+ // it. (16-07)
+ String linkagePointStr = linkagePointStrVal;
+
+ // We are getting these with more than linkage thing in one string.
+ // Ie. "pserver|lag-interface|l-interface, pserver|p-interface|l-interface,
+ // vlan|l-interface"
+ linkagePointStr = linkagePointStr.replace("[", "");
+ linkagePointStr = linkagePointStr.replace("]", "");
+ linkagePointStr = linkagePointStr.replace(" ", "");
+
+ String[] linkage = linkagePointStr.split("\\,");
+ for (int x = 0; x < linkage.length; x++) {
+ lastStepNT = stepPieces[0];
+ String thisStepNT = "";
+ String[] linkageSteps = linkage[x].split("\\|");
+ if (linkageSteps.length == 0) {
+ throw new AAIException("AAI_6125",
+ "Bad linkagePointStr passed to collectTopology4LinkagePoint(): ["
+ + linkagePointStr + "] ");
+ }
+ for (int i = (linkageSteps.length - 1); i >= 0; i--) {
+ thisStepNT = linkageSteps[i];
+ check4EdgeRule(lastStepNT, thisStepNT);
+ thisMap.put(thisGuysTrail, thisStepNT);
+ thisGuysTrail = thisGuysTrail + "|" + thisStepNT;
+ lastStepNT = thisStepNT;
+ }
+ }
+ return thisMap;
+
+ } // End of collectTopology4LinkagePoint()
+
+ /**
+ * Gets the next step elements from set.
+ *
+ * @param constrElemSetVtx the constr elem set vtx
+ * @return Hash of the set of model-elements this set represents
+ * @throws AAIException the AAI exception
+ */
+ public Map<String, Object> getNextStepElementsFromSet(Vertex constrElemSetVtx)
+ throws AAIException {
+ // Take a constrained-element-set and figure out the total set of all the possible elements
+ // that it
+ // represents and return them as a Hash.
+
+ Map<String, Object> retElementHash = new HashMap<>();
+
+ if (constrElemSetVtx == null) {
+ String msg = " getNextStepElementsFromSet() called with null constrElemSetVtx ";
+ throw new AAIException("AAI_6125", msg);
+ }
+
+ String constrNodeType =
+ constrElemSetVtx.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ String constrElemSetUuid =
+ constrElemSetVtx.<String>property("constrained-element-set-uuid").orElse(null);
+ if (constrNodeType == null || !constrNodeType.equals("constrained-element-set")) {
+ String msg = " getNextStepElementsFromSet() called with wrong type model: ["
+ + constrNodeType + "]. ";
+ throw new AAIException("AAI_6125", msg);
+ }
+
+ ArrayList<Vertex> choiceSetVertArray = new ArrayList<>();
+ Iterator<Vertex> vertI =
+ this.traverseIncidentEdges(EdgeType.TREE, constrElemSetVtx, "element-choice-set");
+ int setCount = 0;
+ while (vertI != null && vertI.hasNext()) {
+ Vertex choiceSetVertex = vertI.next();
+ String constrSetType =
+ choiceSetVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ if (constrSetType != null && constrSetType.equals("element-choice-set")) {
+ choiceSetVertArray.add(choiceSetVertex);
+ setCount++;
+ }
+ }
+
+ if (setCount == 0) {
+ String msg = "No element-choice-set found under constrained-element-set-uuid = "
+ + constrElemSetUuid;
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ // Loop through each choice-set and grab the model-elements
+ for (int i = 0; i < setCount; i++) {
+ Vertex choiceSetVert = choiceSetVertArray.get(i);
+ Iterator<Vertex> mVertI =
+ this.traverseIncidentEdges(EdgeType.TREE, choiceSetVert, "model-element");
+ int elCount = 0;
+ while (mVertI != null && mVertI.hasNext()) {
+ Vertex tmpElVertex = mVertI.next();
+ String elNodeType =
+ tmpElVertex.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ if (elNodeType != null && elNodeType.equals("model-element")) {
+ String tmpVid = tmpElVertex.id().toString();
+ retElementHash.put(tmpVid, tmpElVertex);
+ elCount++;
+ } else {
+ // unsupported node type found for this choice-set
+ String msg = "Unsupported nodeType (" + elNodeType
+ + ") found under choice-set under constrained-element-set-uuid = "
+ + constrElemSetUuid;
+ throw new AAIException("AAI_6132", msg);
+ }
+ }
+
+ if (elCount == 0) {
+ String msg =
+ "No model-elements found in choice-set under constrained-element-set-uuid = "
+ + constrElemSetUuid;
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ }
+ return retElementHash;
+
+ } // End of getNextStepElementsFromSet()
+
+ /**
+ * Gen topo map 4 named Q.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param queryVertex the query vertex
+ * @param namedQueryUuid the named query uuid
+ * @return MultiMap of valid next steps for each potential query-element
+ * @throws AAIException the AAI exception
+ */
+ public Multimap<String, String> genTopoMap4NamedQ(String transId, String fromAppId,
+ Vertex queryVertex, String namedQueryUuid) throws AAIException {
+
+ if (queryVertex == null) {
+ throw new AAIException("AAI_6125", "null queryVertex passed to genTopoMap4NamedQ()");
+ }
+
+ Multimap<String, String> initialEmptyMap = ArrayListMultimap.create();
+ List<String> vidsTraversed = new ArrayList<>();
+
+ Vertex firstElementVertex = null;
+ Iterator<Vertex> vertI =
+ this.traverseIncidentEdges(EdgeType.TREE, queryVertex, "named-query-element");
+ int elCount = 0;
+ while (vertI != null && vertI.hasNext()) {
+ elCount++;
+ firstElementVertex = vertI.next();
+ }
+
+ if (elCount > 1) {
+ throw new AAIException("AAI_6133",
+ "Illegal query defined: More than one first element defined for = "
+ + namedQueryUuid);
+ }
+
+ if (firstElementVertex == null) {
+ throw new AAIException("AAI_6114",
+ "Could not find first query element = " + namedQueryUuid);
+ }
+
+ Vertex modVtx = getModelThatNqElementRepresents(firstElementVertex, "");
+ String modelType = getModelTypeFromModel(modVtx, "");
+ if (!modelType.equals("widget")) {
+ throw new AAIException("AAI_6133",
+ "Bad Named Query Definition: First element must correspond to a widget type model. Named Query UUID = "
+ + namedQueryUuid);
+ }
+
+ return collectTopology4NamedQ(transId, fromAppId, firstElementVertex, "", initialEmptyMap,
+ vidsTraversed, 0);
+ } // End of genTopoMap4NamedQ()
+
+ /**
+ * Collect topology 4 named Q.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param thisLevelElemVtx the model element vertex for this level
+ * @param levelCounter the level counter
+ * @return resultSet
+ * @throws AAIException the AAI exception
+ */
+ public Multimap<String, String> collectTopology4NamedQ(String transId, String fromAppId,
+ Vertex thisLevelElemVtx, String incomingTrail, Multimap<String, String> currentMap,
+ List<String> vidsTraversed, int levelCounter) throws AAIException {
+
+ levelCounter++;
+
+ Multimap<String, String> thisMap = ArrayListMultimap.create();
+ thisMap.putAll(currentMap);
+
+ String thisElemVid = thisLevelElemVtx.id().toString();
+ if (levelCounter > MAX_LEVELS) {
+ throw new AAIException("AAI_6125",
+ "collectModelStructure() has looped across more levels than allowed: " + MAX_LEVELS
+ + ". ");
+ }
+ String thisGuysTrail = "";
+
+ // find out what widget (and thereby what aai-node-type) this element represents
+ String thisElementNodeType =
+ getNqElementWidgetType(transId, fromAppId, thisLevelElemVtx, incomingTrail);
+
+ if (incomingTrail.equals("")) {
+ // This is the first one
+ thisGuysTrail = thisElementNodeType;
+ } else {
+ thisGuysTrail = incomingTrail + "|" + thisElementNodeType;
+ }
+
+ vidsTraversed.add(thisElemVid);
+ // Look at the elements pointed to at this level and add on their data
+ Iterator<Vertex> vertI =
+ this.traverseIncidentEdges(EdgeType.TREE, thisLevelElemVtx, "named-query-element");
+ while (vertI != null && vertI.hasNext()) {
+ Vertex tmpVert = vertI.next();
+ String tmpVid = tmpVert.id().toString();
+ String tmpElNT = getNqElementWidgetType(transId, fromAppId, tmpVert, thisGuysTrail);
+ thisMap.put(thisGuysTrail, tmpElNT);
+ if (!vidsTraversed.contains(tmpVid)) {
+ // This is one we would like to use - so we'll recursively get it's result set to
+ // add to ours
+ Multimap<String, String> tmpMap = collectTopology4NamedQ(transId, fromAppId,
+ tmpVert, thisGuysTrail, currentMap, vidsTraversed, levelCounter);
+ thisMap.putAll(tmpMap);
+ }
+ }
+
+ return thisMap;
+
+ } // End of collectTopology4NamedQ()
+
+ /**
+ * Gets the model that NamedQuery element represents.
+ *
+ * @param elementVtx the NQ element vtx
+ * @param elementTrail the element trail
+ * @return the model that element represents
+ * @throws AAIException the AAI exception
+ */
+ public Vertex getModelThatNqElementRepresents(Vertex elementVtx, String elementTrail)
+ throws AAIException {
+
+ // Get the model that a named-query element represents
+ Vertex modVtx = null;
+ Iterator<Vertex> mvertI = this.traverseIncidentEdges(EdgeType.COUSIN, elementVtx, "model");
+ int modCount = 0;
+ while (mvertI != null && mvertI.hasNext()) {
+ modCount++;
+ modVtx = mvertI.next();
+ }
+
+ if (modCount > 1) {
+ String msg =
+ "Illegal element defined: More than one model pointed to by a single named-query-element at ["
+ + elementTrail + "].";
+ throw new AAIException("AAI_6125", msg);
+ }
+
+ if (modVtx == null) {
+ String msg = "Bad named-query definition: Could not find model for element. ";
+ if (!elementTrail.equals("")) {
+ msg =
+ "Bad named-query definition: Could not find model for named-query-element at ["
+ + elementTrail + "].";
+ }
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ String nodeType = modVtx.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ if ((nodeType != null) && nodeType.equals("model")) {
+ return modVtx;
+ } else {
+ String msg =
+ "Illegal Named Query element defined: expecting a 'model', but found 'isA' edge pointing to nodeType = "
+ + nodeType + "] at [" + elementTrail + "].";
+ throw new AAIException("AAI_6125", msg);
+ }
+
+ }// getModelThatNqElementRepresents()
+
+ /**
+ * Gets the model-ver that element represents.
+ *
+ * @param elementVtx the element vtx
+ * @param elementTrail the element trail
+ * @return the model-ver that element represents
+ * @throws AAIException the AAI exception
+ */
+ public Vertex getModelVerThatElementRepresents(Vertex elementVtx, String elementTrail)
+ throws AAIException {
+
+ // Get the model-ver that an element represents
+ Vertex modVerVtx = null;
+ Iterator<Vertex> mvertI =
+ this.traverseIncidentEdges(EdgeType.COUSIN, elementVtx, "model-ver");
+ int modCount = 0;
+ while (mvertI != null && mvertI.hasNext()) {
+ modCount++;
+ modVerVtx = mvertI.next();
+ }
+
+ if (modCount > 1) {
+ String msg =
+ "Illegal element defined: More than one model pointed to by a single element at ["
+ + elementTrail + "].";
+ throw new AAIException("AAI_6125", msg);
+ }
+
+ if (modVerVtx == null) {
+ String msg = "Bad model definition: Could not find model-ver for model-element. ";
+ if (!elementTrail.equals("")) {
+ msg = "Bad model definition: Could not find model-VER for model-element at ["
+ + elementTrail + "].";
+ }
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ String nodeType = modVerVtx.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ if ((nodeType != null) && nodeType.equals("model-ver")) {
+ return modVerVtx;
+ } else {
+ String msg =
+ "Illegal model-element defined: expecting a 'model-ver', but found 'isA' edge pointing to nodeType = "
+ + nodeType + "] at [" + elementTrail + "].";
+ throw new AAIException("AAI_6125", msg);
+ }
+
+ }// getModelVerThatElementRepresents()
+
+ /**
+ * Gets the model that is parent to model-ver node.
+ *
+ * @param modVerVtx the model-ver vtx
+ * @param elementTrail the element trail
+ * @return the model that element represents
+ * @throws AAIException the AAI exception
+ */
+ public Vertex getModelGivenModelVer(Vertex modVerVtx, String elementTrail) throws AAIException {
+
+ // Get the parent model for this "model-ver" node
+ Vertex modVtx = null;
+ Iterator<Vertex> mvertI = this.traverseIncidentEdges(EdgeType.TREE, modVerVtx, "model");
+ int modCount = 0;
+ while (mvertI != null && mvertI.hasNext()) {
+ modCount++;
+ modVtx = mvertI.next();
+ }
+
+ if (modCount > 1) {
+ String msg =
+ "Illegal model-ver node defined: More than one model points to it with a 'has' edge ["
+ + elementTrail + "].";
+ throw new AAIException("AAI_6125", msg);
+ }
+
+ if (modVtx == null) {
+ String msg = "Bad model-ver node: Could not find parent model. ";
+ if (!elementTrail.equals("")) {
+ msg = "Bad model-ver node: Could not find parent model. [" + elementTrail + "].";
+ }
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ String nodeType = modVtx.<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ if ((nodeType != null) && nodeType.equals("model")) {
+ // Found what we were looking for.
+ return modVtx;
+ } else {
+ // Something is amiss
+ String msg =
+ " Could not find parent model node for model-ver node at [" + elementTrail + "].";
+ throw new AAIException("AAI_6125", msg);
+ }
+
+ }// getModelGivenModelVer()
+
+ /**
+ * Gets the model type.
+ *
+ * @param modelVtx the model vtx
+ * @param elementTrail the element trail
+ * @return the model type
+ * @throws AAIException the AAI exception
+ */
+ public String getModelTypeFromModel(Vertex modelVtx, String elementTrail) throws AAIException {
+
+ // Get the model-type from a model vertex
+ if (modelVtx == null) {
+ String msg = " null modelVtx passed to getModelTypeFromModel() ";
+ throw new AAIException("AAI_6114", msg);
+ }
+
+ String modelType = modelVtx.<String>property("model-type").orElse(null);
+ if ((modelType == null) || modelType.equals("")) {
+ String msg =
+ "Could not find model-type for model encountered at [" + elementTrail + "].";
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ if (!modelType.equals("widget") && !modelType.equals("resource")
+ && !modelType.equals("service")) {
+ String msg = "Unrecognized model-type, [" + modelType
+ + "] for model pointed to by element at [" + elementTrail + "].";
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ return modelType;
+
+ }// getModelTypeFromModel()
+
+ /**
+ * Gets the model type given model-ver
+ *
+ * @param modelVerVtx the model-ver vtx
+ * @param elementTrail the element trail
+ * @return the model type
+ * @throws AAIException the AAI exception
+ */
+ public String getModelTypeFromModelVer(Vertex modelVerVtx, String elementTrail)
+ throws AAIException {
+
+ // Get the model-type given a model-ver vertex
+ if (modelVerVtx == null) {
+ String msg = " null modelVerVtx passed to getModelTypeFromModelVer() ";
+ throw new AAIException("AAI_6114", msg);
+ }
+
+ Vertex modVtx = getModelGivenModelVer(modelVerVtx, elementTrail);
+ String modelType = modVtx.<String>property("model-type").orElse(null);
+ if ((modelType == null) || modelType.equals("")) {
+ String msg =
+ "Could not find model-type for model encountered at [" + elementTrail + "].";
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ if (!modelType.equals("widget") && !modelType.equals("resource")
+ && !modelType.equals("service")) {
+ String msg = "Unrecognized model-type, [" + modelType
+ + "] for model pointed to by element at [" + elementTrail + "].";
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ return modelType;
+
+ }// getModelTypeFromModelVer()
+
+ /**
+ * Gets the model-element step name.
+ *
+ * @param elementVtx the model-element vtx
+ * @param elementTrail the element trail
+ * @return the element step name
+ * @throws AAIException the AAI exception
+ */
+ public String getModelElementStepName(Vertex elementVtx, String elementTrail)
+ throws AAIException {
+
+ // Get the "step name" for a model-element
+ // Step names look like this for widget-models: AAIProperties.NODE_TYPE
+ // Step names look like this for resource/service models:
+ // "aai-node-type,model-invariant-id,model-version-id"
+ // NOTE -- if the element points to a resource or service model, then we'll return the
+ // widget-type of the first element (crown widget) for that model.
+ String thisElementNodeType = "?";
+ Vertex modVerVtx = getModelVerThatElementRepresents(elementVtx, elementTrail);
+ String modelType = getModelTypeFromModelVer(modVerVtx, elementTrail);
+
+ if (modelType == null) {
+ String msg =
+ " could not determine modelType in getModelElementStepName(). elementTrail = ["
+ + elementTrail + "].";
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ if (modelType.equals("widget")) {
+ // NOTE: for models that have model-type = "widget", their "model-name" maps directly to
+ // aai-node-type
+ thisElementNodeType = modVerVtx.<String>property("model-name").orElse(null);
+ if ((thisElementNodeType == null) || thisElementNodeType.equals("")) {
+ String msg =
+ "Could not find model-name for the widget model pointed to by element at ["
+ + elementTrail + "].";
+ throw new AAIException("AAI_6132", msg);
+ }
+ return thisElementNodeType;
+ } else if (modelType.equals("resource") || modelType.equals("service")) {
+ Vertex modVtx = getModelGivenModelVer(modVerVtx, elementTrail);
+ String modInvId = modVtx.<String>property("model-invariant-id").orElse(null);
+ String modVerId = modVerVtx.<String>property("model-version-id").orElse(null);
+ Vertex relatedTopElementModelVtx =
+ getTopElementForSvcOrResModelVer(modVerVtx, elementTrail);
+ Vertex relatedModelVtx =
+ getModelVerThatElementRepresents(relatedTopElementModelVtx, elementTrail);
+ thisElementNodeType = relatedModelVtx.<String>property("model-name").orElse(null);
+
+ if ((thisElementNodeType == null) || thisElementNodeType.equals("")) {
+ String msg =
+ "Could not find model-name for the widget model pointed to by element at ["
+ + elementTrail + "].";
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ String stepName = "";
+ if (nodeTypeSupportsPersona(thisElementNodeType)) {
+ // This nodeType that this resource or service model refers to does support
+ // persona-related fields, so
+ // we will use model-invariant-id and model-version-id as part of the step name.
+ stepName = thisElementNodeType + "," + modInvId + "," + modVerId;
+ } else {
+ stepName = thisElementNodeType;
+ }
+ return stepName;
+ } else {
+ String msg = " Unrecognized model-type = [" + modelType + "] pointed to by element at ["
+ + elementTrail + "].";
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ }// getModelElementStepName()
+
+ /**
+ * Node type supports persona.
+ *
+ * @param nodeType the node type
+ * @return the boolean
+ * @throws AAIException the AAI exception
+ */
+ public Boolean nodeTypeSupportsPersona(String nodeType) throws AAIException {
+
+ if (nodeType == null || nodeType.equals("")) {
+ return false;
+ }
+ Introspector introspector = null;
+ try {
+ introspector = loader.introspectorFromName(nodeType);
+ } catch (AAIUnknownObjectException e) {
+ String emsg = " Unrecognized nodeType [" + nodeType + "]\n";
+ throw new AAIException("AAI_6115", emsg);
+ }
+
+ Collection<String> props4ThisNT = introspector.getProperties();
+ return props4ThisNT.contains(addDBAliasedSuffix("model-invariant-id"))
+ && props4ThisNT.contains(addDBAliasedSuffix("model-version-id"));
+
+ }// nodeTypeSupportsPersona()
+
+ /**
+ * Gets a Named Query element's widget type.
+ *
+ * @param elementVtx the named-query element vtx
+ * @param elementTrail the element trail
+ * @return the element widget type
+ * @throws AAIException the AAI exception
+ */
+ public String getNqElementWidgetType(String transId, String fromAppId, Vertex elementVtx,
+ String elementTrail) throws AAIException {
+
+ String thisNqElementWidgetType = "";
+ // Get the associated node-type for the model pointed to by a named-query-element.
+ // NOTE -- if the element points to a resource or service model, then we'll return the
+ // widget-type of the first element (crown widget) for that model.
+ Vertex modVtx = getModelThatNqElementRepresents(elementVtx, elementTrail);
+ String modelType = getModelTypeFromModel(modVtx, elementTrail);
+
+ if (modelType == null || !modelType.equals("widget")) {
+ String emsg = " Model Type must be 'widget' for NamedQuery elements. Found ["
+ + modelType + "] at [" + elementTrail + "]\n";
+ throw new AAIException("AAI_6132", emsg);
+ } else {
+ // For a Widget model, the nodeType is just mapped to the model-element.model-name
+ List<Vertex> modVerVtxArr = getModVersUsingModel(transId, fromAppId, modVtx);
+ if (modVerVtxArr != null && !modVerVtxArr.isEmpty()) {
+ thisNqElementWidgetType =
+ (modVerVtxArr.get(0)).<String>property("model-name").orElse(null);
+ }
+ if (thisNqElementWidgetType == null || thisNqElementWidgetType.equals("")) {
+ String emsg = " Widget type could not be determined at [" + elementTrail + "]\n";
+ throw new AAIException("AAI_6132", emsg);
+ } else {
+ return thisNqElementWidgetType;
+ }
+ }
+
+ }// End getNqElementWidgetType()
+
+ /**
+ * Gets a model-element's top widget type.
+ *
+ * @param elementVtx the model element vtx
+ * @param elementTrail the element trail
+ * @return the element widget type
+ * @throws AAIException the AAI exception
+ */
+ public String getModElementWidgetType(Vertex elementVtx, String elementTrail)
+ throws AAIException {
+
+ // Get the associated node-type for the model-ver pointed to by a model-element.
+ // NOTE -- if the element points to a resource or service model, then we'll return the
+ // widget-type of the first element (crown widget) for that model.
+ Vertex modVerVtx = getModelVerThatElementRepresents(elementVtx, elementTrail);
+ return getModelVerTopWidgetType(modVerVtx, elementTrail);
+
+ }// End getModElementWidgetType()
+
+ /**
+ * Gets the node using unique identifier
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param nodeType the nodeType
+ * @param idPropertyName the property name of the unique identifier
+ * @param uniqueIdVal the UUID value
+ * @return unique vertex found using UUID
+ * @throws AAIException the AAI exception
+ */
+ public Vertex getNodeUsingUniqueId(String transId, String fromAppId, String nodeType,
+ String idPropertyName, String uniqueIdVal) throws AAIException {
+
+ // Given a unique identifier, get the Vertex
+ if (uniqueIdVal == null || uniqueIdVal.equals("")) {
+ String emsg =
+ " Bad uniqueIdVal passed to getNodeUsingUniqueId(): [" + uniqueIdVal + "]\n";
+ throw new AAIException("AAI_6118", emsg);
+ }
+
+ if (idPropertyName == null || idPropertyName.equals("")) {
+ String emsg =
+ " Bad idPropertyName passed to getNodeUsingUniqueId(): [" + idPropertyName + "]\n";
+ throw new AAIException("AAI_6118", emsg);
+ }
+
+ if (nodeType == null || nodeType.equals("")) {
+ String emsg = " Bad nodeType passed to getNodeUsingUniqueId(): [" + nodeType + "]\n";
+ throw new AAIException("AAI_6118", emsg);
+ }
+
+ Vertex uniqVtx = null;
+ Iterable<?> uniqVerts = null;
+ uniqVerts = engine.asAdmin().getReadOnlyTraversalSource().V()
+ .has(AAIProperties.NODE_TYPE, nodeType).has(idPropertyName, uniqueIdVal).toList();
+ if (uniqVerts == null) {
+ String emsg =
+ "Node could not be found for nodeType = [" + nodeType + "], propertyName = ["
+ + idPropertyName + "], propertyValue = [" + uniqueIdVal + "]\n";
+ throw new AAIException("AAI_6114", emsg);
+ } else {
+ int count = 0;
+ Iterator<?> uniqVertsIter = uniqVerts.iterator();
+ if (!uniqVertsIter.hasNext()) {
+ String emsg =
+ "Node could not be found for nodeType = [" + nodeType + "], propertyName = ["
+ + idPropertyName + "], propertyValue = [" + uniqueIdVal + "]\n";
+ throw new AAIException("AAI_6114", emsg);
+ } else {
+ while (uniqVertsIter.hasNext()) {
+ count++;
+ uniqVtx = (Vertex) uniqVertsIter.next();
+ if (count > 1) {
+ String emsg = "More than one node found for nodeType = [" + nodeType
+ + "], propertyName = [" + idPropertyName + "], propertyValue = ["
+ + uniqueIdVal + "]\n";
+ throw new AAIException("AAI_6132", emsg);
+ }
+ }
+ }
+ }
+
+ return uniqVtx;
+ }// End getNodeUsingUniqueId()
+
+ /**
+ * Gets the model-ver nodes using name.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param modelName the model name
+ * @return the model-ver's that use this name
+ * @throws AAIException the AAI exception
+ */
+ public List<Vertex> getModelVersUsingName(String transId, String fromAppId, String modelName)
+ throws AAIException {
+
+ // Given a "model-name", find the model-ver vertices that this maps to
+ if (modelName == null || modelName.equals("")) {
+ String emsg = " Bad modelName passed to getModelVersUsingName(): [" + modelName + "]\n";
+ throw new AAIException("AAI_6118", emsg);
+ }
+
+ List<Vertex> retVtxArr = new ArrayList<>();
+ Iterator<Vertex> modVertsIter = this.engine.asAdmin().getReadOnlyTraversalSource().V()
+ .has(AAIProperties.NODE_TYPE, "model-ver").has("model-name", modelName);
+ if (!modVertsIter.hasNext()) {
+ String emsg =
+ "Model-ver record(s) could not be found for model-ver data passed. model-name = ["
+ + modelName + "]\n";
+ throw new AAIException("AAI_6132", emsg);
+ } else {
+ while (modVertsIter.hasNext()) {
+ Vertex tmpModelVerVtx = modVertsIter.next();
+ retVtxArr.add(tmpModelVerVtx);
+ }
+ }
+
+ return retVtxArr;
+
+ }// End getModelVersUsingName()
+
+ /**
+ * Gets the model-ver nodes using model-invariant-id.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param modelInvId-invariant-id (uniquely identifies a model)
+ * @return the model-ver's defined for the corresponding model
+ * @throws AAIException the AAI exception
+ */
+ public Iterator<Vertex> getModVersUsingModelInvId(String transId, String fromAppId,
+ String modelInvId) throws AAIException {
+
+ // Given a "model-invariant-id", find the model-ver nodes that this maps to
+ if (modelInvId == null || modelInvId.equals("")) {
+ String emsg = " Bad model-invariant-id passed to getModVersUsingModelInvId(): ["
+ + modelInvId + "]\n";
+ throw new AAIException("AAI_6118", emsg);
+ }
+
+ Vertex modVtx =
+ getNodeUsingUniqueId(transId, fromAppId, "model", "model-invariant-id", modelInvId);
+ List<Vertex> retVtxArr = getModVersUsingModel(transId, fromAppId, modVtx);
+ if (retVtxArr == null || retVtxArr.isEmpty()) {
+ String emsg =
+ " Model-ver record(s) could not be found attached to model with model-invariant-id = ["
+ + modelInvId + "]\n";
+ throw new AAIException("AAI_6132", emsg);
+ }
+
+ return retVtxArr.iterator();
+ }// End getModVersUsingModelInvId()
+
+ /**
+ * Gets the model-ver nodes using a model node.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param modVtx vertex
+ * @return the model-ver's defined for the corresponding model
+ * @throws AAIException the AAI exception
+ */
+ public List<Vertex> getModVersUsingModel(String transId, String fromAppId, Vertex modVtx)
+ throws AAIException {
+
+ if (modVtx == null) {
+ String emsg = " Null model vertex passed to getModVersUsingModel(): ";
+ throw new AAIException("AAI_6118", emsg);
+ }
+
+ List<Vertex> retVtxArr = new ArrayList<>();
+ Iterator<Vertex> modVerVertsIter =
+ this.traverseIncidentEdges(EdgeType.TREE, modVtx, "model-ver");
+ if (!modVerVertsIter.hasNext()) {
+ String modelInvId = modVtx.<String>property("model-invariant-id").orElse(null);
+ String emsg =
+ "Model-ver record(s) could not be found attached to model with model-invariant-id = ["
+ + modelInvId + "]\n";
+ throw new AAIException("AAI_6132", emsg);
+ } else {
+ while (modVerVertsIter.hasNext()) {
+ Vertex tmpModelVtx = modVerVertsIter.next();
+ retVtxArr.add(tmpModelVtx);
+ }
+ }
+
+ return retVtxArr;
+
+ }// End getModVersUsingModel()
+
+ /**
+ * Gets the model-version-ids using model-name.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param modelName the model name
+ * @return the model uuids using name
+ * @throws AAIException the AAI exception
+ */
+ public List<String> getModelVerIdsUsingName(String transId, String fromAppId, String modelName)
+ throws AAIException {
+
+ // Given a model-name find the model-ver nodes that it maps to
+ if (modelName == null || modelName.equals("")) {
+ String emsg =
+ " Bad modelName passed to getModelVerIdsUsingName(): [" + modelName + "]\n";
+ throw new AAIException("AAI_6118", emsg);
+ }
+
+ List<String> retArr = new ArrayList<>();
+ Iterator<Vertex> modVerVertsIter = this.engine.asAdmin().getReadOnlyTraversalSource().V()
+ .has(AAIProperties.NODE_TYPE, "model-ver").has("model-name", modelName);
+ if (!modVerVertsIter.hasNext()) {
+ String emsg =
+ " model-ver record(s) could not be found for model data passed. model-name = ["
+ + modelName + "]\n";
+ throw new AAIException("AAI_6114", emsg);
+ } else {
+ while (modVerVertsIter.hasNext()) {
+ Vertex modelVerVtx = modVerVertsIter.next();
+ String tmpUuid = modelVerVtx.<String>property("model-version-id").orElse(null);
+ if ((tmpUuid != null) && !tmpUuid.equals("") && !retArr.contains(tmpUuid)) {
+ retArr.add(tmpUuid);
+ }
+ }
+ }
+
+ if (retArr.isEmpty()) {
+ String emsg = "No model-ver record found for model-name = [" + modelName + "]\n";
+ throw new AAIException("AAI_6132", emsg);
+ }
+
+ return retArr;
+ }// End getModelVerIdsUsingName()
+
+ /**
+ * Gets the model top widget type.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param modelVersionId the model-version-id
+ * @param modelInvId the model-invariant-id
+ * @param modelName the model-name
+ * @return the model top widget type
+ * @throws AAIException the AAI exception
+ */
+ public String getModelVerTopWidgetType(String transId, String fromAppId, String modelVersionId,
+ String modelInvId, String modelName) throws AAIException {
+
+ // Could be given a model-ver's key info (model-version-id), OR, just a (non-unique)
+ // model-name,
+ // Or just a model-invariant-id (which could have multiple model-ver records under it).
+ // In any case, they should only map to one single "top" node-type for the first element.
+
+ String nodeType = "?";
+ Iterator<Vertex> modVerVertsIter;
+
+ if (modelVersionId != null && !modelVersionId.equals("")) {
+ // this would be the best - we can just look up the model-ver records directly
+ modVerVertsIter = this.engine.asAdmin().getReadOnlyTraversalSource().V()
+ .has(AAIProperties.NODE_TYPE, "model-ver").has("model-version-id", modelVersionId);
+ } else if (modelName != null && !modelName.equals("")) {
+ modVerVertsIter = this.engine.asAdmin().getReadOnlyTraversalSource().V()
+ .has(AAIProperties.NODE_TYPE, "model-ver").has("model-name", modelName);
+ } else if (modelInvId != null && !modelInvId.equals("")) {
+ modVerVertsIter = getModVersUsingModelInvId(transId, fromAppId, modelInvId);
+ } else {
+ String msg =
+ "Neither modelVersionId, modelInvariantId, nor modelName passed to: getModelVerTopWidgetType() ";
+ throw new AAIException("AAI_6120", msg);
+ }
+
+ if (!modVerVertsIter.hasNext()) {
+ String emsg =
+ "model-ver record(s) could not be found for model data passed: modelInvariantId = ["
+ + modelInvId + "], modeVersionId = [" + modelVersionId + "], modelName = ["
+ + modelName + "]\n";
+ throw new AAIException("AAI_6114", emsg);
+ } else {
+ String lastNT = "";
+ if (!modVerVertsIter.hasNext()) {
+ String emsg =
+ "model-ver record(s) could not be found for model data passed: modelInvariantId = ["
+ + modelInvId + "], modeVersionId = [" + modelVersionId + "], modelName = ["
+ + modelName + "]\n";
+ throw new AAIException("AAI_6114", emsg);
+ }
+ while (modVerVertsIter.hasNext()) {
+ Vertex tmpModVerVtx = modVerVertsIter.next();
+ String tmpNT = getModelVerTopWidgetType(tmpModVerVtx, "");
+ if (lastNT != null && !lastNT.equals("")) {
+ if (!lastNT.equals(tmpNT)) {
+ String emsg = "Different top-node-types (" + tmpNT + ", " + lastNT
+ + ") found for model data passed. (" + " modelVersionId = ["
+ + modelVersionId + "], modelId = [" + modelInvId + "], modelName = ["
+ + modelName + "])\n";
+ throw new AAIException("AAI_6114", emsg);
+ }
+ }
+ lastNT = tmpNT;
+ nodeType = tmpNT;
+ }
+ }
+
+ return nodeType;
+
+ }// End getModelVerTopWidgetType()
+
+ /**
+ * Gets the widget type that this model-ver starts with.
+ *
+ * @param modVerVtx the model-version vtx
+ * @param elementTrail the element trail
+ * @return the widget type of the starting node of this model
+ * @throws AAIException the AAI exception
+ */
+ public String getModelVerTopWidgetType(Vertex modVerVtx, String elementTrail)
+ throws AAIException {
+ // Get the associated nodeType (Ie. aai-node-type / widget-type) for a model-ver.
+ // NOTE -- if the element points to a resource or service model, then we'll return the
+ // widget-type of the first element (crown widget) for that model.
+ String modelType = getModelTypeFromModelVer(modVerVtx, elementTrail);
+ if (modelType == null) {
+ String msg =
+ " Could not determine modelType in getModelVerTopWidgetType(). elementTrail = ["
+ + elementTrail + "].";
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ String thisElementNodeType = "?";
+ if (modelType.equals("widget")) {
+ // NOTE: for models that have model-type = "widget", their child model-ver nodes will
+ // have "model-name" which maps directly to aai-node-type (all model-ver's under one
+ // model should start with the same widget-type, so we only need to look at one).
+ thisElementNodeType = modVerVtx.<String>property("model-name").orElse(null);
+ if ((thisElementNodeType == null) || thisElementNodeType.equals("")) {
+ String msg =
+ "Could not find model-name for the widget model pointed to by element at ["
+ + elementTrail + "].";
+ throw new AAIException("AAI_6132", msg);
+ }
+ } else if (modelType.equals("resource") || modelType.equals("service")) {
+ Vertex relatedTopElementVtx = getTopElementForSvcOrResModelVer(modVerVtx, elementTrail);
+ Vertex relatedModVerVtx =
+ getModelVerThatElementRepresents(relatedTopElementVtx, elementTrail);
+ thisElementNodeType = relatedModVerVtx.<String>property("model-name").orElse(null);
+ if ((thisElementNodeType == null) || thisElementNodeType.equals("")) {
+ String msg =
+ "Could not find model-name for the widget model pointed to by element at ["
+ + elementTrail + "].";
+ throw new AAIException("AAI_6132", msg);
+ }
+ } else {
+ String msg = " Unrecognized model-type = [" + modelType + "] pointed to by element at ["
+ + elementTrail + "].";
+ throw new AAIException("AAI_6132", msg);
+ }
+
+ return thisElementNodeType;
+
+ }// getModelVerTopWidgetType()
+
+ /**
+ * Validate model.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param modelVersionIdVal the model name version id
+ * @param apiVersion the api version
+ * @throws AAIException the AAI exception
+ */
+ public void validateModel(String transId, String fromAppId, String modelVersionIdVal,
+ String apiVersion) throws AAIException {
+
+ // Note - this will throw an exception if the model either can't be found, or if
+ // we can't figure out its topology map.
+ Vertex modelVerVtx = getNodeUsingUniqueId(transId, fromAppId, "model-ver",
+ "model-version-id", modelVersionIdVal);
+ if (modelVerVtx == null) {
+ String msg =
+ " Could not find model-ver with modelVersionId = [" + modelVersionIdVal + "].";
+ throw new AAIException("AAI_6114", msg);
+ } else {
+ Multimap<String, String> topoMap =
+ genTopoMap4ModelVer(transId, fromAppId, modelVerVtx, modelVersionIdVal);
+ String msg = " modelVer [" + modelVersionIdVal + "] topo multiMap looks like: \n["
+ + topoMap + "]";
+ System.out.println("INFO -- " + msg);
+ }
+ }// End validateModel()
+
+ /**
+ * Validate named query.
+ *
+ * @param transId the trans id
+ * @param fromAppId the from app id
+ * @param namedQueryUuid the named query uuid
+ * @param apiVersion the api version
+ * @throws AAIException the AAI exception
+ */
+ public void validateNamedQuery(String transId, String fromAppId, String namedQueryUuid,
+ String apiVersion) throws AAIException {
+
+ // Note - this will throw an exception if the named query either can't be found, or if
+ // we can't figure out its topology map.
+ Vertex nqVtx = getNodeUsingUniqueId(transId, fromAppId, "named-query", "named-query-uuid",
+ namedQueryUuid);
+
+ if (nqVtx == null) {
+ String msg =
+ " Could not find named-query with namedQueryUuid = [" + namedQueryUuid + "].";
+ throw new AAIException("AAI_6114", msg);
+ } else {
+ // Multimap<String, String> topoMap = genTopoMap4NamedQ( "junkTransId", "junkFromAppId",
+ // graph, nqVtx, namedQueryUuid );
+ // System.out.println("DEBUG -- for test only : --- ");
+ // System.out.println("DEBUG -- topomap = [" + topoMap + "]");
+ }
+
+ }// End validateNamedQuery()
+
+ /**
+ * Show result set.
+ *
+ * @param resSet the res set
+ * @param levelCount the level count
+ */
+ public void showResultSet(ResultSet resSet, int levelCount) {
+
+ levelCount++;
+ String propsStr = "";
+ for (int i = 1; i <= levelCount; i++) {
+ propsStr = propsStr + "-";
+ }
+ if (resSet.getVert() == null) {
+ return;
+ }
+ String nt = resSet.getVert().<String>property(AAIProperties.NODE_TYPE).orElse(null);
+ propsStr = propsStr + "[" + nt + "] ";
+
+ // propsStr = propsStr + " newDataDelFlag = " + resSet.getNewDataDelFlag() + ", trail = " +
+ // resSet.getLocationInModelSubGraph();
+ // propsStr = propsStr + "limitDesc = [" + resSet.getPropertyLimitDesc() + "]";
+ propsStr = propsStr + " trail = " + resSet.getLocationInModelSubGraph();
+
+ Map<String, Object> overrideHash = resSet.getPropertyOverRideHash();
+ if (overrideHash != null && !overrideHash.isEmpty()) {
+ for (Map.Entry<String, Object> entry : overrideHash.entrySet()) {
+ String propName = entry.getKey();
+ Object propVal = entry.getValue();
+ propsStr = propsStr + " [" + propName + " = " + propVal + "]";
+ }
+ } else {
+ Iterator<VertexProperty<Object>> pI = resSet.getVert().properties();
+ while (pI.hasNext()) {
+ VertexProperty<Object> tp = pI.next();
+ if (!tp.key().startsWith("aai") && !tp.key().equals("source-of-truth")
+ // && ! tp.key().equals("resource-version")
+ && !tp.key().startsWith("last-mod")) {
+ propsStr = propsStr + " [" + tp.key() + " = " + tp.value() + "]";
+ }
+ }
+ }
+ // Show the "extra" lookup values too
+ Map<String, Object> extraPropHash = resSet.getExtraPropertyHash();
+ if (extraPropHash != null && !extraPropHash.isEmpty()) {
+ for (Map.Entry<String, Object> entry : extraPropHash.entrySet()) {
+ String propName = entry.getKey();
+ Object propVal = entry.getValue();
+ propsStr = propsStr + " [" + propName + " = " + propVal.toString() + "]";
+ }
+ }
+
+ System.out.println(propsStr);
+ logger.info(propsStr);
+
+ if (!resSet.getSubResultSet().isEmpty()) {
+ ListIterator<ResultSet> listItr = resSet.getSubResultSet().listIterator();
+ while (listItr.hasNext()) {
+ showResultSet(listItr.next(), levelCount);
+ }
+ }
+
+ }// end of showResultSet()
+
+ private Iterator<Vertex> traverseIncidentEdges(EdgeType treeType, Vertex startV,
+ String connectedNodeType) throws AAIException {
+ return this.engine.getQueryBuilder(startV).createEdgeTraversal(treeType, startV,
+ loader.introspectorFromName(connectedNodeType));
+ }
+
+ private Iterator<Vertex> traverseIncidentEdges(EdgeType treeType, Vertex startV,
+ String... connectedNodeType) throws AAIException {
+ QueryBuilder[] builders = new QueryBuilder[connectedNodeType.length];
+ for (int i = 0; i < connectedNodeType.length; i++) {
+ builders[i] = this.engine.getQueryBuilder(startV).createEdgeTraversal(EdgeType.TREE,
+ startV, loader.introspectorFromName(connectedNodeType[i]));
+ }
+ return this.engine.getQueryBuilder(startV).union(builders);
+ }
+
+ private String addDBAliasedSuffix(String propName) {
+ return propName + AAIProperties.DB_ALIAS_SUFFIX;
+ }
+
+ protected String getPropNameWithAliasIfNeeded(String nodeType, String propName)
+ throws AAIUnknownObjectException {
+
+ String retPropName = propName;
+ if (loader.introspectorFromName(nodeType)
+ .getPropertyMetadata(propName, PropertyMetadata.DB_ALIAS).isPresent()) {
+ return propName + AAIProperties.DB_ALIAS_SUFFIX;
+ }
+ return retPropName;
+ }
+
+}
diff --git a/aai-traversal/src/main/java/org/onap/aai/dbgraphgen/ResultSet.java b/aai-traversal/src/main/java/org/onap/aai/dbgraphgen/ResultSet.java
index 2da0e0b..d50b978 100644
--- a/aai-traversal/src/main/java/org/onap/aai/dbgraphgen/ResultSet.java
+++ b/aai-traversal/src/main/java/org/onap/aai/dbgraphgen/ResultSet.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -28,140 +28,131 @@ import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.dbgen.PropertyLimitDesc;
public class ResultSet {
- private Vertex vert;
- private String newDataDelFlag;
- private String doNotOutputFlag;
- private String locationInModelSubGraph;
- private List<ResultSet> subResultSet;
- private PropertyLimitDesc propertyLimitDesc;
- private Map<String,Object> propertyOverRideHash;
- private Map<String,Object> extraPropertyHash;
-
- /**
- * Instantiates a new result set.
- */
- public ResultSet(){
- this.vert = null;
- this.newDataDelFlag = "";
- this.doNotOutputFlag = "";
- this.locationInModelSubGraph = "";
- this.subResultSet = new ArrayList<>();
- this.propertyLimitDesc = null;
- this.propertyOverRideHash = new HashMap<>();
- this.extraPropertyHash = new HashMap<>();
- }
-
-
- public void setPropertyLimitDesc(PropertyLimitDesc pld) {
- this.propertyLimitDesc = pld;
- }
-
- /**
- * Gets the vert.
- *
- * @return the vert
- */
- public Vertex getVert(){
- return this.vert;
- }
-
- /**
- * Gets the sub result set.
- *
- * @return the sub result set
- */
- public List<ResultSet> getSubResultSet(){
- return this.subResultSet;
- }
-
- /**
- * Gets the new data del flag.
- *
- * @return the new data del flag
- */
- public String getNewDataDelFlag(){
- return this.newDataDelFlag;
- }
-
- /**
- * Gets the do not output flag.
- *
- * @return the do not output flag
- */
- public String getDoNotOutputFlag(){
- return this.doNotOutputFlag;
- }
-
- /**
- * Gets the location in model sub graph.
- *
- * @return the location in model sub graph
- */
- public String getLocationInModelSubGraph(){
- return this.locationInModelSubGraph;
- }
-
- /**
- * Gets the property limit desc.
- *
- * @return the property limit desc
- */
- public PropertyLimitDesc getPropertyLimitDesc(){
- return this.propertyLimitDesc;
- }
-
- /**
- * Gets the property over ride hash.
- *
- * @return the property over ride hash
- */
- public Map<String,Object> getPropertyOverRideHash(){
- return this.propertyOverRideHash;
- }
-
- /**
- * Gets the extra property hash.
- *
- * @return the extra property hash
- */
- public Map<String,Object> getExtraPropertyHash(){
- return this.extraPropertyHash;
- }
-
-
- public void setVert(Vertex vert) {
- this.vert = vert;
- }
-
-
- public void setNewDataDelFlag(String newDataDelFlag) {
- this.newDataDelFlag = newDataDelFlag;
- }
-
-
- public void setDoNotOutputFlag(String doNotOutputFlag) {
- this.doNotOutputFlag = doNotOutputFlag;
- }
-
-
- public void setLocationInModelSubGraph(String locationInModelSubGraph) {
- this.locationInModelSubGraph = locationInModelSubGraph;
- }
-
-
- public void setSubResultSet(List<ResultSet> subResultSet) {
- this.subResultSet = subResultSet;
- }
-
-
- public void setPropertyOverRideHash(Map<String, Object> propertyOverRideHash) {
- this.propertyOverRideHash = propertyOverRideHash;
- }
-
-
- public void setExtraPropertyHash(Map<String, Object> extraPropertyHash) {
- this.extraPropertyHash = extraPropertyHash;
- }
-
+ private Vertex vert;
+ private String newDataDelFlag;
+ private String doNotOutputFlag;
+ private String locationInModelSubGraph;
+ private List<ResultSet> subResultSet;
+ private PropertyLimitDesc propertyLimitDesc;
+ private Map<String, Object> propertyOverRideHash;
+ private Map<String, Object> extraPropertyHash;
+
+ /**
+ * Instantiates a new result set.
+ */
+ public ResultSet() {
+ this.vert = null;
+ this.newDataDelFlag = "";
+ this.doNotOutputFlag = "";
+ this.locationInModelSubGraph = "";
+ this.subResultSet = new ArrayList<>();
+ this.propertyLimitDesc = null;
+ this.propertyOverRideHash = new HashMap<>();
+ this.extraPropertyHash = new HashMap<>();
+ }
+
+ public void setPropertyLimitDesc(PropertyLimitDesc pld) {
+ this.propertyLimitDesc = pld;
+ }
+
+ /**
+ * Gets the vert.
+ *
+ * @return the vert
+ */
+ public Vertex getVert() {
+ return this.vert;
+ }
+
+ /**
+ * Gets the sub result set.
+ *
+ * @return the sub result set
+ */
+ public List<ResultSet> getSubResultSet() {
+ return this.subResultSet;
+ }
+
+ /**
+ * Gets the new data del flag.
+ *
+ * @return the new data del flag
+ */
+ public String getNewDataDelFlag() {
+ return this.newDataDelFlag;
+ }
+
+ /**
+ * Gets the do not output flag.
+ *
+ * @return the do not output flag
+ */
+ public String getDoNotOutputFlag() {
+ return this.doNotOutputFlag;
+ }
+
+ /**
+ * Gets the location in model sub graph.
+ *
+ * @return the location in model sub graph
+ */
+ public String getLocationInModelSubGraph() {
+ return this.locationInModelSubGraph;
+ }
+
+ /**
+ * Gets the property limit desc.
+ *
+ * @return the property limit desc
+ */
+ public PropertyLimitDesc getPropertyLimitDesc() {
+ return this.propertyLimitDesc;
+ }
+
+ /**
+ * Gets the property over ride hash.
+ *
+ * @return the property over ride hash
+ */
+ public Map<String, Object> getPropertyOverRideHash() {
+ return this.propertyOverRideHash;
+ }
+
+ /**
+ * Gets the extra property hash.
+ *
+ * @return the extra property hash
+ */
+ public Map<String, Object> getExtraPropertyHash() {
+ return this.extraPropertyHash;
+ }
+
+ public void setVert(Vertex vert) {
+ this.vert = vert;
+ }
+
+ public void setNewDataDelFlag(String newDataDelFlag) {
+ this.newDataDelFlag = newDataDelFlag;
+ }
+
+ public void setDoNotOutputFlag(String doNotOutputFlag) {
+ this.doNotOutputFlag = doNotOutputFlag;
+ }
+
+ public void setLocationInModelSubGraph(String locationInModelSubGraph) {
+ this.locationInModelSubGraph = locationInModelSubGraph;
+ }
+
+ public void setSubResultSet(List<ResultSet> subResultSet) {
+ this.subResultSet = subResultSet;
+ }
+
+ public void setPropertyOverRideHash(Map<String, Object> propertyOverRideHash) {
+ this.propertyOverRideHash = propertyOverRideHash;
+ }
+
+ public void setExtraPropertyHash(Map<String, Object> extraPropertyHash) {
+ this.extraPropertyHash = extraPropertyHash;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/dbgraphmap/SearchGraph.java b/aai-traversal/src/main/java/org/onap/aai/dbgraphmap/SearchGraph.java
index 1ca7c82..1dc8ac1 100644
--- a/aai-traversal/src/main/java/org/onap/aai/dbgraphmap/SearchGraph.java
+++ b/aai-traversal/src/main/java/org/onap/aai/dbgraphmap/SearchGraph.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -21,7 +21,19 @@ package org.onap.aai.dbgraphmap;
import com.google.common.base.CaseFormat;
import com.google.common.collect.Multimap;
+
import edu.emory.mathcs.backport.java.util.Collections;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.*;
+import java.util.stream.Stream;
+
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.Response;
+import javax.xml.bind.JAXBException;
+
import org.apache.commons.lang3.StringUtils;
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
@@ -63,17 +75,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.Response;
-import javax.xml.bind.JAXBException;
-import java.io.UnsupportedEncodingException;
-import java.net.URI;
-import java.util.*;
-import java.util.stream.Stream;
-
-
-
/**
* Database Mapping class which acts as the middle man between the REST interface objects for the
* Search namespace
@@ -90,7 +91,8 @@ public class SearchGraph {
private SchemaVersions schemaVersions;
@Autowired
- public SearchGraph(LoaderFactory loaderFactory, EdgeIngestor edgeIngestor, SchemaVersions schemaVersions) {
+ public SearchGraph(LoaderFactory loaderFactory, EdgeIngestor edgeIngestor,
+ SchemaVersions schemaVersions) {
this.loaderFactory = loaderFactory;
this.edgeIngestor = edgeIngestor;
this.schemaVersions = schemaVersions;
@@ -109,7 +111,8 @@ public class SearchGraph {
genericQueryBuilder.getDbEngine().startTransaction();
if (genericQueryBuilder.getStartNodeType() == null) {
- throw new AAIException("AAI_6120", "null start-node-type passed to the generic query");
+ throw new AAIException("AAI_6120",
+ "null start-node-type passed to the generic query");
}
if (genericQueryBuilder.getStartNodeKeyParams() == null) {
@@ -121,25 +124,28 @@ public class SearchGraph {
}
if (genericQueryBuilder.getDepth() > 6) {
- throw new AAIException("AAI_6120", "The maximum depth supported by the generic query is 6");
+ throw new AAIException("AAI_6120",
+ "The maximum depth supported by the generic query is 6");
}
final QueryBuilder queryBuilder;
// there is an issue with service-instance - it is a unique node but still dependent
// for now query it directly without attempting to craft a valid URI
if (genericQueryBuilder.getStartNodeType().equalsIgnoreCase("service-instance")
- && genericQueryBuilder.getStartNodeKeyParams().size() == 1) {
- genericQueryBuilder.getLoader().introspectorFromName(genericQueryBuilder.getStartNodeType());
+ && genericQueryBuilder.getStartNodeKeyParams().size() == 1) {
+ genericQueryBuilder.getLoader()
+ .introspectorFromName(genericQueryBuilder.getStartNodeType());
// Build a hash with keys to uniquely identify the start Node
String keyName;
String keyValue;
QueryBuilder builder = genericQueryBuilder.getDbEngine().getQueryBuilder()
- .getVerticesByIndexedProperty(AAIProperties.NODE_TYPE, "service-instance");
+ .getVerticesByIndexedProperty(AAIProperties.NODE_TYPE, "service-instance");
for (String keyData : genericQueryBuilder.getStartNodeKeyParams()) {
int colonIndex = keyData.indexOf(':');
if (colonIndex <= 0) {
- throw new AAIException("AAI_6120", "Bad key param passed in: [" + keyData + "]");
+ throw new AAIException("AAI_6120",
+ "Bad key param passed in: [" + keyData + "]");
} else {
keyName = keyData.substring(0, colonIndex).split("\\.")[1];
keyValue = keyData.substring(colonIndex + 1);
@@ -150,18 +156,20 @@ public class SearchGraph {
queryBuilder = builder;
} else {
URI uri = craftUriFromQueryParams(genericQueryBuilder.getLoader(),
- genericQueryBuilder.getStartNodeType(), genericQueryBuilder.getStartNodeKeyParams());
- queryBuilder =
- genericQueryBuilder.getDbEngine().getQueryBuilder().createQueryFromURI(uri).getQueryBuilder();
+ genericQueryBuilder.getStartNodeType(),
+ genericQueryBuilder.getStartNodeKeyParams());
+ queryBuilder = genericQueryBuilder.getDbEngine().getQueryBuilder()
+ .createQueryFromURI(uri).getQueryBuilder();
}
List<Vertex> results = queryBuilder.toList();
if (results.isEmpty()) {
- String errorMessage = String.format("No Node of type %s ", genericQueryBuilder.getStartNodeType(),
- " found for properties: %s", genericQueryBuilder.getStartNodeKeyParams().toString());
+ String errorMessage = String.format("No Node of type %s ",
+ genericQueryBuilder.getStartNodeType(), " found for properties: %s",
+ genericQueryBuilder.getStartNodeKeyParams().toString());
throw new AAIException("AAI_6114", errorMessage);
} else if (results.size() > 1) {
String detail = "More than one Node found by getUniqueNode for params: "
- + genericQueryBuilder.getStartNodeKeyParams().toString() + "\n";
+ + genericQueryBuilder.getStartNodeKeyParams().toString() + "\n";
throw new AAIException("AAI_6112", detail);
}
@@ -170,34 +178,39 @@ public class SearchGraph {
Collection<Vertex> ver = new HashSet<>();
List<Vertex> queryResults;
GraphTraversalSource traversalSource =
- genericQueryBuilder.getDbEngine().asAdmin().getReadOnlyTraversalSource();
+ genericQueryBuilder.getDbEngine().asAdmin().getReadOnlyTraversalSource();
GraphTraversal<Vertex, Vertex> traversal;
- if (genericQueryBuilder.getIncludeNodeTypes().contains(genericQueryBuilder.getStartNodeType())
- || genericQueryBuilder.getDepth() == 0 || genericQueryBuilder.getIncludeNodeTypes().contains("all"))
+ if (genericQueryBuilder.getIncludeNodeTypes()
+ .contains(genericQueryBuilder.getStartNodeType())
+ || genericQueryBuilder.getDepth() == 0
+ || genericQueryBuilder.getIncludeNodeTypes().contains("all"))
ver.add(startNode);
// Now look for a node of includeNodeType within a given depth
- traversal = traversalSource.withSideEffect("x", ver).V(startNode).times(genericQueryBuilder.getDepth())
- .repeat(__.both().store("x")).cap("x").unfold();
+ traversal = traversalSource.withSideEffect("x", ver).V(startNode)
+ .times(genericQueryBuilder.getDepth()).repeat(__.both().store("x")).cap("x")
+ .unfold();
if (!genericQueryBuilder.getIncludeNodeTypes().contains("all")) {
- traversal.where(__.has(AAIProperties.NODE_TYPE, P.within(genericQueryBuilder.getIncludeNodeTypes())));
+ traversal.where(__.has(AAIProperties.NODE_TYPE,
+ P.within(genericQueryBuilder.getIncludeNodeTypes())));
}
queryResults = traversal.toList();
-
if (queryResults.isEmpty()) {
- AAIException aaiException = new AAIException("AAI_6114", "No nodes found - apipe was null/empty");
+ AAIException aaiException =
+ new AAIException("AAI_6114", "No nodes found - apipe was null/empty");
ErrorLogHelper.logException(aaiException);
} else {
Introspector searchResults = createSearchResults(genericQueryBuilder.getLoader(),
- genericQueryBuilder.getUrlBuilder(), queryResults);
+ genericQueryBuilder.getUrlBuilder(), queryResults);
- String outputMediaType = getMediaType(genericQueryBuilder.getHeaders().getAcceptableMediaTypes());
+ String outputMediaType =
+ getMediaType(genericQueryBuilder.getHeaders().getAcceptableMediaTypes());
org.onap.aai.introspection.MarshallerProperties properties =
- new org.onap.aai.introspection.MarshallerProperties.Builder(
- org.onap.aai.restcore.MediaType.getEnum(outputMediaType)).build();
+ new org.onap.aai.introspection.MarshallerProperties.Builder(
+ org.onap.aai.restcore.MediaType.getEnum(outputMediaType)).build();
result = searchResults.marshal(properties);
response = Response.ok().entity(result).build();
@@ -225,8 +238,8 @@ public class SearchGraph {
return response;
}
- private URI craftUriFromQueryParams(Loader loader, String startNodeType, List<String> startNodeKeyParams)
- throws UnsupportedEncodingException, AAIException {
+ private URI craftUriFromQueryParams(Loader loader, String startNodeType,
+ List<String> startNodeKeyParams) throws UnsupportedEncodingException, AAIException {
Introspector relationship = loader.introspectorFromName("relationship");
relationship.setValue("related-to", startNodeType);
@@ -271,40 +284,48 @@ public class SearchGraph {
Introspector target;
if (StringUtils.isBlank(nodesQuery.getTargetNodeType())) {
- throw new AAIException("AAI_6120", "null or empty target-node-type passed to the node query");
+ throw new AAIException("AAI_6120",
+ "null or empty target-node-type passed to the node query");
}
try {
- target = nodesQuery.getLoader().introspectorFromName(nodesQuery.getTargetNodeType());
+ target =
+ nodesQuery.getLoader().introspectorFromName(nodesQuery.getTargetNodeType());
} catch (AAIUnknownObjectException e) {
- throw new AAIException("AAI_6115",
- "Unrecognized nodeType [" + nodesQuery.getTargetNodeType() + "] passed to node query.");
+ throw new AAIException("AAI_6115", "Unrecognized nodeType ["
+ + nodesQuery.getTargetNodeType() + "] passed to node query.");
}
- if (nodesQuery.getFilterParams().isEmpty() && nodesQuery.getEdgeFilterParams().isEmpty()) {
- // For now, it's ok to pass no filter params. We'll just return ALL the nodes of the requested type.
+ if (nodesQuery.getFilterParams().isEmpty()
+ && nodesQuery.getEdgeFilterParams().isEmpty()) {
+ // For now, it's ok to pass no filter params. We'll just return ALL the nodes of the
+ // requested type.
LOGGER.debug("No filters passed to the node query");
}
- GraphTraversal<Vertex, Vertex> traversal = nodesQuery.getDbEngine().asAdmin().getReadOnlyTraversalSource()
- .V().has(AAIProperties.NODE_TYPE, nodesQuery.getTargetNodeType());
+ GraphTraversal<Vertex, Vertex> traversal =
+ nodesQuery.getDbEngine().asAdmin().getReadOnlyTraversalSource().V()
+ .has(AAIProperties.NODE_TYPE, nodesQuery.getTargetNodeType());
for (String filter : nodesQuery.getFilterParams()) {
String[] pieces = filter.split(":");
if (pieces.length < 2) {
- throw new AAIException("AAI_6120", "bad filter passed to node query: [" + filter + "]");
+ throw new AAIException("AAI_6120",
+ "bad filter passed to node query: [" + filter + "]");
} else {
String propName = this.findDbPropName(target, pieces[0]);
String filterType = pieces[1];
if (filterType.equals(EQUALS)) {
if (pieces.length < 3) {
- throw new AAIException("AAI_6120", "No value passed for filter: [" + filter + "]");
+ throw new AAIException("AAI_6120",
+ "No value passed for filter: [" + filter + "]");
}
String value = "?";
if (pieces.length == 3) {
value = pieces[2];
} else { // length > 3
- // When a ipv6 address comes in as a value, it has colons in it which require us to
+ // When a ipv6 address comes in as a value, it has colons in it which
+ // require us to
// pull the "value" off the end of the filter differently
int startPos4Value = propName.length() + filterType.length() + 3;
value = filter.substring(startPos4Value);
@@ -312,13 +333,15 @@ public class SearchGraph {
traversal.has(propName, value);
} else if (filterType.equals(DOES_NOT_EQUAL)) {
if (pieces.length < 3) {
- throw new AAIException("AAI_6120", "No value passed for filter: [" + filter + "]");
+ throw new AAIException("AAI_6120",
+ "No value passed for filter: [" + filter + "]");
}
String value = "?";
if (pieces.length == 3) {
value = pieces[2];
} else { // length > 3
- // When a ipv6 address comes in as a value, it has colons in it which require us to
+ // When a ipv6 address comes in as a value, it has colons in it which
+ // require us to
// pull the "value" off the end of the filter differently
int startPos4Value = propName.length() + filterType.length() + 3;
value = filter.substring(startPos4Value);
@@ -329,7 +352,8 @@ public class SearchGraph {
} else if (filterType.equals(DOES_NOT_EXIST)) {
traversal.hasNot(propName);
} else {
- throw new AAIException("AAI_6120", "bad filterType passed: [" + filterType + "]");
+ throw new AAIException("AAI_6120",
+ "bad filterType passed: [" + filterType + "]");
}
}
}
@@ -337,7 +361,8 @@ public class SearchGraph {
if (!nodesQuery.getEdgeFilterParams().isEmpty()) {
// edge-filter=pserver:EXISTS: OR pserver:EXISTS:hostname:XXX
// edge-filter=pserver:DOES-NOT-EXIST: OR pserver:DOES-NOT-EXIST:hostname:XXX
- String filter = nodesQuery.getEdgeFilterParams().get(0); // we process and allow only one edge filter
+ String filter = nodesQuery.getEdgeFilterParams().get(0); // we process and allow
+ // only one edge filter
// for now
String[] pieces = filter.split(":");
if (pieces.length < 2 || pieces.length == 3 || pieces.length > 4) {
@@ -347,13 +372,14 @@ public class SearchGraph {
String filterType = pieces[1].toUpperCase();
Introspector otherNode;
if (!filterType.equals(EXISTS) && !filterType.equals(DOES_NOT_EXIST)) {
- throw new AAIException("AAI_6120", "bad filterType passed: [" + filterType + "]");
+ throw new AAIException("AAI_6120",
+ "bad filterType passed: [" + filterType + "]");
}
try {
otherNode = nodesQuery.getLoader().introspectorFromName(nodeType);
} catch (AAIUnknownObjectException e) {
throw new AAIException("AAI_6115",
- "Unrecognized nodeType [" + nodeType + "] passed to node query.");
+ "Unrecognized nodeType [" + nodeType + "] passed to node query.");
}
String propName = null;
String propValue = null;
@@ -385,12 +411,13 @@ public class SearchGraph {
List<Vertex> results = traversal.toList();
Introspector searchResults =
- createSearchResults(nodesQuery.getLoader(), nodesQuery.getUrlBuilder(), results);
+ createSearchResults(nodesQuery.getLoader(), nodesQuery.getUrlBuilder(), results);
- String outputMediaType = getMediaType(nodesQuery.getHeaders().getAcceptableMediaTypes());
+ String outputMediaType =
+ getMediaType(nodesQuery.getHeaders().getAcceptableMediaTypes());
org.onap.aai.introspection.MarshallerProperties properties =
- new org.onap.aai.introspection.MarshallerProperties.Builder(
- org.onap.aai.restcore.MediaType.getEnum(outputMediaType)).build();
+ new org.onap.aai.introspection.MarshallerProperties.Builder(
+ org.onap.aai.restcore.MediaType.getEnum(outputMediaType)).build();
result = searchResults.marshal(properties);
response = Response.ok().entity(result).build();
@@ -415,8 +442,8 @@ public class SearchGraph {
return response;
}
- protected Introspector createSearchResults(Loader loader, UrlBuilder urlBuilder, List<Vertex> results)
- throws AAIUnknownObjectException {
+ protected Introspector createSearchResults(Loader loader, UrlBuilder urlBuilder,
+ List<Vertex> results) throws AAIUnknownObjectException {
Introspector searchResults = loader.introspectorFromName("search-results");
List<Object> resultDataList = searchResults.getValue("result-data");
Stream<Vertex> stream;
@@ -461,7 +488,6 @@ public class SearchGraph {
}
}
-
/**
* Gets the edge label.
*
@@ -471,8 +497,7 @@ public class SearchGraph {
* @throws EdgeRuleNotFoundException The Edge Rule Not Found Exception
*/
public String[] getEdgeLabel(String targetNodeType, String nodeType)
- throws EdgeRuleNotFoundException {
-
+ throws EdgeRuleNotFoundException {
EdgeRuleQuery query = new EdgeRuleQuery.Builder(targetNodeType, nodeType).build();
Multimap<String, EdgeRule> edgeRules = edgeIngestor.getRules(query);
@@ -480,7 +505,6 @@ public class SearchGraph {
return edgeRules.values().stream().map(EdgeRule::getLabel).toArray(String[]::new);
}
-
/**
* Run named query.
*
@@ -493,7 +517,7 @@ public class SearchGraph {
* @throws AAIException the AAI exception
*/
public Response runNamedQuery(String fromAppId, String transId, String queryParameters,
- AAIExtensionMap aaiExtMap) throws AAIException {
+ AAIExtensionMap aaiExtMap) throws AAIException {
Introspector inventoryItems;
boolean success = true;
@@ -501,15 +525,16 @@ public class SearchGraph {
try {
MoxyLoader loader = (MoxyLoader) loaderFactory.createLoaderForVersion(ModelType.MOXY,
- schemaVersions.getDefaultVersion());
+ schemaVersions.getDefaultVersion());
DynamicJAXBContext jaxbContext = loader.getJAXBContext();
dbEngine = new JanusGraphDBEngine(QueryStyle.TRAVERSAL, loader);
- DBSerializer serializer =
- new DBSerializer(schemaVersions.getDefaultVersion(), dbEngine, ModelType.MOXY, fromAppId);
+ DBSerializer serializer = new DBSerializer(schemaVersions.getDefaultVersion(), dbEngine,
+ ModelType.MOXY, fromAppId);
ModelBasedProcessing processor = new ModelBasedProcessing(loader, dbEngine, serializer);
dbEngine.startTransaction();
- org.onap.aai.restcore.MediaType mediaType = org.onap.aai.restcore.MediaType.APPLICATION_JSON_TYPE;
+ org.onap.aai.restcore.MediaType mediaType =
+ org.onap.aai.restcore.MediaType.APPLICATION_JSON_TYPE;
String contentType = aaiExtMap.getHttpServletRequest().getContentType();
if (contentType != null && contentType.contains("application/xml")) {
mediaType = org.onap.aai.restcore.MediaType.APPLICATION_XML_TYPE;
@@ -520,7 +545,8 @@ public class SearchGraph {
}
DynamicEntity modelAndNamedQuerySearch = (DynamicEntity) loader
- .unmarshal("ModelAndNamedQuerySearch", queryParameters, mediaType).getUnderlyingObject();
+ .unmarshal("ModelAndNamedQuerySearch", queryParameters, mediaType)
+ .getUnderlyingObject();
if (modelAndNamedQuerySearch == null) {
throw new AAIException("AAI_5105");
}
@@ -538,7 +564,8 @@ public class SearchGraph {
namedQueryLookupHash.put("named-query-name", namedQuery.get("namedQueryName"));
}
if (namedQuery.isSet("namedQueryVersion")) {
- namedQueryLookupHash.put("named-query-version", namedQuery.get("namedQueryVersion"));
+ namedQueryLookupHash.put("named-query-version",
+ namedQuery.get("namedQueryVersion"));
}
}
@@ -546,7 +573,7 @@ public class SearchGraph {
DbMethHelper dbMethHelper = new DbMethHelper(loader, dbEngine);
List<Vertex> namedQueryVertices =
- dbMethHelper.locateUniqueVertices("named-query", namedQueryLookupHash);
+ dbMethHelper.locateUniqueVertices("named-query", namedQueryLookupHash);
for (Vertex vert : namedQueryVertices) {
namedQueryUuid = vert.<String>property("named-query-uuid").orElse(null);
// there should only be one, we'll pick the first if not
@@ -563,15 +590,16 @@ public class SearchGraph {
List<Map<String, Object>> startNodeFilterHash = new ArrayList<>();
mapInstanceFilters(modelAndNamedQuerySearch.get("instanceFilters"), startNodeFilterHash,
- jaxbContext);
+ jaxbContext);
Map<String, Object> secondaryFilterHash = new HashMap<>();
mapSecondaryFilters(modelAndNamedQuerySearch.get("secondaryFilts"), secondaryFilterHash,
- jaxbContext);
+ jaxbContext);
- List<ResultSet> resultSet = processor.queryByNamedQuery(transId, fromAppId, namedQueryUuid,
- startNodeFilterHash, aaiExtMap.getApiVersion(), secondaryFilterCutPoint, secondaryFilterHash);
+ List<ResultSet> resultSet =
+ processor.queryByNamedQuery(transId, fromAppId, namedQueryUuid, startNodeFilterHash,
+ aaiExtMap.getApiVersion(), secondaryFilterCutPoint, secondaryFilterHash);
inventoryItems = loader.introspectorFromName("inventory-response-items");
@@ -613,24 +641,23 @@ public class SearchGraph {
* @throws UnsupportedEncodingException the unsupported encoding exception
*/
public Response executeModelOperation(String fromAppId, String transId, String queryParameters,
- boolean isDelete, AAIExtensionMap aaiExtMap)
- throws AAIException {
+ boolean isDelete, AAIExtensionMap aaiExtMap) throws AAIException {
Response response;
boolean success = true;
TransactionalGraphEngine dbEngine = null;
try {
MoxyLoader loader = (MoxyLoader) loaderFactory.createLoaderForVersion(ModelType.MOXY,
- schemaVersions.getDefaultVersion());
+ schemaVersions.getDefaultVersion());
DynamicJAXBContext jaxbContext = loader.getJAXBContext();
dbEngine = new JanusGraphDBEngine(QueryStyle.TRAVERSAL, loader);
- DBSerializer serializer =
- new DBSerializer(schemaVersions.getDefaultVersion(), dbEngine, ModelType.MOXY, fromAppId);
+ DBSerializer serializer = new DBSerializer(schemaVersions.getDefaultVersion(), dbEngine,
+ ModelType.MOXY, fromAppId);
ModelBasedProcessing processor = new ModelBasedProcessing(loader, dbEngine, serializer);
dbEngine.startTransaction();
-
- org.onap.aai.restcore.MediaType mediaType = org.onap.aai.restcore.MediaType.APPLICATION_JSON_TYPE;
+ org.onap.aai.restcore.MediaType mediaType =
+ org.onap.aai.restcore.MediaType.APPLICATION_JSON_TYPE;
String contentType = aaiExtMap.getHttpServletRequest().getContentType();
if (contentType != null && contentType.contains("application/xml")) {
mediaType = org.onap.aai.restcore.MediaType.APPLICATION_XML_TYPE;
@@ -641,12 +668,12 @@ public class SearchGraph {
}
DynamicEntity modelAndNamedQuerySearch = (DynamicEntity) loader
- .unmarshal("ModelAndNamedQuerySearch", queryParameters, mediaType).getUnderlyingObject();
+ .unmarshal("ModelAndNamedQuerySearch", queryParameters, mediaType)
+ .getUnderlyingObject();
if (modelAndNamedQuerySearch == null) {
throw new AAIException("AAI_5105");
}
-
String modelVersionId = null;
String modelName = null;
String modelInvariantId = null;
@@ -663,7 +690,8 @@ public class SearchGraph {
// 2. model-invariant-id (previously model-id) + model-version
// 3. model-name + model-version
- // we will support both using the OverloadedModel object in the v9 oxm. This allows us to unmarshal
+ // we will support both using the OverloadedModel object in the v9 oxm. This allows us
+ // to unmarshal
// either an old-style model or new-style model + model-ver object
if (modelAndNamedQuerySearch.isSet("queryParameters")) {
DynamicEntity qp = modelAndNamedQuerySearch.get("queryParameters");
@@ -715,12 +743,13 @@ public class SearchGraph {
List<Map<String, Object>> startNodeFilterHash = new ArrayList<>();
- String resourceVersion = mapInstanceFilters( modelAndNamedQuerySearch.get("instanceFilters"),
- startNodeFilterHash, jaxbContext);
+ String resourceVersion = mapInstanceFilters(
+ modelAndNamedQuerySearch.get("instanceFilters"), startNodeFilterHash, jaxbContext);
if (isDelete) {
- List<ResultSet> resultSet = processor.queryByModel(transId, fromAppId, modelVersionId, modelInvariantId,
+ List<ResultSet> resultSet =
+ processor.queryByModel(transId, fromAppId, modelVersionId, modelInvariantId,
modelName, topNodeType, startNodeFilterHash, aaiExtMap.getApiVersion());
unpackResultSet(resultSet, dbEngine, loader, serializer);
@@ -730,8 +759,9 @@ public class SearchGraph {
Vertex firstVert = rs.getVert();
String restURI = serializer.getURIForVertex(firstVert).toString();
String notificationVersion = schemaVersions.getDefaultVersion().toString();
- Map<String, String> delResult = processor.runDeleteByModel(transId, fromAppId, modelVersionId,
- topNodeType, startNodeFilterHash.get(0), aaiExtMap.getApiVersion(), resourceVersion);
+ Map<String, String> delResult =
+ processor.runDeleteByModel(transId, fromAppId, modelVersionId, topNodeType,
+ startNodeFilterHash.get(0), aaiExtMap.getApiVersion(), resourceVersion);
String resultStr = "";
for (Map.Entry<String, String> ent : delResult.entrySet()) {
@@ -744,10 +774,12 @@ public class SearchGraph {
response = Response.ok(resultStr.trim()).build();
} else {
- List<ResultSet> resultSet = processor.queryByModel(transId, fromAppId, modelVersionId, modelInvariantId,
+ List<ResultSet> resultSet =
+ processor.queryByModel(transId, fromAppId, modelVersionId, modelInvariantId,
modelName, topNodeType, startNodeFilterHash, aaiExtMap.getApiVersion());
- Introspector inventoryItems = loader.introspectorFromName("inventory-response-items");
+ Introspector inventoryItems =
+ loader.introspectorFromName("inventory-response-items");
List<Object> invItemList = unpackResultSet(resultSet, dbEngine, loader, serializer);
@@ -786,10 +818,10 @@ public class SearchGraph {
org.onap.aai.introspection.MarshallerProperties properties;
if (isJson) {
properties = new org.onap.aai.introspection.MarshallerProperties.Builder(
- org.onap.aai.restcore.MediaType.APPLICATION_JSON_TYPE).build();
+ org.onap.aai.restcore.MediaType.APPLICATION_JSON_TYPE).build();
} else {
properties = new org.onap.aai.introspection.MarshallerProperties.Builder(
- org.onap.aai.restcore.MediaType.APPLICATION_XML_TYPE).build();
+ org.onap.aai.restcore.MediaType.APPLICATION_XML_TYPE).build();
}
String marshalledObj = obj.marshal(properties);
@@ -804,14 +836,15 @@ public class SearchGraph {
* @param jaxbContext the jaxb context
* @return the string
*/
- private String mapInstanceFilters(DynamicEntity instanceFilters, List<Map<String, Object>> startNodeFilterHash,
- DynamicJAXBContext jaxbContext) {
+ private String mapInstanceFilters(DynamicEntity instanceFilters,
+ List<Map<String, Object>> startNodeFilterHash, DynamicJAXBContext jaxbContext) {
if (instanceFilters == null || !instanceFilters.isSet("instanceFilter")) {
return null;
}
@SuppressWarnings("unchecked")
- List<DynamicEntity> instanceFilter = (ArrayList<DynamicEntity>) instanceFilters.get("instanceFilter");
+ List<DynamicEntity> instanceFilter =
+ (ArrayList<DynamicEntity>) instanceFilters.get("instanceFilter");
String resourceVersion = null;
for (DynamicEntity instFilt : instanceFilter) {
@@ -829,8 +862,9 @@ public class SearchGraph {
// hyphencase the prop and throw it on the hash
if (anyEnt.isSet(propName)) {
thisNodeFilterHash.put(
- nodeType + "." + CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propName),
- anyEnt.get(propName));
+ nodeType + "."
+ + CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propName),
+ anyEnt.get(propName));
if (propName.equals("resourceVersion") && resourceVersion == null) {
resourceVersion = (String) anyEnt.get(propName);
}
@@ -850,14 +884,15 @@ public class SearchGraph {
* @param jaxbContext the jaxb context
* @return the string
*/
- private void mapSecondaryFilters(DynamicEntity secondaryFilts, Map<String, Object> secondaryFilterHash,
- DynamicJAXBContext jaxbContext) {
+ private void mapSecondaryFilters(DynamicEntity secondaryFilts,
+ Map<String, Object> secondaryFilterHash, DynamicJAXBContext jaxbContext) {
if (secondaryFilts == null || !secondaryFilts.isSet("secondaryFilt")) {
return;
}
@SuppressWarnings("unchecked")
- List<DynamicEntity> secondaryFilter = (ArrayList<DynamicEntity>) secondaryFilts.get("secondaryFilt");
+ List<DynamicEntity> secondaryFilter =
+ (ArrayList<DynamicEntity>) secondaryFilts.get("secondaryFilt");
for (DynamicEntity secondaryFilt : secondaryFilter) {
List<DynamicEntity> any = secondaryFilt.get("any");
@@ -874,8 +909,9 @@ public class SearchGraph {
// hyphencase the prop and throw it on the hash
if (anyEnt.isSet(propName)) {
secondaryFilterHash.put(
- nodeType + "." + CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propName),
- anyEnt.get(propName));
+ nodeType + "."
+ + CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, propName),
+ anyEnt.get(propName));
}
}
}
@@ -892,12 +928,12 @@ public class SearchGraph {
* @param aaiExtMap the aai ext map
* @return the dynamic entity
*/
- private DynamicEntity remapInventoryItems(DynamicEntity invResultItem, DynamicJAXBContext jaxbContext,
- Map<String, String> includeTheseVertices, Map<Object, String> objectToVertMap, AAIExtensionMap aaiExtMap) {
-
+ private DynamicEntity remapInventoryItems(DynamicEntity invResultItem,
+ DynamicJAXBContext jaxbContext, Map<String, String> includeTheseVertices,
+ Map<Object, String> objectToVertMap, AAIExtensionMap aaiExtMap) {
- DynamicEntity inventoryItem = jaxbContext
- .newDynamicEntity("inventory.aai.onap.org." + aaiExtMap.getApiVersion() + ".InventoryResponseItem");
+ DynamicEntity inventoryItem = jaxbContext.newDynamicEntity(
+ "inventory.aai.onap.org." + aaiExtMap.getApiVersion() + ".InventoryResponseItem");
Object item = invResultItem.get("item");
inventoryItem.set("modelName", invResultItem.get("modelName"));
inventoryItem.set("item", item);
@@ -909,16 +945,17 @@ public class SearchGraph {
vertexId = objectToVertMap.get(item);
}
- if (includeTheseVertices.containsKey(vertexId) && invResultItem.isSet("inventoryResponseItems")) {
+ if (includeTheseVertices.containsKey(vertexId)
+ && invResultItem.isSet("inventoryResponseItems")) {
List<DynamicEntity> invItemList = new ArrayList<>();
DynamicEntity inventoryItems = jaxbContext.newDynamicEntity(
- "inventory.aai.att.com." + aaiExtMap.getApiVersion() + ".InventoryResponseItems");
+ "inventory.aai.att.com." + aaiExtMap.getApiVersion() + ".InventoryResponseItems");
DynamicEntity subInventoryResponseItems = invResultItem.get("inventoryResponseItems");
List<DynamicEntity> subInventoryResponseItemList =
- subInventoryResponseItems.get("inventoryResponseItem");
+ subInventoryResponseItems.get("inventoryResponseItem");
for (DynamicEntity ent : subInventoryResponseItemList) {
- DynamicEntity invItem =
- remapInventoryItems(ent, jaxbContext, includeTheseVertices, objectToVertMap, aaiExtMap);
+ DynamicEntity invItem = remapInventoryItems(ent, jaxbContext, includeTheseVertices,
+ objectToVertMap, aaiExtMap);
if (invItem != null) {
invItemList.add(invItem);
}
@@ -939,8 +976,9 @@ public class SearchGraph {
* @return the array list - should return list of inventoryItems
* @throws AAIException The AAI Exception
*/
- private List<Object> unpackResultSet(List<ResultSet> resultSetList, TransactionalGraphEngine engine, Loader loader,
- DBSerializer serializer) throws AAIException {
+ private List<Object> unpackResultSet(List<ResultSet> resultSetList,
+ TransactionalGraphEngine engine, Loader loader, DBSerializer serializer)
+ throws AAIException {
List<Object> resultList = new ArrayList<>();
@@ -965,7 +1003,8 @@ public class SearchGraph {
if (resultSet.getExtraPropertyHash() != null) {
Map<String, Object> extraProperties = resultSet.getExtraPropertyHash();
- Introspector extraPropertiesEntity = loader.introspectorFromName("extra-properties");
+ Introspector extraPropertiesEntity =
+ loader.introspectorFromName("extra-properties");
List<Object> extraPropsList = extraPropertiesEntity.getValue("extra-property");
@@ -973,7 +1012,8 @@ public class SearchGraph {
String propName = ent.getKey();
Object propVal = ent.getValue();
- Introspector extraPropEntity = loader.introspectorFromName("extra-property");
+ Introspector extraPropEntity =
+ loader.introspectorFromName("extra-property");
extraPropEntity.setValue("property-name", propName);
extraPropEntity.setValue("property-value", propVal);
@@ -981,11 +1021,13 @@ public class SearchGraph {
extraPropsList.add(extraPropEntity.getUnderlyingObject());
}
- inventoryItem.setValue("extra-properties", extraPropertiesEntity.getUnderlyingObject());
+ inventoryItem.setValue("extra-properties",
+ extraPropertiesEntity.getUnderlyingObject());
}
try {
- serializer.dbToObject(Collections.singletonList(vert), thisObj, 0, true, "false");
+ serializer.dbToObject(Collections.singletonList(vert), thisObj, 0, true,
+ "false");
} catch (UnsupportedEncodingException e1) {
throw new AAIException("AAI_5105");
}
@@ -1001,7 +1043,8 @@ public class SearchGraph {
filterProperties(thisObj, emptyPropertyOverRideHash);
} else if (PropertyLimitDesc.SHOW_ALL.equals(propertyLimitDesc)) {
// keep everything
- } else if (PropertyLimitDesc.SHOW_NAME_AND_KEYS_ONLY.equals(propertyLimitDesc)) {
+ } else if (PropertyLimitDesc.SHOW_NAME_AND_KEYS_ONLY
+ .equals(propertyLimitDesc)) {
HashMap<String, Object> keysAndNamesPropHash = new HashMap<>();
for (String key : thisObj.getAllKeys()) {
@@ -1017,8 +1060,10 @@ public class SearchGraph {
filterProperties(thisObj, keysAndNamesPropHash);
}
} else {
- if (resultSet.getPropertyOverRideHash() != null && resultSet.getPropertyOverRideHash().size() > 0) {
- Map<String, Object> propertyOverRideHash = resultSet.getPropertyOverRideHash();
+ if (resultSet.getPropertyOverRideHash() != null
+ && resultSet.getPropertyOverRideHash().size() > 0) {
+ Map<String, Object> propertyOverRideHash =
+ resultSet.getPropertyOverRideHash();
if (propertyOverRideHash.containsKey("persona-model-id")) {
propertyOverRideHash.remove("persona-model-id");
propertyOverRideHash.put("model-invariant-id", null);
@@ -1037,25 +1082,32 @@ public class SearchGraph {
String modelName = null;
try {
- // Try to get the modelName if we can. Otherwise, do not fail, just return what we have already.
+ // Try to get the modelName if we can. Otherwise, do not fail, just return
+ // what we have already.
String modelInvariantIdLocal =
- vert.<String>property("model-invariant-id-local").orElse(null); // this one
- // points at a
- // model
+ vert.<String>property("model-invariant-id-local").orElse(null); // this
+ // one
+ // points
+ // at a
+ // model
String modelVersionIdLocal =
- vert.<String>property("model-version-id-local").orElse(null); // this one
- // points at a
- // model-ver
+ vert.<String>property("model-version-id-local").orElse(null); // this
+ // one
+ // points
+ // at a
+ // model-ver
if ((modelInvariantIdLocal != null && modelVersionIdLocal != null)
- && (modelInvariantIdLocal.length() > 0 && modelVersionIdLocal.length() > 0)) {
+ && (modelInvariantIdLocal.length() > 0
+ && modelVersionIdLocal.length() > 0)) {
Introspector modelVer = loader.introspectorFromName("model-ver");
modelVer.setValue("model-version-id", modelVersionIdLocal);
QueryBuilder builder = engine.getQueryBuilder().createDBQuery(modelVer);
List<Vertex> modelVerVerts = builder.toList();
if ((modelVerVerts != null) && (modelVerVerts.size() == 1)) {
Vertex modelVerVert = modelVerVerts.get(0);
- modelName = modelVerVert.<String>property("model-name").orElse(null);
+ modelName =
+ modelVerVert.<String>property("model-name").orElse(null);
if (modelName != null && modelName.length() > 0) {
inventoryItem.setValue("model-name", modelName);
}
@@ -1069,11 +1121,12 @@ public class SearchGraph {
if (resultSet.getSubResultSet() != null) {
List<ResultSet> subResultSet = resultSet.getSubResultSet();
if (subResultSet != null && !subResultSet.isEmpty()) {
- List<Object> res = unpackResultSet(subResultSet, engine, loader, serializer);
+ List<Object> res =
+ unpackResultSet(subResultSet, engine, loader, serializer);
if (!res.isEmpty()) {
inventoryItems.setValue("inventory-response-item", res);
inventoryItem.setValue("inventory-response-items",
- inventoryItems.getUnderlyingObject());
+ inventoryItems.getUnderlyingObject());
}
}
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/AAIContainerFilter.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/AAIContainerFilter.java
index f70febf..92c12b5 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/AAIContainerFilter.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/AAIContainerFilter.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -23,19 +23,19 @@ import java.util.UUID;
import org.onap.aai.util.FormatDate;
-public abstract class AAIContainerFilter {
-
- protected String genDate() {
- FormatDate fd = new FormatDate("YYMMdd-HH:mm:ss:SSS");
- return fd.getDateTime();
- }
-
- protected boolean isValidUUID(String transId) {
- try {
- UUID.fromString(transId);
- } catch (IllegalArgumentException e) {
- return false;
- }
- return true;
- }
+public abstract class AAIContainerFilter {
+
+ protected String genDate() {
+ FormatDate fd = new FormatDate("YYMMdd-HH:mm:ss:SSS");
+ return fd.getDateTime();
+ }
+
+ protected boolean isValidUUID(String transId) {
+ try {
+ UUID.fromString(transId);
+ } catch (IllegalArgumentException e) {
+ return false;
+ }
+ return true;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/AAIHeaderProperties.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/AAIHeaderProperties.java
index f27e4f2..22c8234 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/AAIHeaderProperties.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/AAIHeaderProperties.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -21,20 +21,21 @@ package org.onap.aai.interceptors;
public final class AAIHeaderProperties {
- public static final String REQUEST_CONTEXT = "aai-request-context";
+ public static final String REQUEST_CONTEXT = "aai-request-context";
- public static final String HTTP_METHOD_OVERRIDE = "X-HTTP-Method-Override";
+ public static final String HTTP_METHOD_OVERRIDE = "X-HTTP-Method-Override";
- public static final String TRANSACTION_ID = "X-TransactionId";
+ public static final String TRANSACTION_ID = "X-TransactionId";
- public static final String FROM_APP_ID = "X-FromAppId";
+ public static final String FROM_APP_ID = "X-FromAppId";
- public static final String AAI_TX_ID = "X-AAI-TXID";
+ public static final String AAI_TX_ID = "X-AAI-TXID";
- public static final String AAI_REQUEST = "X-REQUEST";
+ public static final String AAI_REQUEST = "X-REQUEST";
- public static final String AAI_REQUEST_TS = "X-REQUEST-TS";
+ public static final String AAI_REQUEST_TS = "X-REQUEST-TS";
- private AAIHeaderProperties(){}
+ private AAIHeaderProperties() {
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/package-info.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/package-info.java
index ee9c334..15a997a 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/package-info.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/package-info.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,11 +26,11 @@
*
* <pre>
* <code>
- * @Priority(AAIRequestFilterPriority.YOUR_PRIORITY)
+ * &#64;Priority(AAIRequestFilterPriority.YOUR_PRIORITY)
* public class YourInterceptor extends AAIContainerFilter implements ContainerRequestFilter {
*
* }
* </code>
* </pre>
*/
-package org.onap.aai.interceptors; \ No newline at end of file
+package org.onap.aai.interceptors;
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/post/AAIResponseFilterPriority.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/post/AAIResponseFilterPriority.java
index ccf89fc..cf899c1 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/post/AAIResponseFilterPriority.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/post/AAIResponseFilterPriority.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,13 +26,14 @@ package org.onap.aai.interceptors.post;
* and INVALID_RESPONSE_STATUS
*/
public final class AAIResponseFilterPriority {
-
- private AAIResponseFilterPriority() {}
- public static final int INVALID_RESPONSE_STATUS = 1000;
+ private AAIResponseFilterPriority() {
+ }
- public static final int RESPONSE_TRANS_LOGGING = 3000;
+ public static final int INVALID_RESPONSE_STATUS = 1000;
- public static final int HEADER_MANIPULATION = 4000;
+ public static final int RESPONSE_TRANS_LOGGING = 3000;
+
+ public static final int HEADER_MANIPULATION = 4000;
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/post/InvalidResponseStatus.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/post/InvalidResponseStatus.java
index 7fd0b9c..b28f0dd 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/post/InvalidResponseStatus.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/post/InvalidResponseStatus.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,47 +19,48 @@
*/
package org.onap.aai.interceptors.post;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.interceptors.AAIContainerFilter;
-import org.onap.aai.logging.ErrorLogHelper;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MediaType;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
+
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.interceptors.AAIContainerFilter;
+import org.onap.aai.logging.ErrorLogHelper;
@Priority(AAIResponseFilterPriority.INVALID_RESPONSE_STATUS)
public class InvalidResponseStatus extends AAIContainerFilter implements ContainerResponseFilter {
- @Override
- public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
- throws IOException {
+ @Override
+ public void filter(ContainerRequestContext requestContext,
+ ContainerResponseContext responseContext) throws IOException {
- if(responseContext.getStatus() == 405){
+ if (responseContext.getStatus() == 405) {
- responseContext.setStatus(400);
- AAIException e = new AAIException("AAI_3012");
- ArrayList<String> templateVars = new ArrayList<>();
+ responseContext.setStatus(400);
+ AAIException e = new AAIException("AAI_3012");
+ ArrayList<String> templateVars = new ArrayList<>();
- List<MediaType> mediaTypeList = new ArrayList<>();
+ List<MediaType> mediaTypeList = new ArrayList<>();
- String contentType = responseContext.getHeaderString("Content-Type");
+ String contentType = responseContext.getHeaderString("Content-Type");
- if (contentType == null) {
- mediaTypeList.add(MediaType.APPLICATION_XML_TYPE);
- } else {
- mediaTypeList.add(MediaType.valueOf(contentType));
- }
+ if (contentType == null) {
+ mediaTypeList.add(MediaType.APPLICATION_XML_TYPE);
+ } else {
+ mediaTypeList.add(MediaType.valueOf(contentType));
+ }
- String message = ErrorLogHelper.getRESTAPIErrorResponse(mediaTypeList, e, templateVars);
+ String message = ErrorLogHelper.getRESTAPIErrorResponse(mediaTypeList, e, templateVars);
- responseContext.setEntity(message);
- }
+ responseContext.setEntity(message);
+ }
- }
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/post/ResponseHeaderManipulation.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/post/ResponseHeaderManipulation.java
index 9d4efe7..d13b122 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/post/ResponseHeaderManipulation.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/post/ResponseHeaderManipulation.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,46 +19,49 @@
*/
package org.onap.aai.interceptors.post;
-import org.onap.aai.interceptors.AAIContainerFilter;
-import org.onap.aai.interceptors.AAIHeaderProperties;
+import java.io.IOException;
import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerResponseContext;
import javax.ws.rs.container.ContainerResponseFilter;
import javax.ws.rs.core.MediaType;
-import java.io.IOException;
+
+import org.onap.aai.interceptors.AAIContainerFilter;
+import org.onap.aai.interceptors.AAIHeaderProperties;
@Priority(AAIResponseFilterPriority.HEADER_MANIPULATION)
-public class ResponseHeaderManipulation extends AAIContainerFilter implements ContainerResponseFilter {
+public class ResponseHeaderManipulation extends AAIContainerFilter
+ implements ContainerResponseFilter {
- private static final String DEFAULT_XML_TYPE = MediaType.APPLICATION_XML;
+ private static final String DEFAULT_XML_TYPE = MediaType.APPLICATION_XML;
- @Override
- public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
- throws IOException {
+ @Override
+ public void filter(ContainerRequestContext requestContext,
+ ContainerResponseContext responseContext) throws IOException {
- updateResponseHeaders(requestContext, responseContext);
+ updateResponseHeaders(requestContext, responseContext);
- }
+ }
- private void updateResponseHeaders(ContainerRequestContext requestContext,
- ContainerResponseContext responseContext) {
+ private void updateResponseHeaders(ContainerRequestContext requestContext,
+ ContainerResponseContext responseContext) {
- responseContext.getHeaders().add(AAIHeaderProperties.AAI_TX_ID, requestContext.getProperty(AAIHeaderProperties.AAI_TX_ID));
+ responseContext.getHeaders().add(AAIHeaderProperties.AAI_TX_ID,
+ requestContext.getProperty(AAIHeaderProperties.AAI_TX_ID));
- String responseContentType = responseContext.getHeaderString("Content-Type");
+ String responseContentType = responseContext.getHeaderString("Content-Type");
- if(responseContentType == null){
- String acceptType = requestContext.getHeaderString("Accept");
+ if (responseContentType == null) {
+ String acceptType = requestContext.getHeaderString("Accept");
- if(acceptType == null || "*/*".equals(acceptType)){
- responseContext.getHeaders().putSingle("Content-Type", DEFAULT_XML_TYPE);
- } else {
- responseContext.getHeaders().putSingle("Content-Type", acceptType);
- }
- }
+ if (acceptType == null || "*/*".equals(acceptType)) {
+ responseContext.getHeaders().putSingle("Content-Type", DEFAULT_XML_TYPE);
+ } else {
+ responseContext.getHeaders().putSingle("Content-Type", acceptType);
+ }
+ }
- }
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/post/ResponseTransactionLogging.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/post/ResponseTransactionLogging.java
index 51fe871..854eeed 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/post/ResponseTransactionLogging.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/post/ResponseTransactionLogging.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -20,6 +20,17 @@
package org.onap.aai.interceptors.post;
import com.google.gson.JsonObject;
+
+import java.io.IOException;
+import java.util.*;
+
+import javax.annotation.Priority;
+import javax.servlet.http.HttpServletResponse;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerResponseContext;
+import javax.ws.rs.container.ContainerResponseFilter;
+import javax.ws.rs.core.PathSegment;
+
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.interceptors.AAIContainerFilter;
import org.onap.aai.interceptors.AAIHeaderProperties;
@@ -29,133 +40,127 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import javax.annotation.Priority;
-import javax.servlet.http.HttpServletResponse;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerResponseContext;
-import javax.ws.rs.container.ContainerResponseFilter;
-import javax.ws.rs.core.PathSegment;
-import java.io.IOException;
-import java.util.*;
-
@Priority(AAIResponseFilterPriority.RESPONSE_TRANS_LOGGING)
-public class ResponseTransactionLogging extends AAIContainerFilter implements ContainerResponseFilter {
-
- private static final Logger TRANSACTION_LOGGER = LoggerFactory.getLogger(ResponseTransactionLogging.class);
-
- private final static String QUERY_API_PATH_SEGMENT = "query";
- private final static String NODES_QUERY_API_PATH_SEGMENT = "nodes-query";
- private final static String GENERIC_QUERY_API_PATH_SEGMENT = "generic-query";
- private final static String DSL_API_PATH_SEGMENT = "dsl";
- private final static String RECENTS_API_PATH_SEGMENT = "recents";
- private final static Set<String> READ_ONLY_QUERIES = getReadOnlyQueries();
-
- @Autowired
- private HttpServletResponse httpServletResponse;
-
- @Override
- public void filter(ContainerRequestContext requestContext, ContainerResponseContext responseContext)
- throws IOException {
-
- this.transLogging(requestContext, responseContext);
-
- }
-
- private void transLogging(ContainerRequestContext requestContext, ContainerResponseContext responseContext) {
-
- String logValue;
- String isGetTransactionResponseLoggingEnabled;
- String postValue;
-
- try {
-
- logValue = AAIConfig.get("aai.transaction.logging");
- isGetTransactionResponseLoggingEnabled = AAIConfig.get("aai.transaction.logging.get");
- postValue = AAIConfig.get("aai.transaction.logging.post");
- } catch (AAIException e) {
- return;
- }
-
- String transId = requestContext.getHeaderString(AAIHeaderProperties.TRANSACTION_ID);
- String fromAppId = requestContext.getHeaderString(AAIHeaderProperties.FROM_APP_ID);
- String fullUri = requestContext.getUriInfo().getRequestUri().toString();
- String requestTs = (String)requestContext.getProperty(AAIHeaderProperties.AAI_REQUEST_TS);
-
- String httpMethod = requestContext.getMethod();
-
- String status = Integer.toString(responseContext.getStatus());
-
- String request = (String)requestContext.getProperty(AAIHeaderProperties.AAI_REQUEST);
- String response = this.getResponseString(responseContext);
-
- if (!Boolean.parseBoolean(logValue)) {
- } else if (!Boolean.parseBoolean(postValue) && "POST".equals(httpMethod)) {
- } else {
-
- JsonObject logEntry = new JsonObject();
- logEntry.addProperty("transactionId", transId);
- logEntry.addProperty("status", status);
- logEntry.addProperty("rqstDate", requestTs);
- logEntry.addProperty("respDate", this.genDate());
- logEntry.addProperty("sourceId", fromAppId + ":" + transId);
- logEntry.addProperty("resourceId", fullUri);
- logEntry.addProperty("resourceType", httpMethod);
- logEntry.addProperty("rqstBuf", Objects.toString(request, ""));
-
- boolean recordResponse = true;
- if (!Boolean.parseBoolean(isGetTransactionResponseLoggingEnabled) && "GET".equals(httpMethod)) {
- recordResponse = false;
- }
- else {
- /**
- * Parse the uri path and see if it is a read-only query
- * If it is, do not record the response in the logs
- */
-
- List<PathSegment> pathSegmentList = requestContext.getUriInfo().getPathSegments();
- for (PathSegment queryType : pathSegmentList) {
- if (READ_ONLY_QUERIES.contains(queryType.toString())) {
- recordResponse = false;
- }
- }
-
- if (recordResponse) {
- logEntry.addProperty("respBuf", Objects.toString(response, ""));
- }
-
- try {
- TRANSACTION_LOGGER.debug(logEntry.toString());
- } catch (Exception e) {
- ErrorLogHelper.logError("AAI_4000", "Exception writing transaction log.");
- }
- }
- }
-
- }
-
- private String getResponseString(ContainerResponseContext responseContext) {
- JsonObject response = new JsonObject();
- response.addProperty("ID", responseContext.getHeaderString(AAIHeaderProperties.AAI_TX_ID));
- response.addProperty("Content-Type", this.httpServletResponse.getContentType());
- response.addProperty("Response-Code", responseContext.getStatus());
- response.addProperty("Headers", responseContext.getHeaders().toString());
- Optional<Object> entityOptional = Optional.ofNullable(responseContext.getEntity());
- if(entityOptional.isPresent()){
- response.addProperty("Entity", entityOptional.get().toString());
- } else {
- response.addProperty("Entity", "");
- }
- return response.toString();
- }
-
- private static Set<String> getReadOnlyQueries() {
- Set<String> readOnlyQueries = new HashSet<String>();
- readOnlyQueries.add(NODES_QUERY_API_PATH_SEGMENT);
- readOnlyQueries.add(GENERIC_QUERY_API_PATH_SEGMENT);
- readOnlyQueries.add(RECENTS_API_PATH_SEGMENT);
- readOnlyQueries.add(QUERY_API_PATH_SEGMENT);
- readOnlyQueries.add(DSL_API_PATH_SEGMENT);
- return readOnlyQueries;
- }
+public class ResponseTransactionLogging extends AAIContainerFilter
+ implements ContainerResponseFilter {
+
+ private static final Logger TRANSACTION_LOGGER =
+ LoggerFactory.getLogger(ResponseTransactionLogging.class);
+
+ private final static String QUERY_API_PATH_SEGMENT = "query";
+ private final static String NODES_QUERY_API_PATH_SEGMENT = "nodes-query";
+ private final static String GENERIC_QUERY_API_PATH_SEGMENT = "generic-query";
+ private final static String DSL_API_PATH_SEGMENT = "dsl";
+ private final static String RECENTS_API_PATH_SEGMENT = "recents";
+ private final static Set<String> READ_ONLY_QUERIES = getReadOnlyQueries();
+
+ @Autowired
+ private HttpServletResponse httpServletResponse;
+
+ @Override
+ public void filter(ContainerRequestContext requestContext,
+ ContainerResponseContext responseContext) throws IOException {
+
+ this.transLogging(requestContext, responseContext);
+
+ }
+
+ private void transLogging(ContainerRequestContext requestContext,
+ ContainerResponseContext responseContext) {
+
+ String logValue;
+ String isGetTransactionResponseLoggingEnabled;
+ String postValue;
+
+ try {
+
+ logValue = AAIConfig.get("aai.transaction.logging");
+ isGetTransactionResponseLoggingEnabled = AAIConfig.get("aai.transaction.logging.get");
+ postValue = AAIConfig.get("aai.transaction.logging.post");
+ } catch (AAIException e) {
+ return;
+ }
+
+ String transId = requestContext.getHeaderString(AAIHeaderProperties.TRANSACTION_ID);
+ String fromAppId = requestContext.getHeaderString(AAIHeaderProperties.FROM_APP_ID);
+ String fullUri = requestContext.getUriInfo().getRequestUri().toString();
+ String requestTs = (String) requestContext.getProperty(AAIHeaderProperties.AAI_REQUEST_TS);
+
+ String httpMethod = requestContext.getMethod();
+
+ String status = Integer.toString(responseContext.getStatus());
+
+ String request = (String) requestContext.getProperty(AAIHeaderProperties.AAI_REQUEST);
+ String response = this.getResponseString(responseContext);
+
+ if (!Boolean.parseBoolean(logValue)) {
+ } else if (!Boolean.parseBoolean(postValue) && "POST".equals(httpMethod)) {
+ } else {
+
+ JsonObject logEntry = new JsonObject();
+ logEntry.addProperty("transactionId", transId);
+ logEntry.addProperty("status", status);
+ logEntry.addProperty("rqstDate", requestTs);
+ logEntry.addProperty("respDate", this.genDate());
+ logEntry.addProperty("sourceId", fromAppId + ":" + transId);
+ logEntry.addProperty("resourceId", fullUri);
+ logEntry.addProperty("resourceType", httpMethod);
+ logEntry.addProperty("rqstBuf", Objects.toString(request, ""));
+
+ boolean recordResponse = true;
+ if (!Boolean.parseBoolean(isGetTransactionResponseLoggingEnabled)
+ && "GET".equals(httpMethod)) {
+ recordResponse = false;
+ } else {
+ /**
+ * Parse the uri path and see if it is a read-only query
+ * If it is, do not record the response in the logs
+ */
+
+ List<PathSegment> pathSegmentList = requestContext.getUriInfo().getPathSegments();
+ for (PathSegment queryType : pathSegmentList) {
+ if (READ_ONLY_QUERIES.contains(queryType.toString())) {
+ recordResponse = false;
+ }
+ }
+
+ if (recordResponse) {
+ logEntry.addProperty("respBuf", Objects.toString(response, ""));
+ }
+
+ try {
+ TRANSACTION_LOGGER.debug(logEntry.toString());
+ } catch (Exception e) {
+ ErrorLogHelper.logError("AAI_4000", "Exception writing transaction log.");
+ }
+ }
+ }
+
+ }
+
+ private String getResponseString(ContainerResponseContext responseContext) {
+ JsonObject response = new JsonObject();
+ response.addProperty("ID", responseContext.getHeaderString(AAIHeaderProperties.AAI_TX_ID));
+ response.addProperty("Content-Type", this.httpServletResponse.getContentType());
+ response.addProperty("Response-Code", responseContext.getStatus());
+ response.addProperty("Headers", responseContext.getHeaders().toString());
+ Optional<Object> entityOptional = Optional.ofNullable(responseContext.getEntity());
+ if (entityOptional.isPresent()) {
+ response.addProperty("Entity", entityOptional.get().toString());
+ } else {
+ response.addProperty("Entity", "");
+ }
+ return response.toString();
+ }
+
+ private static Set<String> getReadOnlyQueries() {
+ Set<String> readOnlyQueries = new HashSet<String>();
+ readOnlyQueries.add(NODES_QUERY_API_PATH_SEGMENT);
+ readOnlyQueries.add(GENERIC_QUERY_API_PATH_SEGMENT);
+ readOnlyQueries.add(RECENTS_API_PATH_SEGMENT);
+ readOnlyQueries.add(QUERY_API_PATH_SEGMENT);
+ readOnlyQueries.add(DSL_API_PATH_SEGMENT);
+ return readOnlyQueries;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/AAIRequestFilterPriority.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/AAIRequestFilterPriority.java
index 4af96c5..ee6374c 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/AAIRequestFilterPriority.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/AAIRequestFilterPriority.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -20,25 +20,26 @@
package org.onap.aai.interceptors.pre;
public final class AAIRequestFilterPriority {
-
- private AAIRequestFilterPriority() {}
-
- public static final int REQUEST_TRANS_LOGGING = 1000;
-
- public static final int HEADER_VALIDATION = 2000;
- public static final int HTTP_HEADER = 4000;
+ private AAIRequestFilterPriority() {
+ }
- public static final int LATEST = 4250;
+ public static final int REQUEST_TRANS_LOGGING = 1000;
- public static final int AUTHORIZATION = 4500;
+ public static final int HEADER_VALIDATION = 2000;
- public static final int RETIRED_SERVICE = 5000;
+ public static final int HTTP_HEADER = 4000;
- public static final int VERSION = 5500;
+ public static final int LATEST = 4250;
- public static final int HEADER_MANIPULATION = 6000;
+ public static final int AUTHORIZATION = 4500;
- public static final int REQUEST_MODIFICATION = 7000;
+ public static final int RETIRED_SERVICE = 5000;
+
+ public static final int VERSION = 5500;
+
+ public static final int HEADER_MANIPULATION = 6000;
+
+ public static final int REQUEST_MODIFICATION = 7000;
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/HeaderValidation.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/HeaderValidation.java
index d70cb01..ed13863 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/HeaderValidation.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/HeaderValidation.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,12 +19,10 @@
*/
package org.onap.aai.interceptors.pre;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.interceptors.AAIContainerFilter;
-import org.onap.aai.interceptors.AAIHeaderProperties;
-import org.onap.aai.logging.ErrorLogHelper;
-import org.onap.logging.filter.base.Constants;
-import org.onap.logging.ref.slf4j.ONAPLogConstants;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
@@ -32,95 +30,102 @@ import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Optional;
+
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.interceptors.AAIContainerFilter;
+import org.onap.aai.interceptors.AAIHeaderProperties;
+import org.onap.aai.logging.ErrorLogHelper;
+import org.onap.logging.filter.base.Constants;
+import org.onap.logging.ref.slf4j.ONAPLogConstants;
@PreMatching
@Priority(AAIRequestFilterPriority.HEADER_VALIDATION)
public class HeaderValidation extends AAIContainerFilter implements ContainerRequestFilter {
- @Override
- public void filter(ContainerRequestContext requestContext) throws IOException {
+ @Override
+ public void filter(ContainerRequestContext requestContext) throws IOException {
+
+ Optional<Response> oResp;
+
+ List<MediaType> acceptHeaderValues = requestContext.getAcceptableMediaTypes();
- Optional<Response> oResp;
+ String fromAppId = getPartnerName(requestContext);
+ oResp = this.validateHeaderValuePresence(fromAppId, "AAI_4009", acceptHeaderValues);
+ if (oResp.isPresent()) {
+ requestContext.abortWith(oResp.get());
+ return;
+ }
+ String transId = getRequestId(requestContext);
+ oResp = this.validateHeaderValuePresence(transId, "AAI_4010", acceptHeaderValues);
+ if (oResp.isPresent()) {
+ requestContext.abortWith(oResp.get());
+ return;
+ }
+ }
- List<MediaType> acceptHeaderValues = requestContext.getAcceptableMediaTypes();
+ private Optional<Response> validateHeaderValuePresence(String value, String errorCode,
+ List<MediaType> acceptHeaderValues) {
+ Response response = null;
+ AAIException aaie;
+ if (value == null || value.isEmpty()) {
+ aaie = new AAIException(errorCode);
+ return Optional
+ .of(Response
+ .status(aaie.getErrorObject().getHTTPResponseCode()).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(acceptHeaderValues, aaie, new ArrayList<>()))
+ .build());
+ }
- String fromAppId = getPartnerName(requestContext);
- oResp = this.validateHeaderValuePresence(fromAppId, "AAI_4009", acceptHeaderValues);
- if (oResp.isPresent()) {
- requestContext.abortWith(oResp.get());
- return;
- }
- String transId = getRequestId(requestContext);
- oResp = this.validateHeaderValuePresence(transId, "AAI_4010", acceptHeaderValues);
- if (oResp.isPresent()) {
- requestContext.abortWith(oResp.get());
- return;
- }
- }
-
- private Optional<Response> validateHeaderValuePresence(String value, String errorCode,
- List<MediaType> acceptHeaderValues) {
- Response response = null;
- AAIException aaie;
- if (value == null || value.isEmpty()) {
- aaie = new AAIException(errorCode);
- return Optional.of(Response.status(aaie.getErrorObject().getHTTPResponseCode())
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(acceptHeaderValues, aaie, new ArrayList<>()))
- .build());
- }
+ return Optional.ofNullable(response);
+ }
- return Optional.ofNullable(response);
- }
- public String getRequestId(ContainerRequestContext requestContext) {
- String requestId = requestContext.getHeaderString(ONAPLogConstants.Headers.REQUEST_ID);
- if (requestId == null || requestId.isEmpty()) {
- requestId = requestContext.getHeaderString(Constants.HttpHeaders.HEADER_REQUEST_ID);
- if (requestId == null || requestId.isEmpty()) {
- requestId = requestContext.getHeaderString(Constants.HttpHeaders.TRANSACTION_ID);
- if (requestId == null || requestId.isEmpty()) {
- requestId = requestContext.getHeaderString(Constants.HttpHeaders.ECOMP_REQUEST_ID);
- if (requestId == null || requestId.isEmpty()) {
- return requestId;
- }
- }
- }
- }
- if (requestContext.getHeaders().get(ONAPLogConstants.Headers.REQUEST_ID) != null) {
- requestContext.getHeaders().get(ONAPLogConstants.Headers.REQUEST_ID).clear();
- }
- if (requestContext.getHeaders().get(Constants.HttpHeaders.TRANSACTION_ID) != null) {
- requestContext.getHeaders().get(Constants.HttpHeaders.TRANSACTION_ID).clear();
- }
- if (requestContext.getHeaders().get(Constants.HttpHeaders.HEADER_REQUEST_ID) != null) {
- requestContext.getHeaders().get(Constants.HttpHeaders.HEADER_REQUEST_ID).clear();
- }
- if (requestContext.getHeaders().get(Constants.HttpHeaders.ECOMP_REQUEST_ID) != null) {
- requestContext.getHeaders().get(Constants.HttpHeaders.ECOMP_REQUEST_ID).clear();
- }
- requestContext.getHeaders().add(Constants.HttpHeaders.TRANSACTION_ID, requestId);
+ public String getRequestId(ContainerRequestContext requestContext) {
+ String requestId = requestContext.getHeaderString(ONAPLogConstants.Headers.REQUEST_ID);
+ if (requestId == null || requestId.isEmpty()) {
+ requestId = requestContext.getHeaderString(Constants.HttpHeaders.HEADER_REQUEST_ID);
+ if (requestId == null || requestId.isEmpty()) {
+ requestId = requestContext.getHeaderString(Constants.HttpHeaders.TRANSACTION_ID);
+ if (requestId == null || requestId.isEmpty()) {
+ requestId =
+ requestContext.getHeaderString(Constants.HttpHeaders.ECOMP_REQUEST_ID);
+ if (requestId == null || requestId.isEmpty()) {
+ return requestId;
+ }
+ }
+ }
+ }
+ if (requestContext.getHeaders().get(ONAPLogConstants.Headers.REQUEST_ID) != null) {
+ requestContext.getHeaders().get(ONAPLogConstants.Headers.REQUEST_ID).clear();
+ }
+ if (requestContext.getHeaders().get(Constants.HttpHeaders.TRANSACTION_ID) != null) {
+ requestContext.getHeaders().get(Constants.HttpHeaders.TRANSACTION_ID).clear();
+ }
+ if (requestContext.getHeaders().get(Constants.HttpHeaders.HEADER_REQUEST_ID) != null) {
+ requestContext.getHeaders().get(Constants.HttpHeaders.HEADER_REQUEST_ID).clear();
+ }
+ if (requestContext.getHeaders().get(Constants.HttpHeaders.ECOMP_REQUEST_ID) != null) {
+ requestContext.getHeaders().get(Constants.HttpHeaders.ECOMP_REQUEST_ID).clear();
+ }
+ requestContext.getHeaders().add(Constants.HttpHeaders.TRANSACTION_ID, requestId);
- return requestId;
- }
+ return requestId;
+ }
- public String getPartnerName(ContainerRequestContext requestContext) {
- String partnerName = requestContext.getHeaderString(ONAPLogConstants.Headers.PARTNER_NAME);
- if (partnerName == null || (partnerName.isEmpty())) {
- partnerName = requestContext.getHeaderString(AAIHeaderProperties.FROM_APP_ID);
- if (partnerName == null || (partnerName.isEmpty())) {
- return partnerName;
- }
- }
- if (requestContext.getHeaders().get(ONAPLogConstants.Headers.PARTNER_NAME) != null) {
- requestContext.getHeaders().get(ONAPLogConstants.Headers.PARTNER_NAME).clear();
- }
- if (requestContext.getHeaders().get(AAIHeaderProperties.FROM_APP_ID) != null) {
- requestContext.getHeaders().get(AAIHeaderProperties.FROM_APP_ID).clear();
- }
- requestContext.getHeaders().add(AAIHeaderProperties.FROM_APP_ID, partnerName);
- return partnerName;
- }
+ public String getPartnerName(ContainerRequestContext requestContext) {
+ String partnerName = requestContext.getHeaderString(ONAPLogConstants.Headers.PARTNER_NAME);
+ if (partnerName == null || (partnerName.isEmpty())) {
+ partnerName = requestContext.getHeaderString(AAIHeaderProperties.FROM_APP_ID);
+ if (partnerName == null || (partnerName.isEmpty())) {
+ return partnerName;
+ }
+ }
+ if (requestContext.getHeaders().get(ONAPLogConstants.Headers.PARTNER_NAME) != null) {
+ requestContext.getHeaders().get(ONAPLogConstants.Headers.PARTNER_NAME).clear();
+ }
+ if (requestContext.getHeaders().get(AAIHeaderProperties.FROM_APP_ID) != null) {
+ requestContext.getHeaders().get(AAIHeaderProperties.FROM_APP_ID).clear();
+ }
+ requestContext.getHeaders().add(AAIHeaderProperties.FROM_APP_ID, partnerName);
+ return partnerName;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/HttpHeaderInterceptor.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/HttpHeaderInterceptor.java
index ee04453..5d9c1ff 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/HttpHeaderInterceptor.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/HttpHeaderInterceptor.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,15 +19,16 @@
*/
package org.onap.aai.interceptors.pre;
-import org.onap.aai.interceptors.AAIContainerFilter;
-import org.onap.aai.interceptors.AAIHeaderProperties;
+import java.io.IOException;
import javax.annotation.Priority;
import javax.ws.rs.HttpMethod;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
-import java.io.IOException;
+
+import org.onap.aai.interceptors.AAIContainerFilter;
+import org.onap.aai.interceptors.AAIHeaderProperties;
/**
* The Class HttpHeaderInterceptor
@@ -35,16 +36,18 @@ import java.io.IOException;
@PreMatching
@Priority(AAIRequestFilterPriority.HTTP_HEADER)
public class HttpHeaderInterceptor extends AAIContainerFilter implements ContainerRequestFilter {
- public static final String patchMethod = "PATCH";
-
+ public static final String patchMethod = "PATCH";
+
@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
- String overrideMethod = containerRequestContext.getHeaderString(AAIHeaderProperties.HTTP_METHOD_OVERRIDE);
- String httpMethod = containerRequestContext.getMethod();
-
- if (HttpMethod.POST.equalsIgnoreCase(httpMethod) && patchMethod.equalsIgnoreCase(overrideMethod)) {
- containerRequestContext.setMethod(patchMethod);
- }
+ String overrideMethod =
+ containerRequestContext.getHeaderString(AAIHeaderProperties.HTTP_METHOD_OVERRIDE);
+ String httpMethod = containerRequestContext.getMethod();
+
+ if (HttpMethod.POST.equalsIgnoreCase(httpMethod)
+ && patchMethod.equalsIgnoreCase(overrideMethod)) {
+ containerRequestContext.setMethod(patchMethod);
+ }
}
-
+
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/OneWaySslAuthorization.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/OneWaySslAuthorization.java
index a6c5ed9..78ab1a9 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/OneWaySslAuthorization.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/OneWaySslAuthorization.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,13 +19,10 @@
*/
package org.onap.aai.interceptors.pre;
-import org.onap.aai.Profiles;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.interceptors.AAIContainerFilter;
-import org.onap.aai.logging.ErrorLogHelper;
-import org.onap.aai.service.AuthorizationService;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.context.annotation.Profile;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
@@ -33,10 +30,14 @@ import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Optional;
+
+import org.onap.aai.Profiles;
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.interceptors.AAIContainerFilter;
+import org.onap.aai.logging.ErrorLogHelper;
+import org.onap.aai.service.AuthorizationService;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.context.annotation.Profile;
@Profile(Profiles.ONE_WAY_SSL)
@PreMatching
@@ -47,17 +48,17 @@ public class OneWaySslAuthorization extends AAIContainerFilter implements Contai
private AuthorizationService authorizationService;
@Override
- public void filter(ContainerRequestContext containerRequestContext) throws IOException
- {
+ public void filter(ContainerRequestContext containerRequestContext) throws IOException {
- if(containerRequestContext.getUriInfo().getRequestUri().getPath().matches("^.*/util/echo$")){
+ if (containerRequestContext.getUriInfo().getRequestUri().getPath()
+ .matches("^.*/util/echo$")) {
return;
}
String basicAuth = containerRequestContext.getHeaderString("Authorization");
List<MediaType> acceptHeaderValues = containerRequestContext.getAcceptableMediaTypes();
- if(basicAuth == null || !basicAuth.startsWith("Basic ")){
+ if (basicAuth == null || !basicAuth.startsWith("Basic ")) {
Optional<Response> responseOptional = errorResponse("AAI_3300", acceptHeaderValues);
containerRequestContext.abortWith(responseOptional.get());
return;
@@ -65,7 +66,7 @@ public class OneWaySslAuthorization extends AAIContainerFilter implements Contai
basicAuth = basicAuth.replaceAll("Basic ", "");
- if(!authorizationService.checkIfUserAuthorized(basicAuth)){
+ if (!authorizationService.checkIfUserAuthorized(basicAuth)) {
Optional<Response> responseOptional = errorResponse("AAI_3300", acceptHeaderValues);
containerRequestContext.abortWith(responseOptional.get());
return;
@@ -76,8 +77,9 @@ public class OneWaySslAuthorization extends AAIContainerFilter implements Contai
private Optional<Response> errorResponse(String errorCode, List<MediaType> acceptHeaderValues) {
AAIException aaie = new AAIException(errorCode);
return Optional.of(Response.status(aaie.getErrorObject().getHTTPResponseCode())
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(acceptHeaderValues, aaie, new ArrayList<>()))
- .build());
+ .entity(
+ ErrorLogHelper.getRESTAPIErrorResponse(acceptHeaderValues, aaie, new ArrayList<>()))
+ .build());
}
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RequestHeaderManipulation.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RequestHeaderManipulation.java
index d2dcc0b..4946e7d 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RequestHeaderManipulation.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RequestHeaderManipulation.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,42 +19,44 @@
*/
package org.onap.aai.interceptors.pre;
-import org.onap.aai.interceptors.AAIContainerFilter;
-import org.onap.aai.interceptors.AAIHeaderProperties;
+import java.util.Collections;
+import java.util.regex.Matcher;
import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.MultivaluedMap;
-import java.util.Collections;
-import java.util.regex.Matcher;
+
+import org.onap.aai.interceptors.AAIContainerFilter;
+import org.onap.aai.interceptors.AAIHeaderProperties;
@PreMatching
@Priority(AAIRequestFilterPriority.HEADER_MANIPULATION)
-public class RequestHeaderManipulation extends AAIContainerFilter implements ContainerRequestFilter {
+public class RequestHeaderManipulation extends AAIContainerFilter
+ implements ContainerRequestFilter {
- @Override
- public void filter(ContainerRequestContext requestContext) {
+ @Override
+ public void filter(ContainerRequestContext requestContext) {
- String uri = requestContext.getUriInfo().getPath();
- this.addRequestContext(uri, requestContext.getHeaders());
+ String uri = requestContext.getUriInfo().getPath();
+ this.addRequestContext(uri, requestContext.getHeaders());
- }
-
- private void addRequestContext(String uri, MultivaluedMap<String, String> requestHeaders) {
+ }
- String rc = "";
+ private void addRequestContext(String uri, MultivaluedMap<String, String> requestHeaders) {
+
+ String rc = "";
Matcher match = VersionInterceptor.EXTRACT_VERSION_PATTERN.matcher(uri);
if (match.find()) {
rc = match.group(1);
}
- if (requestHeaders.containsKey(AAIHeaderProperties.REQUEST_CONTEXT)) {
- requestHeaders.remove(AAIHeaderProperties.REQUEST_CONTEXT);
- }
- requestHeaders.put(AAIHeaderProperties.REQUEST_CONTEXT, Collections.singletonList(rc));
- }
+ if (requestHeaders.containsKey(AAIHeaderProperties.REQUEST_CONTEXT)) {
+ requestHeaders.remove(AAIHeaderProperties.REQUEST_CONTEXT);
+ }
+ requestHeaders.put(AAIHeaderProperties.REQUEST_CONTEXT, Collections.singletonList(rc));
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RequestModification.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RequestModification.java
index acd1305..f7d863d 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RequestModification.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RequestModification.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,7 +19,12 @@
*/
package org.onap.aai.interceptors.pre;
-import org.onap.aai.interceptors.AAIContainerFilter;
+import java.io.IOException;
+import java.util.Arrays;
+import java.util.List;
+import java.util.Map;
+import java.util.Set;
+import java.util.stream.Collectors;
import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
@@ -27,49 +32,45 @@ import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.MultivaluedMap;
import javax.ws.rs.core.UriBuilder;
-import java.io.IOException;
-import java.util.Arrays;
-import java.util.List;
-import java.util.Map;
-import java.util.Set;
-import java.util.stream.Collectors;
+
+import org.onap.aai.interceptors.AAIContainerFilter;
@PreMatching
@Priority(AAIRequestFilterPriority.REQUEST_MODIFICATION)
public class RequestModification extends AAIContainerFilter implements ContainerRequestFilter {
- @Override
- public void filter(ContainerRequestContext requestContext) throws IOException {
+ @Override
+ public void filter(ContainerRequestContext requestContext) throws IOException {
+
+ this.cleanDME2QueryParams(requestContext);
- this.cleanDME2QueryParams(requestContext);
+ }
- }
-
- private void cleanDME2QueryParams(ContainerRequestContext request) {
- UriBuilder builder = request.getUriInfo().getRequestUriBuilder();
- MultivaluedMap<String, String> queries = request.getUriInfo().getQueryParameters();
+ private void cleanDME2QueryParams(ContainerRequestContext request) {
+ UriBuilder builder = request.getUriInfo().getRequestUriBuilder();
+ MultivaluedMap<String, String> queries = request.getUriInfo().getQueryParameters();
- String[] blacklist = { "version", "envContext", "routeOffer" };
- Set<String> blacklistSet = Arrays.stream(blacklist).collect(Collectors.toSet());
+ String[] blacklist = {"version", "envContext", "routeOffer"};
+ Set<String> blacklistSet = Arrays.stream(blacklist).collect(Collectors.toSet());
- boolean remove = true;
+ boolean remove = true;
- for (String param : blacklistSet) {
- if (!queries.containsKey(param)) {
- remove = false;
- break;
- }
- }
+ for (String param : blacklistSet) {
+ if (!queries.containsKey(param)) {
+ remove = false;
+ break;
+ }
+ }
- if (remove) {
- for (Map.Entry<String, List<String>> query : queries.entrySet()) {
- String key = query.getKey();
- if (blacklistSet.contains(key)) {
- builder.replaceQueryParam(key);
- }
- }
- }
- request.setRequestUri(builder.build());
- }
+ if (remove) {
+ for (Map.Entry<String, List<String>> query : queries.entrySet()) {
+ String key = query.getKey();
+ if (blacklistSet.contains(key)) {
+ builder.replaceQueryParam(key);
+ }
+ }
+ }
+ request.setRequestUri(builder.build());
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RequestTransactionLogging.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RequestTransactionLogging.java
index 03cac8d..b37a804 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RequestTransactionLogging.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RequestTransactionLogging.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -20,6 +20,24 @@
package org.onap.aai.interceptors.pre;
import com.google.gson.JsonObject;
+
+import java.io.ByteArrayInputStream;
+import java.io.ByteArrayOutputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.SecureRandom;
+import java.util.Random;
+import java.util.UUID;
+
+import javax.annotation.Priority;
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.container.PreMatching;
+import javax.ws.rs.core.MediaType;
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.UriInfo;
+
import org.glassfish.jersey.message.internal.ReaderWriter;
import org.glassfish.jersey.server.ContainerException;
import org.onap.aai.exceptions.AAIException;
@@ -31,113 +49,104 @@ import org.onap.aai.util.HbaseSaltPrefixer;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
-import javax.annotation.Priority;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerRequestFilter;
-import javax.ws.rs.container.PreMatching;
-import javax.ws.rs.core.MediaType;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.UriInfo;
-import java.io.ByteArrayInputStream;
-import java.io.ByteArrayOutputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.SecureRandom;
-import java.util.Random;
-import java.util.UUID;
-
@PreMatching
@Priority(AAIRequestFilterPriority.REQUEST_TRANS_LOGGING)
-public class RequestTransactionLogging extends AAIContainerFilter implements ContainerRequestFilter {
-
- @Autowired
- private HttpServletRequest httpServletRequest;
-
- private static final String DEFAULT_CONTENT_TYPE = MediaType.APPLICATION_JSON;
- private static final String DEFAULT_RESPONSE_TYPE = MediaType.APPLICATION_XML;
-
- private static final String CONTENT_TYPE = "Content-Type";
- private static final String ACCEPT = "Accept";
- private static final String TEXT_PLAIN = "text/plain";
- private static final String WILDCARD = "*/*";
- private static final String APPLICATION_JSON = "application/json";
-
- @Override
- public void filter(ContainerRequestContext requestContext) throws IOException {
-
- String currentTimeStamp = genDate();
- String fullId = this.getAAITxIdToHeader(currentTimeStamp);
- this.addToRequestContext(requestContext, AAIHeaderProperties.AAI_TX_ID, fullId);
- this.addToRequestContext(requestContext, AAIHeaderProperties.AAI_REQUEST, this.getRequest(requestContext, fullId));
- this.addToRequestContext(requestContext, AAIHeaderProperties.AAI_REQUEST_TS, currentTimeStamp);
- this.addDefaultContentType(requestContext);
- }
-
- private void addToRequestContext(ContainerRequestContext requestContext, String name, String aaiTxIdToHeader) {
- requestContext.setProperty(name, aaiTxIdToHeader);
- }
-
- private void addDefaultContentType(ContainerRequestContext requestContext) {
-
- String contentType = requestContext.getHeaderString(CONTENT_TYPE);
- String acceptType = requestContext.getHeaderString(ACCEPT);
-
- if(contentType == null || contentType.contains(TEXT_PLAIN)){
- requestContext.getHeaders().putSingle(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
- }
-
- if(WILDCARD.equals(acceptType) || StringUtils.isEmpty(acceptType) || acceptType.contains(TEXT_PLAIN)){
- UriInfo uriInfo = requestContext.getUriInfo();
- if(uriInfo != null){
- String path = uriInfo.getPath();
- if(path.endsWith("/dsl") || path.endsWith("/query") || path.contains("/recents/")){
- requestContext.getHeaders().putSingle(ACCEPT, APPLICATION_JSON);
- } else {
- requestContext.getHeaders().putSingle(ACCEPT, DEFAULT_RESPONSE_TYPE);
- }
- } else {
- requestContext.getHeaders().putSingle(ACCEPT, DEFAULT_RESPONSE_TYPE);
- }
- }
- }
-
- private String getAAITxIdToHeader(String currentTimeStamp) {
- String txId = UUID.randomUUID().toString();
- try {
- Random rand = new SecureRandom();
- int number = rand.nextInt(99999);
- txId = HbaseSaltPrefixer.getInstance().prependSalt(AAIConfig.get(AAIConstants.AAI_NODENAME) + "-"
- + currentTimeStamp + "-" + number ); //new Random(System.currentTimeMillis()).nextInt(99999)
- } catch (AAIException e) {
- }
-
- return txId;
- }
-
- private String getRequest(ContainerRequestContext requestContext, String fullId) {
-
- JsonObject request = new JsonObject();
- request.addProperty("ID", fullId);
- request.addProperty("Http-Method", requestContext.getMethod());
- request.addProperty(CONTENT_TYPE, httpServletRequest.getContentType());
- request.addProperty("Headers", requestContext.getHeaders().toString());
-
- ByteArrayOutputStream out = new ByteArrayOutputStream();
- InputStream in = requestContext.getEntityStream();
-
- try {
- if (in.available() > 0) {
- ReaderWriter.writeTo(in, out);
- byte[] requestEntity = out.toByteArray();
- request.addProperty("Payload", new String(requestEntity, "UTF-8"));
- requestContext.setEntityStream(new ByteArrayInputStream(requestEntity));
- }
- } catch (IOException ex) {
- throw new ContainerException(ex);
- }
-
- return request.toString();
- }
+public class RequestTransactionLogging extends AAIContainerFilter
+ implements ContainerRequestFilter {
+
+ @Autowired
+ private HttpServletRequest httpServletRequest;
+
+ private static final String DEFAULT_CONTENT_TYPE = MediaType.APPLICATION_JSON;
+ private static final String DEFAULT_RESPONSE_TYPE = MediaType.APPLICATION_XML;
+
+ private static final String CONTENT_TYPE = "Content-Type";
+ private static final String ACCEPT = "Accept";
+ private static final String TEXT_PLAIN = "text/plain";
+ private static final String WILDCARD = "*/*";
+ private static final String APPLICATION_JSON = "application/json";
+
+ @Override
+ public void filter(ContainerRequestContext requestContext) throws IOException {
+
+ String currentTimeStamp = genDate();
+ String fullId = this.getAAITxIdToHeader(currentTimeStamp);
+ this.addToRequestContext(requestContext, AAIHeaderProperties.AAI_TX_ID, fullId);
+ this.addToRequestContext(requestContext, AAIHeaderProperties.AAI_REQUEST,
+ this.getRequest(requestContext, fullId));
+ this.addToRequestContext(requestContext, AAIHeaderProperties.AAI_REQUEST_TS,
+ currentTimeStamp);
+ this.addDefaultContentType(requestContext);
+ }
+
+ private void addToRequestContext(ContainerRequestContext requestContext, String name,
+ String aaiTxIdToHeader) {
+ requestContext.setProperty(name, aaiTxIdToHeader);
+ }
+
+ private void addDefaultContentType(ContainerRequestContext requestContext) {
+
+ String contentType = requestContext.getHeaderString(CONTENT_TYPE);
+ String acceptType = requestContext.getHeaderString(ACCEPT);
+
+ if (contentType == null || contentType.contains(TEXT_PLAIN)) {
+ requestContext.getHeaders().putSingle(CONTENT_TYPE, DEFAULT_CONTENT_TYPE);
+ }
+
+ if (WILDCARD.equals(acceptType) || StringUtils.isEmpty(acceptType)
+ || acceptType.contains(TEXT_PLAIN)) {
+ UriInfo uriInfo = requestContext.getUriInfo();
+ if (uriInfo != null) {
+ String path = uriInfo.getPath();
+ if (path.endsWith("/dsl") || path.endsWith("/query")
+ || path.contains("/recents/")) {
+ requestContext.getHeaders().putSingle(ACCEPT, APPLICATION_JSON);
+ } else {
+ requestContext.getHeaders().putSingle(ACCEPT, DEFAULT_RESPONSE_TYPE);
+ }
+ } else {
+ requestContext.getHeaders().putSingle(ACCEPT, DEFAULT_RESPONSE_TYPE);
+ }
+ }
+ }
+
+ private String getAAITxIdToHeader(String currentTimeStamp) {
+ String txId = UUID.randomUUID().toString();
+ try {
+ Random rand = new SecureRandom();
+ int number = rand.nextInt(99999);
+ txId = HbaseSaltPrefixer.getInstance().prependSalt(
+ AAIConfig.get(AAIConstants.AAI_NODENAME) + "-" + currentTimeStamp + "-" + number); // new
+ // Random(System.currentTimeMillis()).nextInt(99999)
+ } catch (AAIException e) {
+ }
+
+ return txId;
+ }
+
+ private String getRequest(ContainerRequestContext requestContext, String fullId) {
+
+ JsonObject request = new JsonObject();
+ request.addProperty("ID", fullId);
+ request.addProperty("Http-Method", requestContext.getMethod());
+ request.addProperty(CONTENT_TYPE, httpServletRequest.getContentType());
+ request.addProperty("Headers", requestContext.getHeaders().toString());
+
+ ByteArrayOutputStream out = new ByteArrayOutputStream();
+ InputStream in = requestContext.getEntityStream();
+
+ try {
+ if (in.available() > 0) {
+ ReaderWriter.writeTo(in, out);
+ byte[] requestEntity = out.toByteArray();
+ request.addProperty("Payload", new String(requestEntity, "UTF-8"));
+ requestContext.setEntityStream(new ByteArrayInputStream(requestEntity));
+ }
+ } catch (IOException ex) {
+ throw new ContainerException(ex);
+ }
+
+ return request.toString();
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RetiredInterceptor.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RetiredInterceptor.java
index 643793d..d1aa2e9 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RetiredInterceptor.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/RetiredInterceptor.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,18 @@
*/
package org.onap.aai.interceptors.pre;
+import java.io.IOException;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.annotation.Priority;
+import javax.ws.rs.container.ContainerRequestContext;
+import javax.ws.rs.container.ContainerRequestFilter;
+import javax.ws.rs.container.PreMatching;
+import javax.ws.rs.core.Response;
+
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.interceptors.AAIContainerFilter;
import org.onap.aai.logging.ErrorLogHelper;
@@ -27,17 +39,6 @@ import org.onap.aai.util.AAIConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
-import javax.annotation.Priority;
-import javax.ws.rs.container.ContainerRequestContext;
-import javax.ws.rs.container.ContainerRequestFilter;
-import javax.ws.rs.container.PreMatching;
-import javax.ws.rs.core.Response;
-import java.io.IOException;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-
// Can cache this so if the uri was already cached then it won't run the string
// matching each time but only does it for the first time
@@ -52,13 +53,15 @@ public class RetiredInterceptor extends AAIContainerFilter implements ContainerR
private String basePath;
@Autowired
- public RetiredInterceptor(RetiredService retiredService, @Value("${schema.uri.base.path}") String basePath){
+ public RetiredInterceptor(RetiredService retiredService,
+ @Value("${schema.uri.base.path}") String basePath) {
this.retiredService = retiredService;
this.basePath = basePath;
- if(!basePath.endsWith("/")){
+ if (!basePath.endsWith("/")) {
this.basePath = basePath + "/";
}
}
+
@Override
public void filter(ContainerRequestContext containerRequestContext) throws IOException {
@@ -68,8 +71,8 @@ public class RetiredInterceptor extends AAIContainerFilter implements ContainerR
List<Pattern> retiredAllVersionList = retiredService.getRetiredAllVersionList();
-
- if(checkIfUriRetired(containerRequestContext, retiredAllVersionList, version, requestURI, "")){
+ if (checkIfUriRetired(containerRequestContext, retiredAllVersionList, version, requestURI,
+ "")) {
return;
}
@@ -79,17 +82,13 @@ public class RetiredInterceptor extends AAIContainerFilter implements ContainerR
}
public boolean checkIfUriRetired(ContainerRequestContext containerRequestContext,
- List<Pattern> retiredPatterns,
- String version,
- String requestURI,
- String message){
-
+ List<Pattern> retiredPatterns, String version, String requestURI, String message) {
- for(Pattern retiredPattern : retiredPatterns){
- if(retiredPattern.matcher(requestURI).matches()){
+ for (Pattern retiredPattern : retiredPatterns) {
+ if (retiredPattern.matcher(requestURI).matches()) {
AAIException e;
- if(message == null){
+ if (message == null) {
e = new AAIException("AAI_3007");
} else {
e = new AAIException("AAI_3015");
@@ -99,25 +98,20 @@ public class RetiredInterceptor extends AAIContainerFilter implements ContainerR
if (templateVars.isEmpty()) {
templateVars.add("PUT");
- if(requestURI != null){
+ if (requestURI != null) {
requestURI = requestURI.replaceAll(basePath, "");
}
templateVars.add(requestURI);
- if(message == null){
+ if (message == null) {
templateVars.add(version);
templateVars.add(AAIConfig.get("aai.default.api.version", ""));
}
}
- Response response = Response
- .status(e.getErrorObject().getHTTPResponseCode())
- .entity(
- ErrorLogHelper
- .getRESTAPIErrorResponse(
- containerRequestContext.getAcceptableMediaTypes(), e, templateVars
- )
- )
- .build();
+ Response response = Response.status(e.getErrorObject().getHTTPResponseCode())
+ .entity(ErrorLogHelper.getRESTAPIErrorResponse(
+ containerRequestContext.getAcceptableMediaTypes(), e, templateVars))
+ .build();
containerRequestContext.abortWith(response);
@@ -129,17 +123,16 @@ public class RetiredInterceptor extends AAIContainerFilter implements ContainerR
}
public boolean checkIfUriRetired(ContainerRequestContext containerRequestContext,
- List<Pattern> retiredPatterns,
- String version,
- String requestURI){
- return checkIfUriRetired(containerRequestContext, retiredPatterns, version, requestURI, null);
+ List<Pattern> retiredPatterns, String version, String requestURI) {
+ return checkIfUriRetired(containerRequestContext, retiredPatterns, version, requestURI,
+ null);
}
protected String extractVersionFromPath(String requestURI) {
Matcher versionMatcher = VERSION_PATTERN.matcher(requestURI);
String version = null;
- if(versionMatcher.find()){
+ if (versionMatcher.find()) {
version = versionMatcher.group(0);
}
return version;
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/VersionInterceptor.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/VersionInterceptor.java
index 902d6f0..944d999 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/VersionInterceptor.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/VersionInterceptor.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,23 +19,24 @@
*/
package org.onap.aai.interceptors.pre;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.interceptors.AAIContainerFilter;
-import org.onap.aai.logging.ErrorLogHelper;
-import org.onap.aai.setup.SchemaVersion;
-import org.onap.aai.setup.SchemaVersions;
-import org.springframework.beans.factory.annotation.Autowired;
+import java.util.ArrayList;
+import java.util.Set;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
import javax.ws.rs.core.Response;
-import java.util.ArrayList;
-import java.util.Set;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
+
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.interceptors.AAIContainerFilter;
+import org.onap.aai.logging.ErrorLogHelper;
+import org.onap.aai.setup.SchemaVersion;
+import org.onap.aai.setup.SchemaVersions;
+import org.springframework.beans.factory.annotation.Autowired;
@PreMatching
@Priority(AAIRequestFilterPriority.VERSION)
@@ -48,11 +49,9 @@ public class VersionInterceptor extends AAIContainerFilter implements ContainerR
private final SchemaVersions schemaVersions;
@Autowired
- public VersionInterceptor(SchemaVersions schemaVersions){
+ public VersionInterceptor(SchemaVersions schemaVersions) {
this.schemaVersions = schemaVersions;
- allowedVersions = schemaVersions.getVersions()
- .stream()
- .map(SchemaVersion::toString)
+ allowedVersions = schemaVersions.getVersions().stream().map(SchemaVersion::toString)
.collect(Collectors.toSet());
}
@@ -62,26 +61,31 @@ public class VersionInterceptor extends AAIContainerFilter implements ContainerR
String uri = requestContext.getUriInfo().getPath();
- if (uri.startsWith("search") || uri.startsWith("util/echo") || uri.startsWith("tools") || uri.startsWith("recents")|| uri.startsWith("cq2gremlin")|| uri.startsWith("cq2gremlintest")) {
+ if (uri.startsWith("search") || uri.startsWith("util/echo") || uri.startsWith("tools")
+ || uri.startsWith("recents") || uri.startsWith("cq2gremlin")
+ || uri.startsWith("cq2gremlintest")) {
return;
- }
+ }
Matcher matcher = EXTRACT_VERSION_PATTERN.matcher(uri);
String version = null;
- if(matcher.matches()){
+ if (matcher.matches()) {
version = matcher.group(1);
} else {
- requestContext.abortWith(createInvalidVersionResponse("AAI_3017", requestContext, version));
+ requestContext
+ .abortWith(createInvalidVersionResponse("AAI_3017", requestContext, version));
return;
}
- if(!allowedVersions.contains(version)){
- requestContext.abortWith(createInvalidVersionResponse("AAI_3016", requestContext, version));
+ if (!allowedVersions.contains(version)) {
+ requestContext
+ .abortWith(createInvalidVersionResponse("AAI_3016", requestContext, version));
}
}
- private Response createInvalidVersionResponse(String errorCode, ContainerRequestContext context, String version) {
+ private Response createInvalidVersionResponse(String errorCode, ContainerRequestContext context,
+ String version) {
AAIException e = new AAIException(errorCode);
ArrayList<String> templateVars = new ArrayList<>();
@@ -91,11 +95,9 @@ public class VersionInterceptor extends AAIContainerFilter implements ContainerR
templateVars.add(version);
}
- String entity = ErrorLogHelper.getRESTAPIErrorResponse(context.getAcceptableMediaTypes(), e, templateVars);
+ String entity = ErrorLogHelper.getRESTAPIErrorResponse(context.getAcceptableMediaTypes(), e,
+ templateVars);
- return Response
- .status(e.getErrorObject().getHTTPResponseCode())
- .entity(entity)
- .build();
+ return Response.status(e.getErrorObject().getHTTPResponseCode()).entity(entity).build();
}
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/VersionLatestInterceptor.java b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/VersionLatestInterceptor.java
index 124bc1a..22f923d 100644
--- a/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/VersionLatestInterceptor.java
+++ b/aai-traversal/src/main/java/org/onap/aai/interceptors/pre/VersionLatestInterceptor.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,15 +19,16 @@
*/
package org.onap.aai.interceptors.pre;
-import org.onap.aai.interceptors.AAIContainerFilter;
-import org.onap.aai.setup.SchemaVersions;
-import org.springframework.beans.factory.annotation.Autowired;
+import java.net.URI;
import javax.annotation.Priority;
import javax.ws.rs.container.ContainerRequestContext;
import javax.ws.rs.container.ContainerRequestFilter;
import javax.ws.rs.container.PreMatching;
-import java.net.URI;
+
+import org.onap.aai.interceptors.AAIContainerFilter;
+import org.onap.aai.setup.SchemaVersions;
+import org.springframework.beans.factory.annotation.Autowired;
@PreMatching
@Priority(AAIRequestFilterPriority.LATEST)
@@ -36,7 +37,7 @@ public class VersionLatestInterceptor extends AAIContainerFilter implements Cont
private final SchemaVersions schemaVersions;
@Autowired
- public VersionLatestInterceptor(SchemaVersions schemaVersions){
+ public VersionLatestInterceptor(SchemaVersions schemaVersions) {
this.schemaVersions = schemaVersions;
}
@@ -45,10 +46,12 @@ public class VersionLatestInterceptor extends AAIContainerFilter implements Cont
String uri = requestContext.getUriInfo().getPath();
- if(uri.startsWith("latest")){
- String rawPath = requestContext.getUriInfo().getRequestUri().getRawPath();
- String updatedPath = rawPath.replaceFirst("latest",schemaVersions.getDefaultVersion().toString());
- URI latest = requestContext.getUriInfo().getRequestUriBuilder().replacePath(updatedPath).build();
+ if (uri.startsWith("latest")) {
+ String rawPath = requestContext.getUriInfo().getRequestUri().getRawPath();
+ String updatedPath =
+ rawPath.replaceFirst("latest", schemaVersions.getDefaultVersion().toString());
+ URI latest =
+ requestContext.getUriInfo().getRequestUriBuilder().replacePath(updatedPath).build();
requestContext.setRequestUri(latest);
return;
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/CQ2Gremlin.java b/aai-traversal/src/main/java/org/onap/aai/rest/CQ2Gremlin.java
index d075f70..6e76c29 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/CQ2Gremlin.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/CQ2Gremlin.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,16 @@
*/
package org.onap.aai.rest;
+import java.util.LinkedHashMap;
+import java.util.List;
+import java.util.Map;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.*;
+
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.introspection.LoaderFactory;
import org.onap.aai.rest.db.HttpEntry;
@@ -34,83 +44,72 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestBody;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.*;
-import java.util.LinkedHashMap;
-import java.util.List;
-import java.util.Map;
-
-
@Path("/cq2gremlin")
public class CQ2Gremlin extends RESTAPI {
- private HttpEntry traversalUriHttpEntry;
-
-
- @Autowired
- protected LoaderFactory loaderFactory;
-
- @Autowired
- protected EdgeSerializer rules;
-
-
- @Autowired
- public CQ2Gremlin(
- HttpEntry traversalUriHttpEntry,
- @Value("${schema.uri.base.path}") String basePath
- ){
- this.traversalUriHttpEntry = traversalUriHttpEntry;
- }
-
- @PUT
- @Path("")
- @Consumes({ MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_JSON })
- public Response getC2Qgremlin(@RequestBody Map<String, CustomQueryConfigDTO> content,@Context HttpHeaders headers, @Context UriInfo info) {
- if(content.size() == 0){
- return Response.status(HttpStatus.BAD_REQUEST.value()).entity("At least one custom query should be passed").build();
- }
- return processGremlinQuery(content.values().toArray(new CustomQueryConfigDTO[0])[0], info, headers);
- }
-
- protected Response processGremlinQuery(CustomQueryConfigDTO content, UriInfo info,
- HttpHeaders headers) {
- try{
- LinkedHashMap <String, Object> params;
- CustomQueryDTO queryDTO = content.getQueryDTO();
- String query = queryDTO.getQuery();
- params = new LinkedHashMap <>();
-
- List<String> optionalParameters = queryDTO.getQueryOptionalProperties();
- if (!optionalParameters.isEmpty()){
- for ( String key : optionalParameters ) {
- params.put(key, key);
- }
- }
-
- List<String> requiredParameters = queryDTO.getQueryRequiredProperties();
- if (!requiredParameters.isEmpty()){
- for ( String key : requiredParameters ) {
- params.put(key, key);
- }
- }
-
- SchemaVersions schemaVersions = SpringContextAware.getBean(SchemaVersions.class);
- traversalUriHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion());
- traversalUriHttpEntry.setPaginationParameters("-1", "-1");
-
- TransactionalGraphEngine dbEngine = traversalUriHttpEntry.getDbEngine();
-
- query = new GroovyQueryBuilder().executeTraversal(dbEngine,query, params);
- query = "g" + query;
- return Response.ok(query).build();
- }
- catch(Exception ex){
- return Response.status(500).entity("Query conversion failed with following reason: " + ex.toString()).build();
- }
-
- }
+ private HttpEntry traversalUriHttpEntry;
+
+ @Autowired
+ protected LoaderFactory loaderFactory;
+
+ @Autowired
+ protected EdgeSerializer rules;
+
+ @Autowired
+ public CQ2Gremlin(HttpEntry traversalUriHttpEntry,
+ @Value("${schema.uri.base.path}") String basePath) {
+ this.traversalUriHttpEntry = traversalUriHttpEntry;
+ }
+
+ @PUT
+ @Path("")
+ @Consumes({MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_JSON})
+ public Response getC2Qgremlin(@RequestBody Map<String, CustomQueryConfigDTO> content,
+ @Context HttpHeaders headers, @Context UriInfo info) {
+ if (content.size() == 0) {
+ return Response.status(HttpStatus.BAD_REQUEST.value())
+ .entity("At least one custom query should be passed").build();
+ }
+ return processGremlinQuery(content.values().toArray(new CustomQueryConfigDTO[0])[0], info,
+ headers);
+ }
+
+ protected Response processGremlinQuery(CustomQueryConfigDTO content, UriInfo info,
+ HttpHeaders headers) {
+ try {
+ LinkedHashMap<String, Object> params;
+ CustomQueryDTO queryDTO = content.getQueryDTO();
+ String query = queryDTO.getQuery();
+ params = new LinkedHashMap<>();
+
+ List<String> optionalParameters = queryDTO.getQueryOptionalProperties();
+ if (!optionalParameters.isEmpty()) {
+ for (String key : optionalParameters) {
+ params.put(key, key);
+ }
+ }
+
+ List<String> requiredParameters = queryDTO.getQueryRequiredProperties();
+ if (!requiredParameters.isEmpty()) {
+ for (String key : requiredParameters) {
+ params.put(key, key);
+ }
+ }
+
+ SchemaVersions schemaVersions = SpringContextAware.getBean(SchemaVersions.class);
+ traversalUriHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion());
+ traversalUriHttpEntry.setPaginationParameters("-1", "-1");
+
+ TransactionalGraphEngine dbEngine = traversalUriHttpEntry.getDbEngine();
+
+ query = new GroovyQueryBuilder().executeTraversal(dbEngine, query, params);
+ query = "g" + query;
+ return Response.ok(query).build();
+ } catch (Exception ex) {
+ return Response.status(500)
+ .entity("Query conversion failed with following reason: " + ex.toString()).build();
+ }
+
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/CQ2GremlinTest.java b/aai-traversal/src/main/java/org/onap/aai/rest/CQ2GremlinTest.java
index e3cfaca..626c5f3 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/CQ2GremlinTest.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/CQ2GremlinTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,9 +19,19 @@
*/
package org.onap.aai.rest;
-
import com.beust.jcommander.internal.Lists;
import com.beust.jcommander.internal.Maps;
+
+import java.util.*;
+import java.util.concurrent.atomic.AtomicInteger;
+import java.util.stream.Collectors;
+
+import javax.ws.rs.Consumes;
+import javax.ws.rs.PUT;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.core.*;
+
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.Graph;
@@ -49,171 +59,156 @@ import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestBody;
-import javax.ws.rs.Consumes;
-import javax.ws.rs.PUT;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.core.*;
-import java.util.*;
-import java.util.concurrent.atomic.AtomicInteger;
-import java.util.stream.Collectors;
-
-
@Path("/cq2gremlintest")
public class CQ2GremlinTest extends RESTAPI {
- private static final Logger LOGGER = LoggerFactory.getLogger(CQ2GremlinTest.class);
-
- private HttpEntry traversalUriHttpEntry;
-
-
- @Autowired
- protected LoaderFactory loaderFactory;
-
- @Autowired
- protected EdgeSerializer rules;
-
- protected Loader loader;
- protected GraphTraversalSource gts;
-
-
- @Autowired
- public CQ2GremlinTest(
- HttpEntry traversalUriHttpEntry,
- @Value("${schema.uri.base.path}") String basePath
- ){
- this.traversalUriHttpEntry = traversalUriHttpEntry;
-
- }
-
- @PUT
- @Path("")
- @Consumes({ MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_JSON })
- public Response getC2Qgremlin(@RequestBody CustomQueryTestDTO content,@Context HttpHeaders headers, @Context UriInfo info) throws AAIException {
- if(content == null){
- return Response.status(HttpStatus.BAD_REQUEST.value()).entity("At least one Json payload should be passed").build();
- }
- String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
- String realTime = headers.getRequestHeaders().getFirst("Real-Time");
- SchemaVersions schemaVersions = SpringContextAware.getBean(SchemaVersions.class);
- traversalUriHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion());
- traversalUriHttpEntry.setPaginationParameters("-1", "-1");
- return processC2UnitTest(content);
- }
-
- private Response processC2UnitTest(CustomQueryTestDTO content) {
-
- TransactionalGraphEngine dbEngine = traversalUriHttpEntry.getDbEngine();
- Graph graph = TinkerGraph.open();
- gts = graph.traversal();
- List<Vertex> expectedVertices = createGraph(content, graph);
- GremlinGroovyShell shell = new GremlinGroovyShell();
- loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, new SchemaVersion("v19"));
- LinkedHashMap <String, Object> params = new LinkedHashMap<>();
-
- //Adding parameters
- content.getQueryRequiredProperties().forEach(params::put);
- content.getQueryOptionalProperties().forEach(params::put);
-
- String query = new GroovyQueryBuilder().executeTraversal(dbEngine, content.getStoredQuery(), params);
- query = "g" + query;
- GraphTraversal<Vertex, Vertex> g = graph.traversal().V();
- addStartNode(g, content);
- params.put("g", g);
-
- //Assertion
- GraphTraversal<Vertex, Vertex> result = (GraphTraversal<Vertex, Vertex>)shell.executeTraversal(query, params);
-
- List<Vertex> vertices = result.toList();
-
- LOGGER.info("Expected result set of vertexes [{}]", convert(expectedVertices));
- LOGGER.info("Actual Result set of vertexes [{}]", convert(vertices));
-
- List<Vertex> nonDuplicateExpectedResult = new ArrayList<>(new HashSet<>(expectedVertices));
- vertices = new ArrayList<>(new HashSet<>(vertices));
-
- nonDuplicateExpectedResult.sort(Comparator.comparing(vertex -> vertex.id().toString()));
- vertices.sort(Comparator.comparing(vertex -> vertex.id().toString()));
-
-
- // Use this instead of the assertTrue as this provides more useful
- // debugging information such as this when expected and actual differ:
- // java.lang.AssertionError: Expected all the vertices to be found
- // Expected :[v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
- // Actual :[v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
- if(nonDuplicateExpectedResult.equals(vertices)){
- return Response.ok("Sucessfully executed Junit").build();
- }
- return Response.status(400).build();
-
- }
-
- private List<Vertex> createGraph(CustomQueryTestDTO content, Graph graph) {
- Map<String, Vertex> verticesMap = Maps.newLinkedHashMap();
- //Creating all the Vertices
- content.getVerticesDtos().forEach(vertex -> {
- StringBuilder vertexIdentifier = new StringBuilder();
- List<String> keyValues = Lists.newArrayList();
- keyValues.add(T.id.toString());
- keyValues.add(String.format("%02d", verticesMap.size() * 10));
- AtomicInteger index = new AtomicInteger(0);
- vertex.forEach((k, v) -> {
- if(index.get() == 1)
- vertexIdentifier.append(k);
- keyValues.add(k);
- keyValues.add(v);
- index.incrementAndGet();
- });
- Vertex graphVertex = graph.addVertex(keyValues.toArray());
- verticesMap.put(vertexIdentifier.toString(), graphVertex);
- });
-
- GraphTraversalSource g = graph.traversal();
-
- //Creating all the Edges
- content.getEdgesDtos().forEach(edge -> {
- String fromId = edge.get("from-id");
- String toId = edge.get("to-id");
- boolean treeEdgeIdentifier = !"NONE".equalsIgnoreCase(edge.get("contains-other-v"));
- Vertex fromVertex = verticesMap.get(fromId);
- Vertex toVertex = verticesMap.get(toId);
- try{
- if(treeEdgeIdentifier){
- rules.addTreeEdge(g, fromVertex, toVertex);
- }
- else{
- rules.addEdge(g, fromVertex, toVertex);
- }
- } catch(AAIException ex){
- LOGGER.warn(ex.toString(), ex);
- }
-
- });
-
-
- List<Vertex> expectedVertices = Lists.newArrayList();
- content.getExpectedResultsDtos().getIds().forEach(vertexId -> expectedVertices.add(verticesMap.get(vertexId)));
- return expectedVertices;
- }
-
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g, CustomQueryTestDTO content) {
- Optional<LinkedHashMap<String, String>> startNodeVertex = content.getVerticesDtos().stream().filter(map -> map.containsKey("start-node")).findFirst();
- if(!startNodeVertex.isPresent()){
- throw new IllegalArgumentException("start-node was not specified");
- }
- startNodeVertex.get().forEach((k, v) -> {
- g.has(k, v);
- });
- }
-
- protected String convert(List<Vertex> vertices){
- return vertices
- .stream()
- .map(vertex -> vertex.property("aai-node-type").value().toString())
- .collect(Collectors.joining(","));
- }
-
-
+ private static final Logger LOGGER = LoggerFactory.getLogger(CQ2GremlinTest.class);
+
+ private HttpEntry traversalUriHttpEntry;
+
+ @Autowired
+ protected LoaderFactory loaderFactory;
+
+ @Autowired
+ protected EdgeSerializer rules;
+
+ protected Loader loader;
+ protected GraphTraversalSource gts;
+
+ @Autowired
+ public CQ2GremlinTest(HttpEntry traversalUriHttpEntry,
+ @Value("${schema.uri.base.path}") String basePath) {
+ this.traversalUriHttpEntry = traversalUriHttpEntry;
+
+ }
+
+ @PUT
+ @Path("")
+ @Consumes({MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_JSON})
+ public Response getC2Qgremlin(@RequestBody CustomQueryTestDTO content,
+ @Context HttpHeaders headers, @Context UriInfo info) throws AAIException {
+ if (content == null) {
+ return Response.status(HttpStatus.BAD_REQUEST.value())
+ .entity("At least one Json payload should be passed").build();
+ }
+ String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
+ String realTime = headers.getRequestHeaders().getFirst("Real-Time");
+ SchemaVersions schemaVersions = SpringContextAware.getBean(SchemaVersions.class);
+ traversalUriHttpEntry.setHttpEntryProperties(schemaVersions.getDefaultVersion());
+ traversalUriHttpEntry.setPaginationParameters("-1", "-1");
+ return processC2UnitTest(content);
+ }
+
+ private Response processC2UnitTest(CustomQueryTestDTO content) {
+
+ TransactionalGraphEngine dbEngine = traversalUriHttpEntry.getDbEngine();
+ Graph graph = TinkerGraph.open();
+ gts = graph.traversal();
+ List<Vertex> expectedVertices = createGraph(content, graph);
+ GremlinGroovyShell shell = new GremlinGroovyShell();
+ loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, new SchemaVersion("v19"));
+ LinkedHashMap<String, Object> params = new LinkedHashMap<>();
+
+ // Adding parameters
+ content.getQueryRequiredProperties().forEach(params::put);
+ content.getQueryOptionalProperties().forEach(params::put);
+
+ String query =
+ new GroovyQueryBuilder().executeTraversal(dbEngine, content.getStoredQuery(), params);
+ query = "g" + query;
+ GraphTraversal<Vertex, Vertex> g = graph.traversal().V();
+ addStartNode(g, content);
+ params.put("g", g);
+
+ // Assertion
+ GraphTraversal<Vertex, Vertex> result =
+ (GraphTraversal<Vertex, Vertex>) shell.executeTraversal(query, params);
+
+ List<Vertex> vertices = result.toList();
+
+ LOGGER.info("Expected result set of vertexes [{}]", convert(expectedVertices));
+ LOGGER.info("Actual Result set of vertexes [{}]", convert(vertices));
+
+ List<Vertex> nonDuplicateExpectedResult = new ArrayList<>(new HashSet<>(expectedVertices));
+ vertices = new ArrayList<>(new HashSet<>(vertices));
+
+ nonDuplicateExpectedResult.sort(Comparator.comparing(vertex -> vertex.id().toString()));
+ vertices.sort(Comparator.comparing(vertex -> vertex.id().toString()));
+
+ // Use this instead of the assertTrue as this provides more useful
+ // debugging information such as this when expected and actual differ:
+ // java.lang.AssertionError: Expected all the vertices to be found
+ // Expected :[v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
+ // Actual :[v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
+ if (nonDuplicateExpectedResult.equals(vertices)) {
+ return Response.ok("Sucessfully executed Junit").build();
+ }
+ return Response.status(400).build();
+
+ }
+
+ private List<Vertex> createGraph(CustomQueryTestDTO content, Graph graph) {
+ Map<String, Vertex> verticesMap = Maps.newLinkedHashMap();
+ // Creating all the Vertices
+ content.getVerticesDtos().forEach(vertex -> {
+ StringBuilder vertexIdentifier = new StringBuilder();
+ List<String> keyValues = Lists.newArrayList();
+ keyValues.add(T.id.toString());
+ keyValues.add(String.format("%02d", verticesMap.size() * 10));
+ AtomicInteger index = new AtomicInteger(0);
+ vertex.forEach((k, v) -> {
+ if (index.get() == 1)
+ vertexIdentifier.append(k);
+ keyValues.add(k);
+ keyValues.add(v);
+ index.incrementAndGet();
+ });
+ Vertex graphVertex = graph.addVertex(keyValues.toArray());
+ verticesMap.put(vertexIdentifier.toString(), graphVertex);
+ });
+
+ GraphTraversalSource g = graph.traversal();
+
+ // Creating all the Edges
+ content.getEdgesDtos().forEach(edge -> {
+ String fromId = edge.get("from-id");
+ String toId = edge.get("to-id");
+ boolean treeEdgeIdentifier = !"NONE".equalsIgnoreCase(edge.get("contains-other-v"));
+ Vertex fromVertex = verticesMap.get(fromId);
+ Vertex toVertex = verticesMap.get(toId);
+ try {
+ if (treeEdgeIdentifier) {
+ rules.addTreeEdge(g, fromVertex, toVertex);
+ } else {
+ rules.addEdge(g, fromVertex, toVertex);
+ }
+ } catch (AAIException ex) {
+ LOGGER.warn(ex.toString(), ex);
+ }
+
+ });
+
+ List<Vertex> expectedVertices = Lists.newArrayList();
+ content.getExpectedResultsDtos().getIds()
+ .forEach(vertexId -> expectedVertices.add(verticesMap.get(vertexId)));
+ return expectedVertices;
+ }
+
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g, CustomQueryTestDTO content) {
+ Optional<LinkedHashMap<String, String>> startNodeVertex = content.getVerticesDtos().stream()
+ .filter(map -> map.containsKey("start-node")).findFirst();
+ if (!startNodeVertex.isPresent()) {
+ throw new IllegalArgumentException("start-node was not specified");
+ }
+ startNodeVertex.get().forEach((k, v) -> {
+ g.has(k, v);
+ });
+ }
+
+ protected String convert(List<Vertex> vertices) {
+ return vertices.stream().map(vertex -> vertex.property("aai-node-type").value().toString())
+ .collect(Collectors.joining(","));
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/DslConsumer.java b/aai-traversal/src/main/java/org/onap/aai/rest/DslConsumer.java
index fefd2dc..2b6bbb9 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/DslConsumer.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/DslConsumer.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -22,7 +22,17 @@ package org.onap.aai.rest;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+
import io.micrometer.core.annotation.Timed;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.*;
+import javax.ws.rs.core.Response.Status;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.janusgraph.core.SchemaViolationException;
import org.onap.aai.concurrent.AaiCallable;
@@ -51,222 +61,211 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.*;
-import javax.ws.rs.core.Response.Status;
-import java.util.*;
-import java.util.stream.Collectors;
-
@Path("{version: v[1-9][0-9]*|latest}/dsl")
@Timed
public class DslConsumer extends TraversalConsumer {
- private HttpEntry traversalUriHttpEntry;
-
- private QueryProcessorType processorType = QueryProcessorType.LOCAL_GROOVY;
-
- private static final Logger LOGGER = LoggerFactory.getLogger(DslConsumer.class);
-
- private DslQueryProcessor dslQueryProcessor;
-
- private SchemaVersions schemaVersions;
-
- private String basePath;
-
- private GremlinServerSingleton gremlinServerSingleton;
- private final QueryVersion DEFAULT_VERSION = QueryVersion.V1;
- private QueryVersion dslApiVersion = DEFAULT_VERSION;
-
- private XmlFormatTransformer xmlFormatTransformer;
-
- @Autowired
- public DslConsumer(HttpEntry traversalUriHttpEntry, DslQueryProcessor dslQueryProcessor,
- SchemaVersions schemaVersions, GremlinServerSingleton gremlinServerSingleton,
- XmlFormatTransformer xmlFormatTransformer,
- @Value("${schema.uri.base.path}") String basePath) {
- this.traversalUriHttpEntry = traversalUriHttpEntry;
- this.dslQueryProcessor = dslQueryProcessor;
- this.schemaVersions = schemaVersions;
- this.gremlinServerSingleton = gremlinServerSingleton;
- this.xmlFormatTransformer = xmlFormatTransformer;
- this.basePath = basePath;
- }
-
- @PUT
- @Consumes({ MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
- public Response executeQuery(String content,
- @PathParam("version") String versionParam,
- @DefaultValue("graphson") @QueryParam("format") String queryFormat,
- @DefaultValue("no_op") @QueryParam("subgraph") String subgraph,
- @DefaultValue("all") @QueryParam("validate") String validate,
- @Context HttpHeaders headers,
- @Context HttpServletRequest req,
- @Context UriInfo info,
- @DefaultValue("-1") @QueryParam("resultIndex") String resultIndex,
- @DefaultValue("-1") @QueryParam("resultSize") String resultSize) {
- Set<String> roles = this.getRoles(req.getUserPrincipal());
-
- return runner(TraversalConstants.AAI_TRAVERSAL_DSL_TIMEOUT_ENABLED,
- TraversalConstants.AAI_TRAVERSAL_DSL_TIMEOUT_APP,
- TraversalConstants.AAI_TRAVERSAL_DSL_TIMEOUT_LIMIT,
- headers,
- info,
- HttpMethod.PUT,
- new AaiCallable() {
- @Override
- public Response process() throws Exception {
- return (processExecuteQuery(content, req, versionParam, queryFormat, subgraph, validate, headers, info,
- resultIndex, resultSize, roles));
- }
- }
- );
- }
-
- public Response processExecuteQuery(String content, HttpServletRequest req, String versionParam, String queryFormat, String subgraph,
- String validate, HttpHeaders headers, UriInfo info, String resultIndex,
- String resultSize, Set<String> roles) {
-
- String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
- String dslOverride = headers.getRequestHeaders().getFirst("X-DslOverride");
-
- Optional<String> dslApiVersionHeader = Optional.ofNullable(headers.getRequestHeaders().getFirst("X-DslApiVersion"));
- if (dslApiVersionHeader.isPresent()) {
- try {
- dslApiVersion = QueryVersion.valueOf(dslApiVersionHeader.get());
- } catch (IllegalArgumentException e) {
- LOGGER.debug("Defaulting DSL Api Version to "+DEFAULT_VERSION);
- }
- }
-
- Response response;
- SchemaVersion version = new SchemaVersion(versionParam);
-
- TransactionalGraphEngine dbEngine = null;
- try {
- String serverBase = req.getRequestURL().toString().replaceAll("/(v[0-9]+|latest)/.*", "/");
- traversalUriHttpEntry.setHttpEntryProperties(version, serverBase);
- traversalUriHttpEntry.setPaginationParameters(resultIndex, resultSize);
- dbEngine = traversalUriHttpEntry.getDbEngine();
- JsonObject input = new JsonParser().parse(content).getAsJsonObject();
- JsonElement dslElement = input.get("dsl");
- String dsl = "";
- if (dslElement != null) {
- dsl = dslElement.getAsString();
- }
-
-
- boolean isDslOverride = dslOverride != null && !AAIConfig.get(TraversalConstants.DSL_OVERRIDE).equals("false")
- && dslOverride.equals(AAIConfig.get(TraversalConstants.DSL_OVERRIDE));
-
- if(isDslOverride) {
- dslQueryProcessor.setStartNodeValidationFlag(false);
- }
-
- dslQueryProcessor.setValidationRules(validate);
-
- Format format = Format.getFormat(queryFormat);
-
- if(isAggregate(format)){
- dslQueryProcessor.setAggregate(true);
- }
-
- if(isHistory(format)){
- validateHistoryParams(format, info.getQueryParameters());
- }
-
- GraphTraversalSource traversalSource = getTraversalSource(dbEngine, format, info, roles);
-
- GenericQueryProcessor processor = new GenericQueryProcessor.Builder(dbEngine, gremlinServerSingleton)
- .queryFrom(dsl, "dsl").queryProcessor(dslQueryProcessor).version(dslApiVersion).processWith(processorType)
- .format(format).uriParams(info.getQueryParameters()).traversalSource(isHistory(format), traversalSource).create();
-
- SubGraphStyle subGraphStyle = SubGraphStyle.valueOf(subgraph);
- List<Object> vertTemp = processor.execute(subGraphStyle);
-
-
- // Dedup if duplicate objects are returned in each array in the aggregate format scenario.
- List<Object> vertTempDedupedObjectList = dedupObjectInAggregateFormatResult(vertTemp);
-
- List <Object> vertices;
- if (isAggregate(format)){
- vertices = traversalUriHttpEntry.getPaginatedVertexListForAggregateFormat(vertTempDedupedObjectList);
- } else {
- vertices = traversalUriHttpEntry.getPaginatedVertexList(vertTemp);
- }
-
- DBSerializer serializer = new DBSerializer(version, dbEngine, ModelType.MOXY, sourceOfTruth);
- FormatFactory ff = new FormatFactory(traversalUriHttpEntry.getLoader(), serializer, schemaVersions,
- this.basePath, serverBase);
-
- MultivaluedMap<String, String> mvm = new MultivaluedHashMap<>();
- mvm.putAll(info.getQueryParameters());
- if (isHistory(format)) {
- mvm.putSingle("startTs", Long.toString(getStartTime(format, mvm)));
- mvm.putSingle("endTs", Long.toString(getEndTime(mvm)));
- }
- Formatter formatter = ff.get(format, mvm);
-
- final Map<String, List<String>> propertiesMap = processor.getPropertiesMap();
- String result = "";
- if (propertiesMap != null && !propertiesMap.isEmpty()){
- result = formatter.output(vertices, propertiesMap).toString();
- }
- else {
- result = formatter.output(vertices).toString();
- }
-
- String acceptType = headers.getHeaderString("Accept");
-
- if(acceptType == null){
- acceptType = MediaType.APPLICATION_JSON;
- }
-
- if(MediaType.APPLICATION_XML_TYPE.isCompatible(MediaType.valueOf(acceptType))){
- result = xmlFormatTransformer.transform(result);
- }
-
- if(traversalUriHttpEntry.isPaginated()){
- response = Response.status(Status.OK)
- .type(acceptType)
- .header("total-results", traversalUriHttpEntry.getTotalVertices())
- .header("total-pages", traversalUriHttpEntry.getTotalPaginationBuckets())
- .entity(result)
- .build();
- }else {
- response = Response.status(Status.OK)
- .type(acceptType)
- .entity(result).build();
- }
-
- } catch (AAIException e) {
- response = consumerExceptionResponseGenerator(headers, info, HttpMethod.PUT, e);
- } catch (SchemaViolationException sve) {
- AAIException ex = new AAIException("AAI_4020", sve);
- response = consumerExceptionResponseGenerator(headers, info, HttpMethod.PUT, ex);
- } catch (Exception e) {
- AAIException ex = new AAIException("AAI_4000", e);
- response = consumerExceptionResponseGenerator(headers, info, HttpMethod.PUT, ex);
- } finally {
- if (dbEngine != null) {
- dbEngine.rollback();
- }
-
- }
-
- return response;
- }
-
- private List<Object> dedupObjectInAggregateFormatResult(List<Object> vertTemp) {
- List<Object> vertTempDedupedObjectList = new ArrayList<Object>();
- Iterator<Object> itr = vertTemp.listIterator();
- while (itr.hasNext()){
- Object o = itr.next();
- if (o instanceof ArrayList) {
- vertTempDedupedObjectList.add(((ArrayList) o).stream().distinct().collect(Collectors.toList()));
- }
- }
- return vertTempDedupedObjectList;
- }
+ private HttpEntry traversalUriHttpEntry;
+
+ private QueryProcessorType processorType = QueryProcessorType.LOCAL_GROOVY;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(DslConsumer.class);
+
+ private DslQueryProcessor dslQueryProcessor;
+
+ private SchemaVersions schemaVersions;
+
+ private String basePath;
+
+ private GremlinServerSingleton gremlinServerSingleton;
+ private final QueryVersion DEFAULT_VERSION = QueryVersion.V1;
+ private QueryVersion dslApiVersion = DEFAULT_VERSION;
+
+ private XmlFormatTransformer xmlFormatTransformer;
+
+ @Autowired
+ public DslConsumer(HttpEntry traversalUriHttpEntry, DslQueryProcessor dslQueryProcessor,
+ SchemaVersions schemaVersions, GremlinServerSingleton gremlinServerSingleton,
+ XmlFormatTransformer xmlFormatTransformer,
+ @Value("${schema.uri.base.path}") String basePath) {
+ this.traversalUriHttpEntry = traversalUriHttpEntry;
+ this.dslQueryProcessor = dslQueryProcessor;
+ this.schemaVersions = schemaVersions;
+ this.gremlinServerSingleton = gremlinServerSingleton;
+ this.xmlFormatTransformer = xmlFormatTransformer;
+ this.basePath = basePath;
+ }
+
+ @PUT
+ @Consumes({MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
+ public Response executeQuery(String content, @PathParam("version") String versionParam,
+ @DefaultValue("graphson") @QueryParam("format") String queryFormat,
+ @DefaultValue("no_op") @QueryParam("subgraph") String subgraph,
+ @DefaultValue("all") @QueryParam("validate") String validate, @Context HttpHeaders headers,
+ @Context HttpServletRequest req, @Context UriInfo info,
+ @DefaultValue("-1") @QueryParam("resultIndex") String resultIndex,
+ @DefaultValue("-1") @QueryParam("resultSize") String resultSize) {
+ Set<String> roles = this.getRoles(req.getUserPrincipal());
+
+ return runner(TraversalConstants.AAI_TRAVERSAL_DSL_TIMEOUT_ENABLED,
+ TraversalConstants.AAI_TRAVERSAL_DSL_TIMEOUT_APP,
+ TraversalConstants.AAI_TRAVERSAL_DSL_TIMEOUT_LIMIT, headers, info, HttpMethod.PUT,
+ new AaiCallable() {
+ @Override
+ public Response process() throws Exception {
+ return (processExecuteQuery(content, req, versionParam, queryFormat, subgraph,
+ validate, headers, info, resultIndex, resultSize, roles));
+ }
+ });
+ }
+
+ public Response processExecuteQuery(String content, HttpServletRequest req, String versionParam,
+ String queryFormat, String subgraph, String validate, HttpHeaders headers, UriInfo info,
+ String resultIndex, String resultSize, Set<String> roles) {
+
+ String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
+ String dslOverride = headers.getRequestHeaders().getFirst("X-DslOverride");
+
+ Optional<String> dslApiVersionHeader =
+ Optional.ofNullable(headers.getRequestHeaders().getFirst("X-DslApiVersion"));
+ if (dslApiVersionHeader.isPresent()) {
+ try {
+ dslApiVersion = QueryVersion.valueOf(dslApiVersionHeader.get());
+ } catch (IllegalArgumentException e) {
+ LOGGER.debug("Defaulting DSL Api Version to " + DEFAULT_VERSION);
+ }
+ }
+
+ Response response;
+ SchemaVersion version = new SchemaVersion(versionParam);
+
+ TransactionalGraphEngine dbEngine = null;
+ try {
+ String serverBase =
+ req.getRequestURL().toString().replaceAll("/(v[0-9]+|latest)/.*", "/");
+ traversalUriHttpEntry.setHttpEntryProperties(version, serverBase);
+ traversalUriHttpEntry.setPaginationParameters(resultIndex, resultSize);
+ dbEngine = traversalUriHttpEntry.getDbEngine();
+ JsonObject input = new JsonParser().parse(content).getAsJsonObject();
+ JsonElement dslElement = input.get("dsl");
+ String dsl = "";
+ if (dslElement != null) {
+ dsl = dslElement.getAsString();
+ }
+
+ boolean isDslOverride = dslOverride != null
+ && !AAIConfig.get(TraversalConstants.DSL_OVERRIDE).equals("false")
+ && dslOverride.equals(AAIConfig.get(TraversalConstants.DSL_OVERRIDE));
+
+ if (isDslOverride) {
+ dslQueryProcessor.setStartNodeValidationFlag(false);
+ }
+
+ dslQueryProcessor.setValidationRules(validate);
+
+ Format format = Format.getFormat(queryFormat);
+
+ if (isAggregate(format)) {
+ dslQueryProcessor.setAggregate(true);
+ }
+
+ if (isHistory(format)) {
+ validateHistoryParams(format, info.getQueryParameters());
+ }
+
+ GraphTraversalSource traversalSource =
+ getTraversalSource(dbEngine, format, info, roles);
+
+ GenericQueryProcessor processor =
+ new GenericQueryProcessor.Builder(dbEngine, gremlinServerSingleton)
+ .queryFrom(dsl, "dsl").queryProcessor(dslQueryProcessor).version(dslApiVersion)
+ .processWith(processorType).format(format).uriParams(info.getQueryParameters())
+ .traversalSource(isHistory(format), traversalSource).create();
+
+ SubGraphStyle subGraphStyle = SubGraphStyle.valueOf(subgraph);
+ List<Object> vertTemp = processor.execute(subGraphStyle);
+
+ // Dedup if duplicate objects are returned in each array in the aggregate format
+ // scenario.
+ List<Object> vertTempDedupedObjectList = dedupObjectInAggregateFormatResult(vertTemp);
+
+ List<Object> vertices;
+ if (isAggregate(format)) {
+ vertices = traversalUriHttpEntry
+ .getPaginatedVertexListForAggregateFormat(vertTempDedupedObjectList);
+ } else {
+ vertices = traversalUriHttpEntry.getPaginatedVertexList(vertTemp);
+ }
+
+ DBSerializer serializer =
+ new DBSerializer(version, dbEngine, ModelType.MOXY, sourceOfTruth);
+ FormatFactory ff = new FormatFactory(traversalUriHttpEntry.getLoader(), serializer,
+ schemaVersions, this.basePath, serverBase);
+
+ MultivaluedMap<String, String> mvm = new MultivaluedHashMap<>();
+ mvm.putAll(info.getQueryParameters());
+ if (isHistory(format)) {
+ mvm.putSingle("startTs", Long.toString(getStartTime(format, mvm)));
+ mvm.putSingle("endTs", Long.toString(getEndTime(mvm)));
+ }
+ Formatter formatter = ff.get(format, mvm);
+
+ final Map<String, List<String>> propertiesMap = processor.getPropertiesMap();
+ String result = "";
+ if (propertiesMap != null && !propertiesMap.isEmpty()) {
+ result = formatter.output(vertices, propertiesMap).toString();
+ } else {
+ result = formatter.output(vertices).toString();
+ }
+
+ String acceptType = headers.getHeaderString("Accept");
+
+ if (acceptType == null) {
+ acceptType = MediaType.APPLICATION_JSON;
+ }
+
+ if (MediaType.APPLICATION_XML_TYPE.isCompatible(MediaType.valueOf(acceptType))) {
+ result = xmlFormatTransformer.transform(result);
+ }
+
+ if (traversalUriHttpEntry.isPaginated()) {
+ response = Response.status(Status.OK).type(acceptType)
+ .header("total-results", traversalUriHttpEntry.getTotalVertices())
+ .header("total-pages", traversalUriHttpEntry.getTotalPaginationBuckets())
+ .entity(result).build();
+ } else {
+ response = Response.status(Status.OK).type(acceptType).entity(result).build();
+ }
+
+ } catch (AAIException e) {
+ response = consumerExceptionResponseGenerator(headers, info, HttpMethod.PUT, e);
+ } catch (SchemaViolationException sve) {
+ AAIException ex = new AAIException("AAI_4020", sve);
+ response = consumerExceptionResponseGenerator(headers, info, HttpMethod.PUT, ex);
+ } catch (Exception e) {
+ AAIException ex = new AAIException("AAI_4000", e);
+ response = consumerExceptionResponseGenerator(headers, info, HttpMethod.PUT, ex);
+ } finally {
+ if (dbEngine != null) {
+ dbEngine.rollback();
+ }
+
+ }
+
+ return response;
+ }
+
+ private List<Object> dedupObjectInAggregateFormatResult(List<Object> vertTemp) {
+ List<Object> vertTempDedupedObjectList = new ArrayList<Object>();
+ Iterator<Object> itr = vertTemp.listIterator();
+ while (itr.hasNext()) {
+ Object o = itr.next();
+ if (o instanceof ArrayList) {
+ vertTempDedupedObjectList
+ .add(((ArrayList) o).stream().distinct().collect(Collectors.toList()));
+ }
+ }
+ return vertTempDedupedObjectList;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/ExceptionHandler.java b/aai-traversal/src/main/java/org/onap/aai/rest/ExceptionHandler.java
index 452815e..d6d2f5e 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/ExceptionHandler.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/ExceptionHandler.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,10 @@
*/
package org.onap.aai.rest;
+import com.fasterxml.jackson.core.JsonParseException;
+import com.fasterxml.jackson.databind.JsonMappingException;
+import com.sun.istack.SAXParseException2;
+
import java.util.ArrayList;
import java.util.List;
@@ -33,9 +37,6 @@ import javax.ws.rs.ext.Provider;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.logging.ErrorLogHelper;
-import com.fasterxml.jackson.core.JsonParseException;
-import com.fasterxml.jackson.databind.JsonMappingException;
-import com.sun.istack.SAXParseException2;
/**
* The Class ExceptionHandler.
@@ -43,84 +44,81 @@ import com.sun.istack.SAXParseException2;
@Provider
public class ExceptionHandler implements ExceptionMapper<Exception> {
- private static final String AAI_4007 = "AAI_4007";
+ private static final String AAI_4007 = "AAI_4007";
@Context
private HttpServletRequest request;
-
+
@Context
private HttpHeaders headers;
-
+
@Override
public Response toResponse(Exception exception) {
- Response response = null;
- ArrayList<String> templateVars = new ArrayList<>();
+ Response response = null;
+ ArrayList<String> templateVars = new ArrayList<>();
- //the general case is that cxf will give us a WebApplicationException
- //with a linked exception
- if (exception instanceof WebApplicationException) {
- WebApplicationException e = (WebApplicationException) exception;
- if (e.getCause() instanceof SAXParseException2) {
- templateVars.add("UnmarshalException");
- AAIException ex = new AAIException(AAI_4007, exception);
- response = Response
- .status(400)
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
- .build();
+ // the general case is that cxf will give us a WebApplicationException
+ // with a linked exception
+ if (exception instanceof WebApplicationException) {
+ WebApplicationException e = (WebApplicationException) exception;
+ if (e.getCause() instanceof SAXParseException2) {
+ templateVars.add("UnmarshalException");
+ AAIException ex = new AAIException(AAI_4007, exception);
+ response = Response.status(400).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
+ .build();
- }
- } else if (exception instanceof JsonParseException) {
- //jackson does it differently so we get the direct JsonParseException
- templateVars.add("JsonParseException");
- AAIException ex = new AAIException(AAI_4007, exception);
- response = Response
- .status(400)
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
- .build();
+ }
+ } else if (exception instanceof JsonParseException) {
+ // jackson does it differently so we get the direct JsonParseException
+ templateVars.add("JsonParseException");
+ AAIException ex = new AAIException(AAI_4007, exception);
+ response = Response
+ .status(400).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
+ .build();
} else if (exception instanceof JsonMappingException) {
- //jackson does it differently so we get the direct JsonParseException
- templateVars.add("JsonMappingException");
- AAIException ex = new AAIException(AAI_4007, exception);
- response = Response
- .status(400)
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
- .build();
- }
-
- // it didn't get set above, we wrap a general fault here
- if (response == null) {
-
- Exception actual_e = exception;
- if (exception instanceof WebApplicationException) {
- WebApplicationException e = (WebApplicationException) exception;
- response = e.getResponse();
- } else {
- templateVars.add(request.getMethod());
- templateVars.add("unknown");
- AAIException ex = new AAIException("AAI_4000", actual_e);
- List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
- int setError = 0;
+ // jackson does it differently so we get the direct JsonParseException
+ templateVars.add("JsonMappingException");
+ AAIException ex = new AAIException(AAI_4007, exception);
+ response = Response
+ .status(400).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
+ .build();
+ }
+
+ // it didn't get set above, we wrap a general fault here
+ if (response == null) {
+
+ Exception actual_e = exception;
+ if (exception instanceof WebApplicationException) {
+ WebApplicationException e = (WebApplicationException) exception;
+ response = e.getResponse();
+ } else {
+ templateVars.add(request.getMethod());
+ templateVars.add("unknown");
+ AAIException ex = new AAIException("AAI_4000", actual_e);
+ List<MediaType> mediaTypes = headers.getAcceptableMediaTypes();
+ int setError = 0;
- for (MediaType mediaType : mediaTypes) {
- if (MediaType.APPLICATION_XML_TYPE.isCompatible(mediaType)) {
- response = Response
- .status(400)
- .type(MediaType.APPLICATION_XML_TYPE)
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
- .build();
- setError = 1;
- }
- }
- if (setError == 0) {
- response = Response
- .status(400)
- .type(MediaType.APPLICATION_JSON_TYPE)
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
- .build();
- }
- }
- }
- return response;
+ for (MediaType mediaType : mediaTypes) {
+ if (MediaType.APPLICATION_XML_TYPE.isCompatible(mediaType)) {
+ response = Response.status(400).type(MediaType.APPLICATION_XML_TYPE)
+ .entity(ErrorLogHelper.getRESTAPIErrorResponse(
+ headers.getAcceptableMediaTypes(), ex, templateVars))
+ .build();
+ setError = 1;
+ }
+ }
+ if (setError == 0) {
+ response = Response.status(400).type(MediaType.APPLICATION_JSON_TYPE)
+ .entity(ErrorLogHelper.getRESTAPIErrorResponse(
+ headers.getAcceptableMediaTypes(), ex, templateVars))
+ .build();
+ }
+ }
+ }
+ return response;
}
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/QueryConsumer.java b/aai-traversal/src/main/java/org/onap/aai/rest/QueryConsumer.java
index e015ec3..460065e 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/QueryConsumer.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/QueryConsumer.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -22,14 +22,24 @@ package org.onap.aai.rest;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+
import io.micrometer.core.annotation.Timed;
+
+import java.net.URI;
+import java.util.*;
+import java.util.stream.Collectors;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.*;
+import javax.ws.rs.core.Response.Status;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.onap.aai.concurrent.AaiCallable;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.ModelType;
import org.onap.aai.logging.ErrorLogHelper;
-
import org.onap.aai.parsers.query.QueryParser;
import org.onap.aai.rest.db.HttpEntry;
import org.onap.aai.rest.search.CustomQueryConfig;
@@ -54,181 +64,178 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.*;
-import javax.ws.rs.core.Response.Status;
-import java.net.URI;
-import java.util.*;
-import java.util.stream.Collectors;
-
@Path("{version: v[1-9][0-9]*|latest}/query")
@Timed
public class QueryConsumer extends TraversalConsumer {
- private QueryProcessorType processorType = QueryProcessorType.LOCAL_GROOVY;
-
- private static final Logger LOGGER = LoggerFactory.getLogger(QueryConsumer.class);
-
- private HttpEntry traversalUriHttpEntry;
-
-
- private SchemaVersions schemaVersions;
-
- private String basePath;
-
- private GremlinServerSingleton gremlinServerSingleton;
-
- private XmlFormatTransformer xmlFormatTransformer;
-
- @Autowired
- public QueryConsumer(HttpEntry traversalUriHttpEntry, SchemaVersions schemaVersions,
- GremlinServerSingleton gremlinServerSingleton, XmlFormatTransformer xmlFormatTransformer, @Value("${schema.uri.base.path}") String basePath) {
- this.traversalUriHttpEntry = traversalUriHttpEntry;
- this.schemaVersions = schemaVersions;
- this.gremlinServerSingleton = gremlinServerSingleton;
- this.basePath = basePath;
- this.xmlFormatTransformer = xmlFormatTransformer;
- }
-
- @PUT
- @Consumes({ MediaType.APPLICATION_JSON})
- @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
- public Response executeQuery(String content,
- @PathParam("version") String versionParam,
- @DefaultValue("graphson") @QueryParam("format") String queryFormat,
- @DefaultValue("no_op") @QueryParam("subgraph") String subgraph,
- @Context HttpHeaders headers,
- @Context HttpServletRequest req,
- @Context UriInfo info,
- @DefaultValue("-1") @QueryParam("resultIndex") String resultIndex,
- @DefaultValue("-1") @QueryParam("resultSize") String resultSize) {
- Set<String> roles = this.getRoles(req.getUserPrincipal());
-
- return runner(TraversalConstants.AAI_TRAVERSAL_TIMEOUT_ENABLED,
- TraversalConstants.AAI_TRAVERSAL_TIMEOUT_APP,
- TraversalConstants.AAI_TRAVERSAL_TIMEOUT_LIMIT,
- headers,
- info,
- HttpMethod.GET,
- new AaiCallable<Response>() {
- @Override
- public Response process() {
- return processExecuteQuery(content, req, versionParam, queryFormat, subgraph, headers, info, resultIndex, resultSize, roles);
- }
- });
- }
-
- public Response processExecuteQuery(String content, HttpServletRequest req, String versionParam, String queryFormat, String subgraph,
- HttpHeaders headers, UriInfo info, String resultIndex,
- String resultSize, Set<String> roles) {
-
- String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
- String queryProcessor = headers.getRequestHeaders().getFirst("QueryProcessor");
- QueryProcessorType processorType = this.processorType;
- Response response;
- TransactionalGraphEngine dbEngine = null;
-
- try {
- this.checkQueryParams(info.getQueryParameters());
- Format format = Format.getFormat(queryFormat);
- if (queryProcessor != null) {
- processorType = QueryProcessorType.valueOf(queryProcessor);
- }
- SubGraphStyle subGraphStyle = SubGraphStyle.valueOf(subgraph);
-
- JsonParser parser = new JsonParser();
- JsonObject input = parser.parse(content).getAsJsonObject();
- JsonElement startElement = input.get("start");
- JsonElement queryElement = input.get("query");
- JsonElement gremlinElement = input.get("gremlin");
- List<URI> startURIs = new ArrayList<>();
- String queryURI = "";
- String gremlin = "";
-
- SchemaVersion version = new SchemaVersion(versionParam);
- String serverBase = req.getRequestURL().toString().replaceAll("/(v[0-9]+|latest)/.*", "/");
- traversalUriHttpEntry.setHttpEntryProperties(version, serverBase);
- /*
- * Changes for Pagination
- */
-
- traversalUriHttpEntry.setPaginationParameters(resultIndex, resultSize);
- dbEngine = traversalUriHttpEntry.getDbEngine();
-
- if (startElement != null) {
-
- if (startElement.isJsonArray()) {
- for (JsonElement element : startElement.getAsJsonArray()) {
- startURIs.add(new URI(element.getAsString()));
- }
- } else {
- startURIs.add(new URI(startElement.getAsString()));
- }
- }
- if (queryElement != null) {
- queryURI = queryElement.getAsString();
- }
- if (gremlinElement != null) {
- gremlin = gremlinElement.getAsString();
- }
- URI queryURIObj = new URI(queryURI);
-
- CustomQueryConfig customQueryConfig = getCustomQueryConfig(queryURIObj);
- if ( customQueryConfig != null ) {
- List<String> missingRequiredQueryParameters = checkForMissingQueryParameters( customQueryConfig.getQueryRequiredProperties(), URITools.getQueryMap(queryURIObj));
-
- if ( !missingRequiredQueryParameters.isEmpty() ) {
- return( createMessageMissingQueryRequiredParameters( missingRequiredQueryParameters, headers));
- }
-
- List<String> invalidQueryParameters = checkForInvalidQueryParameters( customQueryConfig, URITools.getQueryMap(queryURIObj));
-
- if ( !invalidQueryParameters.isEmpty() ) {
- return( createMessageInvalidQueryParameters( invalidQueryParameters, headers));
- }
-
- } else if ( queryElement != null ) {
- return (createMessageInvalidQuerySection(queryURI, headers));
- }
-
- GenericQueryProcessor processor;
-
- if(isHistory(format)){
- validateHistoryParams(format, info.getQueryParameters());
- }
- GraphTraversalSource traversalSource = getTraversalSource(dbEngine, format, info, roles);
- QueryStyle queryStyle = getQueryStyle(format, traversalUriHttpEntry);
-
- if (!startURIs.isEmpty()) {
- Set<Vertex> vertexSet = new LinkedHashSet<>();
- QueryParser uriQuery;
- List<Vertex> vertices;
- for (URI startUri : startURIs) {
- uriQuery = dbEngine.getQueryBuilder(queryStyle, traversalSource).createQueryFromURI(startUri, URITools.getQueryMap(startUri));
- vertices = uriQuery.getQueryBuilder().toList();
- vertexSet.addAll(vertices);
- }
-
- processor = new GenericQueryProcessor.Builder(dbEngine, gremlinServerSingleton)
- .startFrom(vertexSet).queryFrom(queryURIObj).format(format)
- .processWith(processorType).traversalSource(isHistory(format), traversalSource).create();
- } else if (!queryURI.equals("")){
- processor = new GenericQueryProcessor.Builder(dbEngine, gremlinServerSingleton)
- .queryFrom(queryURIObj)
- .processWith(processorType).traversalSource(isHistory(format), traversalSource).create();
- } else {
- processor = new GenericQueryProcessor.Builder(dbEngine, gremlinServerSingleton)
- .queryFrom(gremlin, "gremlin")
- .processWith(processorType).traversalSource(isHistory(format), traversalSource).create();
- }
- List<Object> vertTemp = processor.execute(subGraphStyle);
- List<Object> vertices = traversalUriHttpEntry.getPaginatedVertexList(vertTemp);
-
- DBSerializer serializer = new DBSerializer(version, dbEngine, ModelType.MOXY, sourceOfTruth);
- FormatFactory ff = new FormatFactory(traversalUriHttpEntry.getLoader(), serializer, schemaVersions, this.basePath, serverBase);
-
- MultivaluedMap<String, String> mvm = new MultivaluedHashMap<>();
+ private QueryProcessorType processorType = QueryProcessorType.LOCAL_GROOVY;
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(QueryConsumer.class);
+
+ private HttpEntry traversalUriHttpEntry;
+
+ private SchemaVersions schemaVersions;
+
+ private String basePath;
+
+ private GremlinServerSingleton gremlinServerSingleton;
+
+ private XmlFormatTransformer xmlFormatTransformer;
+
+ @Autowired
+ public QueryConsumer(HttpEntry traversalUriHttpEntry, SchemaVersions schemaVersions,
+ GremlinServerSingleton gremlinServerSingleton, XmlFormatTransformer xmlFormatTransformer,
+ @Value("${schema.uri.base.path}") String basePath) {
+ this.traversalUriHttpEntry = traversalUriHttpEntry;
+ this.schemaVersions = schemaVersions;
+ this.gremlinServerSingleton = gremlinServerSingleton;
+ this.basePath = basePath;
+ this.xmlFormatTransformer = xmlFormatTransformer;
+ }
+
+ @PUT
+ @Consumes({MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
+ public Response executeQuery(String content, @PathParam("version") String versionParam,
+ @DefaultValue("graphson") @QueryParam("format") String queryFormat,
+ @DefaultValue("no_op") @QueryParam("subgraph") String subgraph,
+ @Context HttpHeaders headers, @Context HttpServletRequest req, @Context UriInfo info,
+ @DefaultValue("-1") @QueryParam("resultIndex") String resultIndex,
+ @DefaultValue("-1") @QueryParam("resultSize") String resultSize) {
+ Set<String> roles = this.getRoles(req.getUserPrincipal());
+
+ return runner(TraversalConstants.AAI_TRAVERSAL_TIMEOUT_ENABLED,
+ TraversalConstants.AAI_TRAVERSAL_TIMEOUT_APP,
+ TraversalConstants.AAI_TRAVERSAL_TIMEOUT_LIMIT, headers, info, HttpMethod.GET,
+ new AaiCallable<Response>() {
+ @Override
+ public Response process() {
+ return processExecuteQuery(content, req, versionParam, queryFormat, subgraph,
+ headers, info, resultIndex, resultSize, roles);
+ }
+ });
+ }
+
+ public Response processExecuteQuery(String content, HttpServletRequest req, String versionParam,
+ String queryFormat, String subgraph, HttpHeaders headers, UriInfo info, String resultIndex,
+ String resultSize, Set<String> roles) {
+
+ String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
+ String queryProcessor = headers.getRequestHeaders().getFirst("QueryProcessor");
+ QueryProcessorType processorType = this.processorType;
+ Response response;
+ TransactionalGraphEngine dbEngine = null;
+
+ try {
+ this.checkQueryParams(info.getQueryParameters());
+ Format format = Format.getFormat(queryFormat);
+ if (queryProcessor != null) {
+ processorType = QueryProcessorType.valueOf(queryProcessor);
+ }
+ SubGraphStyle subGraphStyle = SubGraphStyle.valueOf(subgraph);
+
+ JsonParser parser = new JsonParser();
+ JsonObject input = parser.parse(content).getAsJsonObject();
+ JsonElement startElement = input.get("start");
+ JsonElement queryElement = input.get("query");
+ JsonElement gremlinElement = input.get("gremlin");
+ List<URI> startURIs = new ArrayList<>();
+ String queryURI = "";
+ String gremlin = "";
+
+ SchemaVersion version = new SchemaVersion(versionParam);
+ String serverBase =
+ req.getRequestURL().toString().replaceAll("/(v[0-9]+|latest)/.*", "/");
+ traversalUriHttpEntry.setHttpEntryProperties(version, serverBase);
+ /*
+ * Changes for Pagination
+ */
+
+ traversalUriHttpEntry.setPaginationParameters(resultIndex, resultSize);
+ dbEngine = traversalUriHttpEntry.getDbEngine();
+
+ if (startElement != null) {
+
+ if (startElement.isJsonArray()) {
+ for (JsonElement element : startElement.getAsJsonArray()) {
+ startURIs.add(new URI(element.getAsString()));
+ }
+ } else {
+ startURIs.add(new URI(startElement.getAsString()));
+ }
+ }
+ if (queryElement != null) {
+ queryURI = queryElement.getAsString();
+ }
+ if (gremlinElement != null) {
+ gremlin = gremlinElement.getAsString();
+ }
+ URI queryURIObj = new URI(queryURI);
+
+ CustomQueryConfig customQueryConfig = getCustomQueryConfig(queryURIObj);
+ if (customQueryConfig != null) {
+ List<String> missingRequiredQueryParameters =
+ checkForMissingQueryParameters(customQueryConfig.getQueryRequiredProperties(),
+ URITools.getQueryMap(queryURIObj));
+
+ if (!missingRequiredQueryParameters.isEmpty()) {
+ return (createMessageMissingQueryRequiredParameters(
+ missingRequiredQueryParameters, headers));
+ }
+
+ List<String> invalidQueryParameters = checkForInvalidQueryParameters(
+ customQueryConfig, URITools.getQueryMap(queryURIObj));
+
+ if (!invalidQueryParameters.isEmpty()) {
+ return (createMessageInvalidQueryParameters(invalidQueryParameters, headers));
+ }
+
+ } else if (queryElement != null) {
+ return (createMessageInvalidQuerySection(queryURI, headers));
+ }
+
+ GenericQueryProcessor processor;
+
+ if (isHistory(format)) {
+ validateHistoryParams(format, info.getQueryParameters());
+ }
+ GraphTraversalSource traversalSource =
+ getTraversalSource(dbEngine, format, info, roles);
+ QueryStyle queryStyle = getQueryStyle(format, traversalUriHttpEntry);
+
+ if (!startURIs.isEmpty()) {
+ Set<Vertex> vertexSet = new LinkedHashSet<>();
+ QueryParser uriQuery;
+ List<Vertex> vertices;
+ for (URI startUri : startURIs) {
+ uriQuery = dbEngine.getQueryBuilder(queryStyle, traversalSource)
+ .createQueryFromURI(startUri, URITools.getQueryMap(startUri));
+ vertices = uriQuery.getQueryBuilder().toList();
+ vertexSet.addAll(vertices);
+ }
+
+ processor = new GenericQueryProcessor.Builder(dbEngine, gremlinServerSingleton)
+ .startFrom(vertexSet).queryFrom(queryURIObj).format(format)
+ .processWith(processorType).traversalSource(isHistory(format), traversalSource)
+ .create();
+ } else if (!queryURI.equals("")) {
+ processor = new GenericQueryProcessor.Builder(dbEngine, gremlinServerSingleton)
+ .queryFrom(queryURIObj).processWith(processorType)
+ .traversalSource(isHistory(format), traversalSource).create();
+ } else {
+ processor = new GenericQueryProcessor.Builder(dbEngine, gremlinServerSingleton)
+ .queryFrom(gremlin, "gremlin").processWith(processorType)
+ .traversalSource(isHistory(format), traversalSource).create();
+ }
+ List<Object> vertTemp = processor.execute(subGraphStyle);
+ List<Object> vertices = traversalUriHttpEntry.getPaginatedVertexList(vertTemp);
+
+ DBSerializer serializer =
+ new DBSerializer(version, dbEngine, ModelType.MOXY, sourceOfTruth);
+ FormatFactory ff = new FormatFactory(traversalUriHttpEntry.getLoader(), serializer,
+ schemaVersions, this.basePath, serverBase);
+
+ MultivaluedMap<String, String> mvm = new MultivaluedHashMap<>();
mvm.putAll(info.getQueryParameters());
if (isHistory(format)) {
mvm.putSingle("startTs", Long.toString(getStartTime(format, mvm)));
@@ -236,142 +243,139 @@ public class QueryConsumer extends TraversalConsumer {
}
Formatter formatter = ff.get(format, mvm);
- String result = formatter.output(vertices).toString();
-
- String acceptType = headers.getHeaderString("Accept");
-
- if(acceptType == null){
- acceptType = MediaType.APPLICATION_JSON;
- }
-
- if(MediaType.APPLICATION_XML_TYPE.isCompatible(MediaType.valueOf(acceptType))){
- result = xmlFormatTransformer.transform(result);
- }
-
- if(traversalUriHttpEntry.isPaginated()){
- response = Response.status(Status.OK)
- .type(acceptType)
- .header("total-results", traversalUriHttpEntry.getTotalVertices())
- .header("total-pages", traversalUriHttpEntry.getTotalPaginationBuckets())
- .entity(result)
- .build();
- }else {
- response = Response.status(Status.OK)
- .type(acceptType)
- .entity(result).build();
- }
- } catch (AAIException e) {
- response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, e);
- } catch (Exception e ) {
- AAIException ex = new AAIException("AAI_4000", e);
- response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, ex);
- } finally {
- if (dbEngine != null) {
- dbEngine.rollback();
- }
-
- }
-
- return response;
- }
-
- public void checkQueryParams(MultivaluedMap<String, String> params) throws AAIException {
-
- if (params.containsKey("depth") && params.getFirst("depth").matches("\\d+")) {
- String depth = params.getFirst("depth");
- int i = Integer.parseInt(depth);
- if (i > 1) {
- throw new AAIException("AAI_3303");
- }
- }
-
-
- }
-
- private List<String> checkForMissingQueryParameters( List<String> requiredParameters, MultivaluedMap<String, String> queryParams ) {
- List<String> result = new ArrayList<>();
-
- for ( String param : requiredParameters ) {
- if ( !queryParams.containsKey(param)) {
- result.add(param);
- }
- }
- return result;
- }
-
- private CustomQueryConfig getCustomQueryConfig(URI uriObj ) {
- String path = uriObj.getPath();
-
- String[] parts = path.split("/");
- boolean hasQuery = false;
- for ( String part:parts ) {
- if ( hasQuery) {
- return gremlinServerSingleton.getCustomQueryConfig(part);
- }
- if ( "query".equals(part)) {
- hasQuery = true;
- }
- }
-
- return null;
-
- }
-
- private Response createMessageMissingQueryRequiredParameters(List<String> missingRequiredQueryParams, HttpHeaders headers) {
- AAIException e = new AAIException("AAI_3013");
-
- ArrayList<String> templateVars = new ArrayList<>();
- templateVars.add(missingRequiredQueryParams.toString());
-
- return Response
- .status(e.getErrorObject().getHTTPResponseCode())
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e,
- templateVars)).build();
- }
-
- private Response createMessageInvalidQuerySection(String invalidQuery, HttpHeaders headers) {
- AAIException e = new AAIException("AAI_3014");
-
- ArrayList<String> templateVars = new ArrayList<>();
- templateVars.add(invalidQuery);
-
- return Response
- .status(e.getErrorObject().getHTTPResponseCode())
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e,
- templateVars)).build();
- }
-
-
- private List<String> checkForInvalidQueryParameters( CustomQueryConfig customQueryConfig, MultivaluedMap<String, String> queryParams) {
-
- List<String> allParameters = new ArrayList<>();
- /*
- * Add potential Required and Optional to allParameters
- */
- Optional.ofNullable(customQueryConfig.getQueryOptionalProperties()).ifPresent(allParameters::addAll);
- Optional.ofNullable(customQueryConfig.getQueryRequiredProperties()).ifPresent(allParameters::addAll);
-
- if(queryParams.isEmpty()) {
- return new ArrayList<>();
- }
- return queryParams.keySet().stream()
- .filter(param -> !allParameters.contains(param))
- .collect(Collectors.toList());
- }
-
- private Response createMessageInvalidQueryParameters(List<String> invalidQueryParams, HttpHeaders headers) {
- AAIException e = new AAIException("AAI_3022");
-
- ArrayList<String> templateVars = new ArrayList<>();
- templateVars.add(invalidQueryParams.toString());
-
- return Response
- .status(e.getErrorObject().getHTTPResponseCode())
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(
- headers.getAcceptableMediaTypes(),
- e,
- templateVars)).build();
-
- }
+ String result = formatter.output(vertices).toString();
+
+ String acceptType = headers.getHeaderString("Accept");
+
+ if (acceptType == null) {
+ acceptType = MediaType.APPLICATION_JSON;
+ }
+
+ if (MediaType.APPLICATION_XML_TYPE.isCompatible(MediaType.valueOf(acceptType))) {
+ result = xmlFormatTransformer.transform(result);
+ }
+
+ if (traversalUriHttpEntry.isPaginated()) {
+ response = Response.status(Status.OK).type(acceptType)
+ .header("total-results", traversalUriHttpEntry.getTotalVertices())
+ .header("total-pages", traversalUriHttpEntry.getTotalPaginationBuckets())
+ .entity(result).build();
+ } else {
+ response = Response.status(Status.OK).type(acceptType).entity(result).build();
+ }
+ } catch (AAIException e) {
+ response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, e);
+ } catch (Exception e) {
+ AAIException ex = new AAIException("AAI_4000", e);
+ response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, ex);
+ } finally {
+ if (dbEngine != null) {
+ dbEngine.rollback();
+ }
+
+ }
+
+ return response;
+ }
+
+ public void checkQueryParams(MultivaluedMap<String, String> params) throws AAIException {
+
+ if (params.containsKey("depth") && params.getFirst("depth").matches("\\d+")) {
+ String depth = params.getFirst("depth");
+ int i = Integer.parseInt(depth);
+ if (i > 1) {
+ throw new AAIException("AAI_3303");
+ }
+ }
+
+ }
+
+ private List<String> checkForMissingQueryParameters(List<String> requiredParameters,
+ MultivaluedMap<String, String> queryParams) {
+ List<String> result = new ArrayList<>();
+
+ for (String param : requiredParameters) {
+ if (!queryParams.containsKey(param)) {
+ result.add(param);
+ }
+ }
+ return result;
+ }
+
+ private CustomQueryConfig getCustomQueryConfig(URI uriObj) {
+ String path = uriObj.getPath();
+
+ String[] parts = path.split("/");
+ boolean hasQuery = false;
+ for (String part : parts) {
+ if (hasQuery) {
+ return gremlinServerSingleton.getCustomQueryConfig(part);
+ }
+ if ("query".equals(part)) {
+ hasQuery = true;
+ }
+ }
+
+ return null;
+
+ }
+
+ private Response createMessageMissingQueryRequiredParameters(
+ List<String> missingRequiredQueryParams, HttpHeaders headers) {
+ AAIException e = new AAIException("AAI_3013");
+
+ ArrayList<String> templateVars = new ArrayList<>();
+ templateVars.add(missingRequiredQueryParams.toString());
+
+ return Response
+ .status(e.getErrorObject().getHTTPResponseCode()).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars))
+ .build();
+ }
+
+ private Response createMessageInvalidQuerySection(String invalidQuery, HttpHeaders headers) {
+ AAIException e = new AAIException("AAI_3014");
+
+ ArrayList<String> templateVars = new ArrayList<>();
+ templateVars.add(invalidQuery);
+
+ return Response
+ .status(e.getErrorObject().getHTTPResponseCode()).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars))
+ .build();
+ }
+
+ private List<String> checkForInvalidQueryParameters(CustomQueryConfig customQueryConfig,
+ MultivaluedMap<String, String> queryParams) {
+
+ List<String> allParameters = new ArrayList<>();
+ /*
+ * Add potential Required and Optional to allParameters
+ */
+ Optional.ofNullable(customQueryConfig.getQueryOptionalProperties())
+ .ifPresent(allParameters::addAll);
+ Optional.ofNullable(customQueryConfig.getQueryRequiredProperties())
+ .ifPresent(allParameters::addAll);
+
+ if (queryParams.isEmpty()) {
+ return new ArrayList<>();
+ }
+ return queryParams.keySet().stream().filter(param -> !allParameters.contains(param))
+ .collect(Collectors.toList());
+ }
+
+ private Response createMessageInvalidQueryParameters(List<String> invalidQueryParams,
+ HttpHeaders headers) {
+ AAIException e = new AAIException("AAI_3022");
+
+ ArrayList<String> templateVars = new ArrayList<>();
+ templateVars.add(invalidQueryParams.toString());
+
+ return Response
+ .status(e.getErrorObject().getHTTPResponseCode()).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars))
+ .build();
+
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/RecentAPIConsumer.java b/aai-traversal/src/main/java/org/onap/aai/rest/RecentAPIConsumer.java
index 7ec20bc..7f40979 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/RecentAPIConsumer.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/RecentAPIConsumer.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -20,11 +20,19 @@
package org.onap.aai.rest;
import io.micrometer.core.annotation.Timed;
+
+import java.util.List;
+import java.util.concurrent.TimeUnit;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.*;
+import javax.ws.rs.core.Response.Status;
+
import org.onap.aai.concurrent.AaiCallable;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.introspection.ModelType;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
-
import org.onap.aai.rest.db.HttpEntry;
import org.onap.aai.rest.search.GenericQueryProcessor;
import org.onap.aai.rest.search.GremlinServerSingleton;
@@ -47,209 +55,205 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.*;
-import javax.ws.rs.core.Response.Status;
-import java.util.List;
-import java.util.concurrent.TimeUnit;
-
@Path("/recents/{version: v[1-9][0-9]*|latest}")
@Timed
public class RecentAPIConsumer extends RESTAPI {
private static final String AAI_3021 = "AAI_3021";
-
- /** The introspector factory type. */
- private ModelType introspectorFactoryType = ModelType.MOXY;
-
- private QueryProcessorType processorType = QueryProcessorType.LOCAL_GROOVY;
- /** The query style. */
-
- private static final Logger LOGGER = LoggerFactory.getLogger(RecentAPIConsumer.class);
-
- private HttpEntry traversalUriHttpEntry;
-
- private SchemaVersions schemaVersions;
-
- private String basePath;
-
- private GremlinServerSingleton gremlinServerSingleton;
-
- private XmlFormatTransformer xmlFormatTransformer;
-
-
- @Autowired
- public RecentAPIConsumer(
- HttpEntry traversalUriHttpEntry,
- SchemaVersions schemaVersions,
- GremlinServerSingleton gremlinServerSingleton,
- XmlFormatTransformer xmlFormatTransformer,
- @Value("${schema.uri.base.path}") String basePath
- ){
- this.traversalUriHttpEntry = traversalUriHttpEntry;
- this.schemaVersions = schemaVersions;
- this.gremlinServerSingleton = gremlinServerSingleton;
- this.xmlFormatTransformer = xmlFormatTransformer;
- this.basePath = basePath;
- }
-
- @GET
- @Path("/{nodeType: .+}")
- @Consumes({ MediaType.APPLICATION_JSON })
- @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
- public Response getRecentData(String content,
- @PathParam("version") String versionParam,
- @PathParam("nodeType") String nodeType,
- @Context HttpHeaders headers,
- @Context HttpServletRequest req,
- @Context UriInfo info) {
-
- return runner(TraversalConstants.AAI_TRAVERSAL_TIMEOUT_ENABLED, TraversalConstants.AAI_TRAVERSAL_TIMEOUT_APP,
- TraversalConstants.AAI_TRAVERSAL_TIMEOUT_LIMIT, headers, info, HttpMethod.GET, new AaiCallable<Response>() {
- @Override
- public Response process() {
- return processRecentData(content, req, versionParam, nodeType, info, headers);
- }
- });
-
- }
-
- public Response processRecentData(String content, HttpServletRequest req, @PathParam("version") String versionParam,
- @PathParam("nodeType") String nodeType, @Context UriInfo info, @Context HttpHeaders headers) {
-
- String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
- String queryProcessor = headers.getRequestHeaders().getFirst("QueryProcessor");
- QueryProcessorType processorType = this.processorType;
- Response response;
- TransactionalGraphEngine dbEngine = null;
- try {
-
- if (queryProcessor != null) {
- processorType = QueryProcessorType.valueOf(queryProcessor);
- }
-
- SchemaVersion version = new SchemaVersion(versionParam);
- this.checkVersion(version);
-
- String serverBase = req.getRequestURL().toString().replaceAll("/(v[0-9]+|latest)/.*", "/");
- traversalUriHttpEntry.setHttpEntryProperties(version, serverBase);
- dbEngine = traversalUriHttpEntry.getDbEngine();
-
- /*
- * Check for mandatory parameters here
- */
-
- this.checkNodeType(nodeType);
- this.checkQueryParams(info.getQueryParameters());
-
- GenericQueryProcessor processor = null;
-
-
-
- processor = new GenericQueryProcessor.Builder(dbEngine, gremlinServerSingleton).queryFrom(nodeType, "nodeQuery")
- .uriParams(info.getQueryParameters())
- .processWith(processorType).create();
-
-
-
- String result = "";
- SubGraphStyle subGraphStyle = null;
- List<Object> vertices = processor.execute(subGraphStyle);
-
- DBSerializer serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, sourceOfTruth);
- FormatFactory ff = new FormatFactory(traversalUriHttpEntry.getLoader(), serializer, schemaVersions, this.basePath, serverBase);
+
+ /** The introspector factory type. */
+ private ModelType introspectorFactoryType = ModelType.MOXY;
+
+ private QueryProcessorType processorType = QueryProcessorType.LOCAL_GROOVY;
+ /** The query style. */
+
+ private static final Logger LOGGER = LoggerFactory.getLogger(RecentAPIConsumer.class);
+
+ private HttpEntry traversalUriHttpEntry;
+
+ private SchemaVersions schemaVersions;
+
+ private String basePath;
+
+ private GremlinServerSingleton gremlinServerSingleton;
+
+ private XmlFormatTransformer xmlFormatTransformer;
+
+ @Autowired
+ public RecentAPIConsumer(HttpEntry traversalUriHttpEntry, SchemaVersions schemaVersions,
+ GremlinServerSingleton gremlinServerSingleton, XmlFormatTransformer xmlFormatTransformer,
+ @Value("${schema.uri.base.path}") String basePath) {
+ this.traversalUriHttpEntry = traversalUriHttpEntry;
+ this.schemaVersions = schemaVersions;
+ this.gremlinServerSingleton = gremlinServerSingleton;
+ this.xmlFormatTransformer = xmlFormatTransformer;
+ this.basePath = basePath;
+ }
+
+ @GET
+ @Path("/{nodeType: .+}")
+ @Consumes({MediaType.APPLICATION_JSON})
+ @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
+ public Response getRecentData(String content, @PathParam("version") String versionParam,
+ @PathParam("nodeType") String nodeType, @Context HttpHeaders headers,
+ @Context HttpServletRequest req, @Context UriInfo info) {
+
+ return runner(TraversalConstants.AAI_TRAVERSAL_TIMEOUT_ENABLED,
+ TraversalConstants.AAI_TRAVERSAL_TIMEOUT_APP,
+ TraversalConstants.AAI_TRAVERSAL_TIMEOUT_LIMIT, headers, info, HttpMethod.GET,
+ new AaiCallable<Response>() {
+ @Override
+ public Response process() {
+ return processRecentData(content, req, versionParam, nodeType, info, headers);
+ }
+ });
+
+ }
+
+ public Response processRecentData(String content, HttpServletRequest req,
+ @PathParam("version") String versionParam, @PathParam("nodeType") String nodeType,
+ @Context UriInfo info, @Context HttpHeaders headers) {
+
+ String sourceOfTruth = headers.getRequestHeaders().getFirst("X-FromAppId");
+ String queryProcessor = headers.getRequestHeaders().getFirst("QueryProcessor");
+ QueryProcessorType processorType = this.processorType;
+ Response response;
+ TransactionalGraphEngine dbEngine = null;
+ try {
+
+ if (queryProcessor != null) {
+ processorType = QueryProcessorType.valueOf(queryProcessor);
+ }
+
+ SchemaVersion version = new SchemaVersion(versionParam);
+ this.checkVersion(version);
+
+ String serverBase =
+ req.getRequestURL().toString().replaceAll("/(v[0-9]+|latest)/.*", "/");
+ traversalUriHttpEntry.setHttpEntryProperties(version, serverBase);
+ dbEngine = traversalUriHttpEntry.getDbEngine();
+
+ /*
+ * Check for mandatory parameters here
+ */
+
+ this.checkNodeType(nodeType);
+ this.checkQueryParams(info.getQueryParameters());
+
+ GenericQueryProcessor processor = null;
+
+ processor = new GenericQueryProcessor.Builder(dbEngine, gremlinServerSingleton)
+ .queryFrom(nodeType, "nodeQuery").uriParams(info.getQueryParameters())
+ .processWith(processorType).create();
+
+ String result = "";
+ SubGraphStyle subGraphStyle = null;
+ List<Object> vertices = processor.execute(subGraphStyle);
+
+ DBSerializer serializer =
+ new DBSerializer(version, dbEngine, introspectorFactoryType, sourceOfTruth);
+ FormatFactory ff = new FormatFactory(traversalUriHttpEntry.getLoader(), serializer,
+ schemaVersions, this.basePath, serverBase);
Format format = Format.pathed_resourceversion;
-
- Formatter formater = ff.get(format, info.getQueryParameters());
-
- result = formater.output(vertices).toString();
-
- //LOGGER.info("Completed");
-
- String acceptType = headers.getHeaderString("Accept");
-
- if(acceptType == null){
- acceptType = MediaType.APPLICATION_JSON;
- }
-
- if(MediaType.APPLICATION_XML_TYPE.isCompatible(MediaType.valueOf(acceptType))){
- result = xmlFormatTransformer.transform(result);
- }
-
- response = Response.status(Status.OK).type(acceptType).entity(result).build();
-
- } catch (AAIException e) {
- response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, e);
- } catch (Exception e) {
- AAIException ex = new AAIException("AAI_4000", e);
- response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, ex);
- } finally {
-
- if (dbEngine != null) {
- dbEngine.rollback();
- }
-
- }
-
- return response;
- }
-
- private void checkVersion(SchemaVersion version) throws AAIException {
- if(!schemaVersions.getVersions().contains(version)){
- throw new AAIException(AAI_3021, "Schema Version is not valid");
- }
- }
-
- public void checkNodeType(String nodeType) throws AAIException {
- try {
- traversalUriHttpEntry.getLoader().introspectorFromName(nodeType);
- } catch (AAIUnknownObjectException e) {
- throw new AAIException("AAI_6115", "Unrecognized nodeType [" + nodeType + "] passed to recents query.");
- }
- }
- public void checkQueryParams(MultivaluedMap<String, String> params) throws AAIException {
-
- boolean isHoursParameter = false;
- boolean isDateTimeParameter = false;
-
- if (params != null && params.containsKey("hours") && params.getFirst("hours").matches("-?\\d+")) {
- isHoursParameter = true;
- long hours;
- try{
- hours = Long.parseLong(params.getFirst("hours"));
- }
- catch(NumberFormatException ex){
- throw new AAIException(AAI_3021, " Invalid Hours. Valid values for hours are 1 to " + AAIConstants.HISTORY_MAX_HOURS);
- }
- if (hours < 1 || hours > AAIConstants.HISTORY_MAX_HOURS) {
- throw new AAIException(AAI_3021, " Valid values for hours are 1 to " + AAIConstants.HISTORY_MAX_HOURS);
- }
- }
- if (params != null && params.containsKey("date-time") && params.getFirst("date-time").matches("-?\\d+")) {
- isDateTimeParameter = true;
- Long minStartTime = System.currentTimeMillis() - TimeUnit.HOURS.toMillis(AAIConstants.HISTORY_MAX_HOURS);
- Long startTime;
- try{
- startTime = Long.parseLong(params.getFirst("date-time"));
- }
- catch(NumberFormatException ex){
- throw new AAIException(AAI_3021, " Invalid Data-time. Valid values for date-time are "+minStartTime+" to " + System.currentTimeMillis() );
- }
- if (startTime < minStartTime) {
- throw new AAIException(AAI_3021, " Valid values for date-time are "+minStartTime+" to " + System.currentTimeMillis() );
- }
- }
-
- if(!isHoursParameter && !isDateTimeParameter){
- throw new AAIException(AAI_3021, "Send valid hours or date-time to specify the timebounds");
- }
-
- if(isHoursParameter && isDateTimeParameter){
- throw new AAIException(AAI_3021, "Send either hours or date-time and not both to specify the timebounds");
- }
-
-
- }
+
+ Formatter formater = ff.get(format, info.getQueryParameters());
+
+ result = formater.output(vertices).toString();
+
+ // LOGGER.info("Completed");
+
+ String acceptType = headers.getHeaderString("Accept");
+
+ if (acceptType == null) {
+ acceptType = MediaType.APPLICATION_JSON;
+ }
+
+ if (MediaType.APPLICATION_XML_TYPE.isCompatible(MediaType.valueOf(acceptType))) {
+ result = xmlFormatTransformer.transform(result);
+ }
+
+ response = Response.status(Status.OK).type(acceptType).entity(result).build();
+
+ } catch (AAIException e) {
+ response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, e);
+ } catch (Exception e) {
+ AAIException ex = new AAIException("AAI_4000", e);
+ response = consumerExceptionResponseGenerator(headers, info, HttpMethod.GET, ex);
+ } finally {
+
+ if (dbEngine != null) {
+ dbEngine.rollback();
+ }
+
+ }
+
+ return response;
+ }
+
+ private void checkVersion(SchemaVersion version) throws AAIException {
+ if (!schemaVersions.getVersions().contains(version)) {
+ throw new AAIException(AAI_3021, "Schema Version is not valid");
+ }
+ }
+
+ public void checkNodeType(String nodeType) throws AAIException {
+ try {
+ traversalUriHttpEntry.getLoader().introspectorFromName(nodeType);
+ } catch (AAIUnknownObjectException e) {
+ throw new AAIException("AAI_6115",
+ "Unrecognized nodeType [" + nodeType + "] passed to recents query.");
+ }
+ }
+
+ public void checkQueryParams(MultivaluedMap<String, String> params) throws AAIException {
+
+ boolean isHoursParameter = false;
+ boolean isDateTimeParameter = false;
+
+ if (params != null && params.containsKey("hours")
+ && params.getFirst("hours").matches("-?\\d+")) {
+ isHoursParameter = true;
+ long hours;
+ try {
+ hours = Long.parseLong(params.getFirst("hours"));
+ } catch (NumberFormatException ex) {
+ throw new AAIException(AAI_3021, " Invalid Hours. Valid values for hours are 1 to "
+ + AAIConstants.HISTORY_MAX_HOURS);
+ }
+ if (hours < 1 || hours > AAIConstants.HISTORY_MAX_HOURS) {
+ throw new AAIException(AAI_3021,
+ " Valid values for hours are 1 to " + AAIConstants.HISTORY_MAX_HOURS);
+ }
+ }
+ if (params != null && params.containsKey("date-time")
+ && params.getFirst("date-time").matches("-?\\d+")) {
+ isDateTimeParameter = true;
+ Long minStartTime = System.currentTimeMillis()
+ - TimeUnit.HOURS.toMillis(AAIConstants.HISTORY_MAX_HOURS);
+ Long startTime;
+ try {
+ startTime = Long.parseLong(params.getFirst("date-time"));
+ } catch (NumberFormatException ex) {
+ throw new AAIException(AAI_3021,
+ " Invalid Data-time. Valid values for date-time are " + minStartTime + " to "
+ + System.currentTimeMillis());
+ }
+ if (startTime < minStartTime) {
+ throw new AAIException(AAI_3021, " Valid values for date-time are " + minStartTime
+ + " to " + System.currentTimeMillis());
+ }
+ }
+
+ if (!isHoursParameter && !isDateTimeParameter) {
+ throw new AAIException(AAI_3021,
+ "Send valid hours or date-time to specify the timebounds");
+ }
+
+ if (isHoursParameter && isDateTimeParameter) {
+ throw new AAIException(AAI_3021,
+ "Send either hours or date-time and not both to specify the timebounds");
+ }
+
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/TraversalConsumer.java b/aai-traversal/src/main/java/org/onap/aai/rest/TraversalConsumer.java
index a8f88ec..2980f28 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/TraversalConsumer.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/TraversalConsumer.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,15 @@
*/
package org.onap.aai.rest;
+import java.security.Principal;
+import java.util.Collections;
+import java.util.Set;
+import java.util.concurrent.TimeUnit;
+import java.util.stream.Collectors;
+
+import javax.ws.rs.core.MultivaluedMap;
+import javax.ws.rs.core.UriInfo;
+
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.tinkerpop.gremlin.process.traversal.P;
@@ -37,14 +46,6 @@ import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.serialization.queryformats.Format;
-import javax.ws.rs.core.MultivaluedMap;
-import javax.ws.rs.core.UriInfo;
-import java.security.Principal;
-import java.util.Collections;
-import java.util.Set;
-import java.util.concurrent.TimeUnit;
-import java.util.stream.Collectors;
-
public abstract class TraversalConsumer extends RESTAPI {
private static final String HISTORICAL_FORMAT = "state,lifecycle";
@@ -57,12 +58,12 @@ public abstract class TraversalConsumer extends RESTAPI {
private Long furthestInThePast = null;
public TraversalConsumer() {
- this.historyTruncateWindow = Integer.parseInt(
- SpringContextAware.getApplicationContext().getEnvironment().getProperty("history.truncate.window.days", "365"));
- this.historyEnabled = Boolean.parseBoolean(
- SpringContextAware.getApplicationContext().getEnvironment().getProperty("history.enabled", "false"));
- this.multiTenancyEnabled = Boolean.parseBoolean(
- SpringContextAware.getApplicationContext().getEnvironment().getProperty("multi.tenancy.enabled", "false"));
+ this.historyTruncateWindow = Integer.parseInt(SpringContextAware.getApplicationContext()
+ .getEnvironment().getProperty("history.truncate.window.days", "365"));
+ this.historyEnabled = Boolean.parseBoolean(SpringContextAware.getApplicationContext()
+ .getEnvironment().getProperty("history.enabled", "false"));
+ this.multiTenancyEnabled = Boolean.parseBoolean(SpringContextAware.getApplicationContext()
+ .getEnvironment().getProperty("multi.tenancy.enabled", "false"));
}
public boolean isHistory(Format queryFormat) {
@@ -84,85 +85,60 @@ public abstract class TraversalConsumer extends RESTAPI {
} else if (Format.lifecycle.equals(format)) {
return getLifeCycleSubgraphStrategy(startTs, endTs);
} else {
- return SubgraphStrategy.build()
- .vertices(__.has(AAIProperties.START_TS, P.gte(startTs)))
- .vertexProperties(__.has(AAIProperties.START_TS, P.gte(startTs)))
- .edges(__.has(AAIProperties.START_TS, P.gte(startTs))).create();
+ return SubgraphStrategy.build().vertices(__.has(AAIProperties.START_TS, P.gte(startTs)))
+ .vertexProperties(__.has(AAIProperties.START_TS, P.gte(startTs)))
+ .edges(__.has(AAIProperties.START_TS, P.gte(startTs))).create();
}
}
private SubgraphStrategy getLifeCycleSubgraphStrategy(long startTs, long endTs) {
return SubgraphStrategy.build()
- .vertices(
- __.not(
- __.or(
- __.and(
- __.has(AAIProperties.START_TS, P.gt(startTs)),
- __.has(AAIProperties.START_TS, P.gt(endTs))
- ),
- __.and(
- __.has(AAIProperties.END_TS).has(AAIProperties.END_TS, P.lt(startTs)),
- __.has(AAIProperties.END_TS).has(AAIProperties.END_TS, P.lt(endTs))
- )
- )
- )
- ).vertexProperties(
- __.not(
- __.or(
- __.and(
- __.has(AAIProperties.START_TS, P.gt(startTs)),
- __.has(AAIProperties.START_TS, P.gt(endTs))
- ),
- __.and(
- __.has(AAIProperties.END_TS).has(AAIProperties.END_TS, P.lt(startTs)),
- __.has(AAIProperties.END_TS).has(AAIProperties.END_TS, P.lt(endTs))
- )
- )
- )
- ).edges(
- __.not(
- __.or(
- __.and(
- __.has(AAIProperties.START_TS, P.gt(startTs)),
- __.has(AAIProperties.START_TS, P.gt(endTs))
- ),
- __.and(
- __.has(AAIProperties.END_TS).has(AAIProperties.END_TS, P.lt(startTs)),
- __.has(AAIProperties.END_TS).has(AAIProperties.END_TS, P.lt(endTs))
- )
- )
- )
- ).create();
+ .vertices(__.not(__.or(
+ __.and(__.has(AAIProperties.START_TS, P.gt(startTs)),
+ __.has(AAIProperties.START_TS, P.gt(endTs))),
+ __.and(__.has(AAIProperties.END_TS).has(AAIProperties.END_TS, P.lt(startTs)),
+ __.has(AAIProperties.END_TS).has(AAIProperties.END_TS, P.lt(endTs))))))
+ .vertexProperties(__.not(__.or(
+ __.and(__.has(AAIProperties.START_TS, P.gt(startTs)),
+ __.has(AAIProperties.START_TS, P.gt(endTs))),
+ __.and(__.has(AAIProperties.END_TS).has(AAIProperties.END_TS, P.lt(startTs)),
+ __.has(AAIProperties.END_TS).has(AAIProperties.END_TS, P.lt(endTs))))))
+ .edges(__.not(__.or(
+ __.and(__.has(AAIProperties.START_TS, P.gt(startTs)),
+ __.has(AAIProperties.START_TS, P.gt(endTs))),
+ __.and(__.has(AAIProperties.END_TS).has(AAIProperties.END_TS, P.lt(startTs)),
+ __.has(AAIProperties.END_TS).has(AAIProperties.END_TS, P.lt(endTs))))))
+ .create();
}
private SubgraphStrategy getStateSubgraphStrategy(long startTs) {
return SubgraphStrategy.build()
- .vertices(
- __.and(__.has(AAIProperties.START_TS, P.lte(startTs)),
- __.or(__.hasNot(AAIProperties.END_TS), __.has(AAIProperties.END_TS, P.gt(startTs))))
- ).vertexProperties(
- __.and(__.has(AAIProperties.START_TS, P.lte(startTs)),
- __.or(__.hasNot(AAIProperties.END_TS), __.has(AAIProperties.END_TS, P.gt(startTs))))
- ).edges(
- __.and(__.has(AAIProperties.START_TS, P.lte(startTs)),
- __.or(__.hasNot(AAIProperties.END_TS), __.has(AAIProperties.END_TS, P.gt(startTs))))
- ).create();
+ .vertices(__.and(__.has(AAIProperties.START_TS, P.lte(startTs)),
+ __.or(__.hasNot(AAIProperties.END_TS),
+ __.has(AAIProperties.END_TS, P.gt(startTs)))))
+ .vertexProperties(__.and(__.has(AAIProperties.START_TS, P.lte(startTs)),
+ __.or(__.hasNot(AAIProperties.END_TS),
+ __.has(AAIProperties.END_TS, P.gt(startTs)))))
+ .edges(__.and(__.has(AAIProperties.START_TS, P.lte(startTs)), __
+ .or(__.hasNot(AAIProperties.END_TS), __.has(AAIProperties.END_TS, P.gt(startTs)))))
+ .create();
}
private SubgraphStrategy getDataOwnerSubgraphStrategy(Set<String> roles) {
return SubgraphStrategy.build()
- .vertices(
- __.or(__.has("data-owner", P.within(roles)), __.hasNot("data-owner"))
- ).create();
+ .vertices(__.or(__.has("data-owner", P.within(roles)), __.hasNot("data-owner")))
+ .create();
}
- protected GraphTraversalSource getTraversalSource(TransactionalGraphEngine dbEngine, Format format, UriInfo info, Set<String> roles) throws AAIException {
+ protected GraphTraversalSource getTraversalSource(TransactionalGraphEngine dbEngine,
+ Format format, UriInfo info, Set<String> roles) throws AAIException {
GraphTraversalSource traversalSource;
if (isHistory(format)) {
long localStartTime = this.getStartTime(format, info.getQueryParameters());
long localEndTime = this.getEndTime(info.getQueryParameters());
- traversalSource = dbEngine.asAdmin().getTraversalSource().withStrategies(getSubgraphStrategy(localStartTime, localEndTime, format));
+ traversalSource = dbEngine.asAdmin().getTraversalSource()
+ .withStrategies(getSubgraphStrategy(localStartTime, localEndTime, format));
} else {
traversalSource = dbEngine.asAdmin().getTraversalSource();
@@ -185,13 +161,13 @@ public abstract class TraversalConsumer extends RESTAPI {
return Collections.EMPTY_SET;
}
- return account.getRoles()
- .stream()
- .map(role -> StringUtils.removeEnd(role, OwnerCheck.READ_ONLY_SUFFIX))
- .collect(Collectors.toSet());
+ return account.getRoles().stream()
+ .map(role -> StringUtils.removeEnd(role, OwnerCheck.READ_ONLY_SUFFIX))
+ .collect(Collectors.toSet());
}
- protected void validateHistoryParams(Format format, MultivaluedMap<String, String> params) throws AAIException {
+ protected void validateHistoryParams(Format format, MultivaluedMap<String, String> params)
+ throws AAIException {
getStartTime(format, params);
getEndTime(params);
}
@@ -199,31 +175,37 @@ public abstract class TraversalConsumer extends RESTAPI {
/**
* If a request comes in for information prior to our truncation timeframe, throw an error.
* In the changes api, we never return change timestamps prior to the truncation timeframe.
- * In the lifecycle api, we should treat a call with no timestamp as a lifecycle since call with a timestamp of the truncation time
- * in the lifecycle api, we should return an error if the timestamp provided is prior to the truncation time
- * In the state api, we should return an error if the timestamp provided is prior to the truncation time
+ * In the lifecycle api, we should treat a call with no timestamp as a lifecycle since call with
+ * a timestamp of the truncation time
+ * in the lifecycle api, we should return an error if the timestamp provided is prior to the
+ * truncation time
+ * In the state api, we should return an error if the timestamp provided is prior to the
+ * truncation time
+ *
* @param params
* @return
*/
- protected long getStartTime(Format format, MultivaluedMap<String, String> params) throws AAIException {
+ protected long getStartTime(Format format, MultivaluedMap<String, String> params)
+ throws AAIException {
if (startTime != null) {
return startTime;
}
- String startTs = params.getFirst("startTs") ;
+ String startTs = params.getFirst("startTs");
if (Format.state.equals(format)) {
- if (startTs == null || startTs.isEmpty() || "-1".equals(startTs) || "now".equals(startTs)) {
+ if (startTs == null || startTs.isEmpty() || "-1".equals(startTs)
+ || "now".equals(startTs)) {
startTime = currentTime;
} else {
startTime = Long.valueOf(startTs);
verifyTimeAgainstTruncationTime(startTime);
}
} else if (Format.lifecycle.equals(format)) {
- if("now".equals(startTs)) {
+ if ("now".equals(startTs)) {
startTime = currentTime;
- } else if (startTs == null || startTs.isEmpty()|| "-1".equals(startTs)) {
+ } else if (startTs == null || startTs.isEmpty() || "-1".equals(startTs)) {
startTime = getFurthestInThePast();
} else {
startTime = Long.valueOf(startTs);
@@ -246,7 +228,7 @@ public abstract class TraversalConsumer extends RESTAPI {
return endTime;
}
- String endTs = params.getFirst("endTs") ;
+ String endTs = params.getFirst("endTs");
if (endTs == null || endTs.isEmpty() || "-1".equals(endTs) || "now".equals(endTs)) {
endTime = currentTime;
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/AAIDslErrorListener.java b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/AAIDslErrorListener.java
index 26a625a..33629f0 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/AAIDslErrorListener.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/AAIDslErrorListener.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -27,8 +27,9 @@ import org.antlr.v4.runtime.misc.ParseCancellationException;
public class AAIDslErrorListener extends BaseErrorListener {
@Override
- public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line, int charPositionInLine, String msg, RecognitionException e)
- throws ParseCancellationException {
+ public void syntaxError(Recognizer<?, ?> recognizer, Object offendingSymbol, int line,
+ int charPositionInLine, String msg, RecognitionException e)
+ throws ParseCancellationException {
throw new ParseCancellationException("line " + line + ":" + charPositionInLine + " " + msg);
}
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/DslContext.java b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/DslContext.java
index cf7f51d..6088561 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/DslContext.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/DslContext.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,146 +19,146 @@
*/
package org.onap.aai.rest.dsl;
-import org.antlr.v4.runtime.ParserRuleContext;
-
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
+import org.antlr.v4.runtime.ParserRuleContext;
+
public class DslContext {
- private ParserRuleContext ctx;
-
- private boolean validationFlag = true;
- private boolean isStartNode = false;
- private String startNode = "";
- private List<String> startNodeKeys = new ArrayList<>();
-
- private String currentNode;
- private String previousNode;
-
- private boolean isTraversal = false;
- private boolean isWhereQuery = false;
- private boolean isUnionQuery = false;
- private boolean isUnionStart = false;
-
- private String whereStartNode = "";
-
- private Deque<String> unionStartNodes = new LinkedList<>();
-
- /*
- * Limit Queries have to be applied in the end - so i have to set this in
- * context
- */
- public StringBuilder limitQuery = new StringBuilder();
-
- public ParserRuleContext getCtx() {
- return ctx;
- }
-
- public void setCtx(ParserRuleContext ctx) {
- this.ctx = ctx;
- }
-
- public boolean isStartNode() {
- return isStartNode;
- }
-
- public void setStartNodeFlag(boolean isStartNode) {
- this.isStartNode = isStartNode;
- }
-
- public String getStartNode() {
- return startNode;
- }
-
- public void setStartNode(String startNode) {
- this.startNode = startNode;
- }
-
- public List<String> getStartNodeKeys() {
- return startNodeKeys;
- }
-
- public String getCurrentNode() {
- return currentNode;
- }
-
- public void setCurrentNode(String currentNode) {
- this.currentNode = currentNode;
- }
-
- public String getPreviousNode() {
- return previousNode;
- }
-
- public void setPreviousNode(String previousNode) {
- this.previousNode = previousNode;
- }
-
- public boolean isTraversal() {
- return isTraversal;
- }
-
- public void setTraversal(boolean isTraversal) {
- this.isTraversal = isTraversal;
- }
-
- public boolean isWhereQuery() {
- return isWhereQuery;
- }
-
- public void setWhereQuery(boolean isWhereQuery) {
- this.isWhereQuery = isWhereQuery;
- }
-
- public boolean isUnionQuery() {
- return isUnionQuery;
- }
-
- public void setUnionQuery(boolean isUnionQuery) {
- this.isUnionQuery = isUnionQuery;
- }
-
- public String getWhereStartNode() {
- return whereStartNode;
- }
-
- public void setWhereStartNode(String whereStartNode) {
- this.whereStartNode = whereStartNode;
- }
-
- public Deque<String> getUnionStartNodes() {
- return unionStartNodes;
- }
-
- public void setUnionStartNodes(Deque<String> unionStartNodes) {
- this.unionStartNodes = unionStartNodes;
- }
-
- public boolean isUnionStart() {
- return isUnionStart;
- }
-
- public void setUnionStart(boolean isUnionStart) {
- this.isUnionStart = isUnionStart;
- }
-
- public StringBuilder getLimitQuery() {
- return limitQuery;
- }
-
- public void setLimitQuery(StringBuilder limitQuery) {
- this.limitQuery = limitQuery;
- }
-
- public boolean isValidationFlag() {
- return validationFlag;
- }
-
- public void setValidationFlag(boolean validationFlag) {
- this.validationFlag = validationFlag;
- }
+ private ParserRuleContext ctx;
+
+ private boolean validationFlag = true;
+ private boolean isStartNode = false;
+ private String startNode = "";
+ private List<String> startNodeKeys = new ArrayList<>();
+
+ private String currentNode;
+ private String previousNode;
+
+ private boolean isTraversal = false;
+ private boolean isWhereQuery = false;
+ private boolean isUnionQuery = false;
+ private boolean isUnionStart = false;
+
+ private String whereStartNode = "";
+
+ private Deque<String> unionStartNodes = new LinkedList<>();
+
+ /*
+ * Limit Queries have to be applied in the end - so i have to set this in
+ * context
+ */
+ public StringBuilder limitQuery = new StringBuilder();
+
+ public ParserRuleContext getCtx() {
+ return ctx;
+ }
+
+ public void setCtx(ParserRuleContext ctx) {
+ this.ctx = ctx;
+ }
+
+ public boolean isStartNode() {
+ return isStartNode;
+ }
+
+ public void setStartNodeFlag(boolean isStartNode) {
+ this.isStartNode = isStartNode;
+ }
+
+ public String getStartNode() {
+ return startNode;
+ }
+
+ public void setStartNode(String startNode) {
+ this.startNode = startNode;
+ }
+
+ public List<String> getStartNodeKeys() {
+ return startNodeKeys;
+ }
+
+ public String getCurrentNode() {
+ return currentNode;
+ }
+
+ public void setCurrentNode(String currentNode) {
+ this.currentNode = currentNode;
+ }
+
+ public String getPreviousNode() {
+ return previousNode;
+ }
+
+ public void setPreviousNode(String previousNode) {
+ this.previousNode = previousNode;
+ }
+
+ public boolean isTraversal() {
+ return isTraversal;
+ }
+
+ public void setTraversal(boolean isTraversal) {
+ this.isTraversal = isTraversal;
+ }
+
+ public boolean isWhereQuery() {
+ return isWhereQuery;
+ }
+
+ public void setWhereQuery(boolean isWhereQuery) {
+ this.isWhereQuery = isWhereQuery;
+ }
+
+ public boolean isUnionQuery() {
+ return isUnionQuery;
+ }
+
+ public void setUnionQuery(boolean isUnionQuery) {
+ this.isUnionQuery = isUnionQuery;
+ }
+
+ public String getWhereStartNode() {
+ return whereStartNode;
+ }
+
+ public void setWhereStartNode(String whereStartNode) {
+ this.whereStartNode = whereStartNode;
+ }
+
+ public Deque<String> getUnionStartNodes() {
+ return unionStartNodes;
+ }
+
+ public void setUnionStartNodes(Deque<String> unionStartNodes) {
+ this.unionStartNodes = unionStartNodes;
+ }
+
+ public boolean isUnionStart() {
+ return isUnionStart;
+ }
+
+ public void setUnionStart(boolean isUnionStart) {
+ this.isUnionStart = isUnionStart;
+ }
+
+ public StringBuilder getLimitQuery() {
+ return limitQuery;
+ }
+
+ public void setLimitQuery(StringBuilder limitQuery) {
+ this.limitQuery = limitQuery;
+ }
+
+ public boolean isValidationFlag() {
+ return validationFlag;
+ }
+
+ public void setValidationFlag(boolean validationFlag) {
+ this.validationFlag = validationFlag;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/DslQueryBuilder.java b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/DslQueryBuilder.java
index d5b365e..a953fcb 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/DslQueryBuilder.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/DslQueryBuilder.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -21,6 +21,13 @@ package org.onap.aai.rest.dsl;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
+
+import java.util.List;
+import java.util.Optional;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+import java.util.stream.Collectors;
+
import org.onap.aai.edges.EdgeIngestor;
import org.onap.aai.edges.EdgeRule;
import org.onap.aai.edges.EdgeRuleQuery;
@@ -35,12 +42,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
-import java.util.List;
-import java.util.Optional;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
-import java.util.stream.Collectors;
-
public class DslQueryBuilder {
private final EdgeIngestor edgeRules;
@@ -84,7 +85,7 @@ public class DslQueryBuilder {
*/
public DslQueryBuilder end(long selectCounter) {
selectCount = selectCounter;
- if(selectCounter <= 0) {
+ if (selectCounter <= 0) {
return this.end();
} else {
query.append(".select('stepMain').fold().dedup()");
@@ -108,26 +109,28 @@ public class DslQueryBuilder {
}
public DslQueryBuilder edgeQuery(Edge edge, String aNode, String bNode) {
- List<String> edgeLabels = edge.getLabels().stream().map(edgeLabel -> StringUtils.quote(edgeLabel.getLabel())).collect(Collectors.toList());
+ List<String> edgeLabels = edge.getLabels().stream()
+ .map(edgeLabel -> StringUtils.quote(edgeLabel.getLabel())).collect(Collectors.toList());
EdgeRuleQuery.Builder baseQ = new EdgeRuleQuery.Builder(aNode, bNode);
- if((AAIDirection.valueOf(edge.getDirection().name())) != AAIDirection.BOTH) {
- baseQ = baseQ.direction(AAIDirection.valueOf(edge.getDirection().name()));
+ if ((AAIDirection.valueOf(edge.getDirection().name())) != AAIDirection.BOTH) {
+ baseQ = baseQ.direction(AAIDirection.valueOf(edge.getDirection().name()));
}
return edgeQueryWithBuilder(edgeLabels, aNode, bNode, baseQ);
}
- private DslQueryBuilder edgeQueryWithBuilder(List<String> edgeLabels, String aNode, String bNode, EdgeRuleQuery.Builder edgeBuilder) {
- //TODO : change this for fuzzy search.
+ private DslQueryBuilder edgeQueryWithBuilder(List<String> edgeLabels, String aNode,
+ String bNode, EdgeRuleQuery.Builder edgeBuilder) {
+ // TODO : change this for fuzzy search.
String edgeType = "";
String edgeLabelsClause = "";
String edgeTraversalClause = ".createEdgeTraversal(";
-
if (!edgeLabels.isEmpty()) {
edgeTraversalClause = ".createEdgeTraversalWithLabels(";
- edgeLabelsClause = String.join("", ", new ArrayList<>(Arrays.asList(", String.join(",", edgeLabels), "))");
+ edgeLabelsClause = String.join("", ", new ArrayList<>(Arrays.asList(",
+ String.join(",", edgeLabels), "))");
}
LOGGER.debug("EdgeLabels Clause: {}", edgeLabelsClause);
@@ -140,23 +143,27 @@ public class DslQueryBuilder {
try {
rules.putAll(edgeRules.getRules(edgeBuilder.label(label).build()));
} catch (EdgeRuleNotFoundException e) {
- queryException.append("Exception while finding the edge rule between the nodeTypes: ").append(aNode).append(", ").append(bNode).append(label);
+ queryException
+ .append("Exception while finding the edge rule between the nodeTypes: ")
+ .append(aNode).append(", ").append(bNode).append(label);
}
});
}
} catch (EdgeRuleNotFoundException e) {
if (!edgeLabels.isEmpty()) {
- queryException.append("- No EdgeRule found for passed nodeTypes: ").append(aNode).append(", ").append(bNode).append(edgeLabels.stream().toString());
- }
- else {
- queryException.append("- No EdgeRule found for passed nodeTypes: ").append(aNode).append(", ").append(bNode);
+ queryException.append("- No EdgeRule found for passed nodeTypes: ").append(aNode)
+ .append(", ").append(bNode).append(edgeLabels.stream().toString());
+ } else {
+ queryException.append("- No EdgeRule found for passed nodeTypes: ").append(aNode)
+ .append(", ").append(bNode);
}
return this;
}
if (rules.isEmpty() || rules.keys().isEmpty()) {
- queryException.append("- No EdgeRule found for passed nodeTypes: ").append(aNode).append(", ").append(bNode);
+ queryException.append("- No EdgeRule found for passed nodeTypes: ").append(aNode)
+ .append(", ").append(bNode);
} else {
if (edgeLabels.isEmpty()) {
if (edgeRules.hasRule(edgeBuilder.edgeType(EdgeType.TREE).build())) {
@@ -172,16 +179,15 @@ public class DslQueryBuilder {
}
}
- query.append(edgeTraversalClause).append(edgeType).append(" '").append(aNode)
- .append("','").append(bNode).append("'").append(edgeLabelsClause).append(")");
+ query.append(edgeTraversalClause).append(edgeType).append(" '").append(aNode).append("','")
+ .append(bNode).append("'").append(edgeLabelsClause).append(")");
return this;
}
-
public DslQueryBuilder where(boolean isNot) {
query.append(".where(");
- if(isNot){
+ if (isNot) {
query.append("builder.newInstance().not(");
}
return this;
@@ -189,7 +195,7 @@ public class DslQueryBuilder {
public DslQueryBuilder endWhere(boolean isNot) {
query.append(")");
- if(isNot){
+ if (isNot) {
query.append(")");
}
return this;
@@ -201,13 +207,14 @@ public class DslQueryBuilder {
}
public DslQueryBuilder filter(boolean isNot, String node, String key, List<String> values) {
- return this.filterPropertyStart(isNot,values).filterPropertyKeys(node, key, values).filterPropertyEnd();
+ return this.filterPropertyStart(isNot, values).filterPropertyKeys(node, key, values)
+ .filterPropertyEnd();
}
public DslQueryBuilder filterPropertyStart(boolean isNot, List<String> values) {
if (isNot) {
query.append(".getVerticesExcludeByProperty(");
- } else if(values!= null && !values.isEmpty() && Boolean.parseBoolean(values.get(0))) {
+ } else if (values != null && !values.isEmpty() && Boolean.parseBoolean(values.get(0))) {
query.append(".getVerticesByBooleanProperty(");
} else {
query.append(".getVerticesByProperty(");
@@ -225,10 +232,8 @@ public class DslQueryBuilder {
Introspector obj = loader.introspectorFromName(node);
if (keys.isEmpty()) {
- queryException.append("No keys sent. Valid keys for ")
- .append(node)
- .append(" are ")
- .append(String.join(",", obj.getIndexedProperties()));
+ queryException.append("No keys sent. Valid keys for ").append(node).append(" are ")
+ .append(String.join(",", obj.getIndexedProperties()));
return this;
}
@@ -241,21 +246,22 @@ public class DslQueryBuilder {
public DslQueryBuilder select(long selectCounter, List<String> keys) {
/*
- * TODO : isNot should look at the vertex properties and include everything except the notKeys
+ * TODO : isNot should look at the vertex properties and include everything except the
+ * notKeys
*/
Pattern p = Pattern.compile("aai-node-type");
Matcher m = p.matcher(query);
int count = 0;
- while (m.find()){
+ while (m.find()) {
count++;
}
if (selectCounter == count || keys == null) {
String selectStep = "step" + selectCounter;
-// String keysArray = String.join(",", keys);
- query.append(".as('").append(selectStep).append("')")
- .append(".as('stepMain').select('").append(selectStep).append("')");
+ // String keysArray = String.join(",", keys);
+ query.append(".as('").append(selectStep).append("')").append(".as('stepMain').select('")
+ .append(selectStep).append("')");
}
return this;
}
@@ -263,7 +269,8 @@ public class DslQueryBuilder {
public DslQueryBuilder filterPropertyKeys(String node, String key, List<String> values) {
try {
Introspector obj = loader.introspectorFromName(node);
- Optional<String> alias = obj.getPropertyMetadata(key.replace("'",""), PropertyMetadata.DB_ALIAS);
+ Optional<String> alias =
+ obj.getPropertyMetadata(key.replace("'", ""), PropertyMetadata.DB_ALIAS);
if (alias.isPresent()) {
key = StringUtils.quote(alias.get());
}
@@ -271,14 +278,15 @@ public class DslQueryBuilder {
query.append(key);
if (values != null && !values.isEmpty()) {
- if (values.size() > 1) { // values.size() > 1 indicates possibility of a list
+ if (values.size() > 1) { // values.size() > 1 indicates possibility of a list
// eliminate quotes from each element
for (int i = 0; i < values.size(); i++) {
values.set(i, getConvertedValue(classType, key, values.get(i)));
}
String valuesArray = String.join(",", values);
- query.append(",").append(" new ArrayList<>(Arrays.asList(").append(valuesArray).append("))");
- } else { // otherwise values should only contain one value
+ query.append(",").append(" new ArrayList<>(Arrays.asList(").append(valuesArray)
+ .append("))");
+ } else { // otherwise values should only contain one value
query.append(",").append(getConvertedValue(classType, key, values.get(0)));
}
}
@@ -297,30 +305,29 @@ public class DslQueryBuilder {
if (classType.equals(Integer.class.getName())) {
int castInt = Integer.parseInt(convertedValue);
convertedValue = String.valueOf(castInt);
- }
- else if (classType.equals(Long.class.getName())) {
+ } else if (classType.equals(Long.class.getName())) {
long castLong = Long.parseLong(convertedValue);
convertedValue = String.valueOf(castLong);
- }
- else if (classType.equals(Boolean.class.getName())) {
- if ("1".equals(convertedValue)) { // checking for integer true value
+ } else if (classType.equals(Boolean.class.getName())) {
+ if ("1".equals(convertedValue)) { // checking for integer true value
convertedValue = "true";
}
boolean castBoolean = Boolean.parseBoolean(convertedValue);
convertedValue = String.valueOf(castBoolean);
}
} catch (Exception e) {
- queryException.append("AAI_4020 ").append(String.format("Value [%s] is not an instance of the expected data type for property key [%s] and cannot be converted. " +
- "Expected: class %s, found: class %s", value, key, classType, String.class.getName()));
+ queryException.append("AAI_4020 ").append(String.format(
+ "Value [%s] is not an instance of the expected data type for property key [%s] and cannot be converted. "
+ + "Expected: class %s, found: class %s",
+ value, key, classType, String.class.getName()));
}
}
return convertedValue;
}
private boolean isTypeSensitive(String classType) {
- if (classType.equals(Integer.class.getName()) ||
- classType.equals(Boolean.class.getName()) ||
- classType.equals(Long.class.getName())) {
+ if (classType.equals(Integer.class.getName()) || classType.equals(Boolean.class.getName())
+ || classType.equals(Long.class.getName())) {
return true;
}
return false;
@@ -368,5 +375,4 @@ public class DslQueryBuilder {
return this;
}
-
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/DslQueryProcessor.java b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/DslQueryProcessor.java
index 14663e1..a21ca04 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/DslQueryProcessor.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/DslQueryProcessor.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,15 @@
*/
package org.onap.aai.rest.dsl;
+import java.io.ByteArrayInputStream;
+import java.io.InputStream;
+import java.io.InputStreamReader;
+import java.lang.reflect.InvocationTargetException;
+import java.nio.charset.StandardCharsets;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
import org.antlr.v4.runtime.*;
import org.antlr.v4.runtime.misc.ParseCancellationException;
import org.antlr.v4.runtime.tree.ParseTree;
@@ -32,138 +41,144 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import java.io.ByteArrayInputStream;
-import java.io.InputStream;
-import java.io.InputStreamReader;
-import java.lang.reflect.InvocationTargetException;
-import java.nio.charset.StandardCharsets;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
/**
* The Class DslQueryProcessor.
*/
public class DslQueryProcessor {
- private static final Logger LOGGER = LoggerFactory.getLogger(DslQueryProcessor.class);
-
- private Map<QueryVersion, ParseTreeListener> dslListeners;
- private boolean startNodeValidationFlag = true;
- private String validationRules = "";
- private String packageName = "org.onap.aai.dsl.";
- private static final String LEXER = "AAIDslLexer";
- private static final String PARSER = "AAIDslParser";
- private static final String EOF_TOKEN = "<EOF>";
-
- private boolean isAggregate = false;
-
- @Autowired
- public DslQueryProcessor(Map<QueryVersion, ParseTreeListener> dslListeners) {
- this.dslListeners = dslListeners;
- }
-
- public Map<String, Object> parseAaiQuery(QueryVersion version, String aaiQuery) throws AAIException {
- Map<String, Object> resultMap = new HashMap<>();
- try {
- // Create a input stream that reads our string
- InputStream stream = new ByteArrayInputStream(aaiQuery.getBytes(StandardCharsets.UTF_8));
-
- packageName = packageName + version.toString().toLowerCase() + ".";
-
- Class<?> lexerClass = Class.forName(packageName + LEXER);
- Class<?> parserClass = Class.forName(packageName + PARSER);
-
- Lexer lexer = (Lexer)lexerClass.getConstructor(CharStream.class).newInstance(CharStreams.fromStream(stream, StandardCharsets.UTF_8));
- lexer.removeErrorListeners();
- lexer.addErrorListener(new AAIDslErrorListener());
- CommonTokenStream tokens = new CommonTokenStream(lexer);
-
- // Parser that feeds off of the tokens buffer
- Parser parser = (Parser)parserClass.getConstructor(TokenStream.class).newInstance(tokens);
- parser.removeErrorListeners();
- parser.addErrorListener(new AAIDslErrorListener());
- ParseTreeListener dslListener = dslListeners.get(version);
- dslListener.getClass().getMethod("setValidationFlag", boolean.class).invoke(dslListener, isStartNodeValidationFlag());
- dslListener.getClass().getMethod("setAggregateFlag", boolean.class).invoke(dslListener,isAggregate());
-
- if(!getValidationRules().isEmpty() && !"none".equals(getValidationRules())) {
- DslValidator validator = new DslValidator.Builder()
- .create();
- dslListener.getClass().getMethod("setQueryValidator", DslValidator.class, String.class).invoke(dslListener, validator, getValidationRules());
- }
-
- // Specify our entry point
- ParseTree ptree = (ParseTree)parserClass.getMethod("aaiquery").invoke(parser);
-
- // Check if there is no EOF token at the end of the parsed aaiQuery
- // If none, DSL query may have not been parsed correctly and omitted part of the query out. If so error out.
- // If it wasn't expecting a opening parens after a closing bracket for union, it will drop the proceeding part of the query.
- Token eofToken = tokens.get(tokens.size() - 1);
+ private static final Logger LOGGER = LoggerFactory.getLogger(DslQueryProcessor.class);
+
+ private Map<QueryVersion, ParseTreeListener> dslListeners;
+ private boolean startNodeValidationFlag = true;
+ private String validationRules = "";
+ private String packageName = "org.onap.aai.dsl.";
+ private static final String LEXER = "AAIDslLexer";
+ private static final String PARSER = "AAIDslParser";
+ private static final String EOF_TOKEN = "<EOF>";
+
+ private boolean isAggregate = false;
+
+ @Autowired
+ public DslQueryProcessor(Map<QueryVersion, ParseTreeListener> dslListeners) {
+ this.dslListeners = dslListeners;
+ }
+
+ public Map<String, Object> parseAaiQuery(QueryVersion version, String aaiQuery)
+ throws AAIException {
+ Map<String, Object> resultMap = new HashMap<>();
+ try {
+ // Create a input stream that reads our string
+ InputStream stream =
+ new ByteArrayInputStream(aaiQuery.getBytes(StandardCharsets.UTF_8));
+
+ packageName = packageName + version.toString().toLowerCase() + ".";
+
+ Class<?> lexerClass = Class.forName(packageName + LEXER);
+ Class<?> parserClass = Class.forName(packageName + PARSER);
+
+ Lexer lexer = (Lexer) lexerClass.getConstructor(CharStream.class)
+ .newInstance(CharStreams.fromStream(stream, StandardCharsets.UTF_8));
+ lexer.removeErrorListeners();
+ lexer.addErrorListener(new AAIDslErrorListener());
+ CommonTokenStream tokens = new CommonTokenStream(lexer);
+
+ // Parser that feeds off of the tokens buffer
+ Parser parser =
+ (Parser) parserClass.getConstructor(TokenStream.class).newInstance(tokens);
+ parser.removeErrorListeners();
+ parser.addErrorListener(new AAIDslErrorListener());
+ ParseTreeListener dslListener = dslListeners.get(version);
+ dslListener.getClass().getMethod("setValidationFlag", boolean.class).invoke(dslListener,
+ isStartNodeValidationFlag());
+ dslListener.getClass().getMethod("setAggregateFlag", boolean.class).invoke(dslListener,
+ isAggregate());
+
+ if (!getValidationRules().isEmpty() && !"none".equals(getValidationRules())) {
+ DslValidator validator = new DslValidator.Builder().create();
+ dslListener.getClass()
+ .getMethod("setQueryValidator", DslValidator.class, String.class)
+ .invoke(dslListener, validator, getValidationRules());
+ }
+
+ // Specify our entry point
+ ParseTree ptree = (ParseTree) parserClass.getMethod("aaiquery").invoke(parser);
+
+ // Check if there is no EOF token at the end of the parsed aaiQuery
+ // If none, DSL query may have not been parsed correctly and omitted part of the query
+ // out. If so error out.
+ // If it wasn't expecting a opening parens after a closing bracket for union, it will
+ // drop the proceeding part of the query.
+ Token eofToken = tokens.get(tokens.size() - 1);
if (eofToken != null && !eofToken.getText().equals(EOF_TOKEN)) {
- if (eofToken.getText().equals("(")) {
- throw new AAIException("AAI_6153", "DSL Syntax Error while processing the query: DSL Query could not be parsed correctly. Please check your syntax.");
- }
- }
-
- if (LOGGER.isInfoEnabled()) {
- LOGGER.info("QUERY-interim {}", ptree.toStringTree(parser));
- }
-
- // Walk it and attach our listener
- ParseTreeWalker walker = new ParseTreeWalker();
-
- walker.walk(dslListener, ptree);
- String query = (String) dslListener.getClass().getMethod("getQuery").invoke(dslListener);
- resultMap.put("query", query);
- if (version.equals(QueryVersion.V2)){
- Map<String, List<String>> selectKeys= ((DslListener)dslListener).getSelectKeys();
- if (selectKeys != null && !selectKeys.isEmpty()){
- resultMap.put("propertiesMap", selectKeys);
- }
- }
- LOGGER.info("Final QUERY {}", query);
- return resultMap;
- }catch(InvocationTargetException e){
- if (e.getTargetException() instanceof ParseCancellationException) {
- throw new AAIException("AAI_6153", "DSL Syntax Error while processing the query :" + e.getTargetException().getMessage());
- } else if (e.getTargetException() instanceof AAIException) {
- AAIException ex = (AAIException)e.getTargetException();
- throw new AAIException((ex.getCode().isEmpty() ? "AAI_6149":ex.getCode()), "DSL Error while processing the query :" + ex.getMessage());
- } else {
- throw new AAIException("AAI_6152","Exception while processing DSL query");
- }
-
- } catch(ParseCancellationException e) {
- throw new AAIException("AAI_6153", "DSL Syntax Error while processing the query: " + e.getMessage());
-
- } catch (Exception e) {
- throw new AAIException("AAI_6152","Error while processing the query: " + e.getMessage());
-
- }
- }
-
- public boolean isStartNodeValidationFlag() {
- return startNodeValidationFlag;
- }
-
- public void setStartNodeValidationFlag(boolean startNodeValidationFlag) {
- this.startNodeValidationFlag = startNodeValidationFlag;
- }
-
- public boolean isAggregate() {
- return isAggregate;
- }
-
- public void setAggregate(boolean aggregate) {
- this.isAggregate = aggregate;
- }
-
- public String getValidationRules() {
- return validationRules;
- }
-
- public void setValidationRules(String validationRules) {
- this.validationRules = validationRules;
- }
+ if (eofToken.getText().equals("(")) {
+ throw new AAIException("AAI_6153",
+ "DSL Syntax Error while processing the query: DSL Query could not be parsed correctly. Please check your syntax.");
+ }
+ }
+
+ if (LOGGER.isInfoEnabled()) {
+ LOGGER.info("QUERY-interim {}", ptree.toStringTree(parser));
+ }
+
+ // Walk it and attach our listener
+ ParseTreeWalker walker = new ParseTreeWalker();
+
+ walker.walk(dslListener, ptree);
+ String query =
+ (String) dslListener.getClass().getMethod("getQuery").invoke(dslListener);
+ resultMap.put("query", query);
+ if (version.equals(QueryVersion.V2)) {
+ Map<String, List<String>> selectKeys = ((DslListener) dslListener).getSelectKeys();
+ if (selectKeys != null && !selectKeys.isEmpty()) {
+ resultMap.put("propertiesMap", selectKeys);
+ }
+ }
+ LOGGER.info("Final QUERY {}", query);
+ return resultMap;
+ } catch (InvocationTargetException e) {
+ if (e.getTargetException() instanceof ParseCancellationException) {
+ throw new AAIException("AAI_6153", "DSL Syntax Error while processing the query :"
+ + e.getTargetException().getMessage());
+ } else if (e.getTargetException() instanceof AAIException) {
+ AAIException ex = (AAIException) e.getTargetException();
+ throw new AAIException((ex.getCode().isEmpty() ? "AAI_6149" : ex.getCode()),
+ "DSL Error while processing the query :" + ex.getMessage());
+ } else {
+ throw new AAIException("AAI_6152", "Exception while processing DSL query");
+ }
+
+ } catch (ParseCancellationException e) {
+ throw new AAIException("AAI_6153",
+ "DSL Syntax Error while processing the query: " + e.getMessage());
+
+ } catch (Exception e) {
+ throw new AAIException("AAI_6152",
+ "Error while processing the query: " + e.getMessage());
+
+ }
+ }
+
+ public boolean isStartNodeValidationFlag() {
+ return startNodeValidationFlag;
+ }
+
+ public void setStartNodeValidationFlag(boolean startNodeValidationFlag) {
+ this.startNodeValidationFlag = startNodeValidationFlag;
+ }
+
+ public boolean isAggregate() {
+ return isAggregate;
+ }
+
+ public void setAggregate(boolean aggregate) {
+ this.isAggregate = aggregate;
+ }
+
+ public String getValidationRules() {
+ return validationRules;
+ }
+
+ public void setValidationRules(String validationRules) {
+ this.validationRules = validationRules;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/Edge.java b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/Edge.java
index c3be5dc..111c188 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/Edge.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/Edge.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,17 +19,17 @@
*/
package org.onap.aai.rest.dsl;
-import org.onap.aai.rest.enums.EdgeDirection;
-
import java.util.List;
import java.util.stream.Collectors;
+import org.onap.aai.rest.enums.EdgeDirection;
+
public class Edge {
private List<EdgeLabel> labels;
private EdgeDirection direction;
- public Edge (EdgeDirection direction, List<EdgeLabel> labels) {
+ public Edge(EdgeDirection direction, List<EdgeLabel> labels) {
this.labels = labels;
this.direction = direction;
}
@@ -53,7 +53,7 @@ public class Edge {
@Override
public String toString() {
return String.format("labels: %s, direction: %s ",
- labels.stream().map(EdgeLabel::getLabel).collect(Collectors.joining(",")),
- this.getDirection().name());
+ labels.stream().map(EdgeLabel::getLabel).collect(Collectors.joining(",")),
+ this.getDirection().name());
}
-} \ No newline at end of file
+}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/EdgeLabel.java b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/EdgeLabel.java
index 703adaf..6acf758 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/EdgeLabel.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/EdgeLabel.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -24,7 +24,7 @@ public class EdgeLabel {
private String label;
private boolean isExactMatch;
- public EdgeLabel (String label, boolean isExactMatch) {
+ public EdgeLabel(String label, boolean isExactMatch) {
this.isExactMatch = isExactMatch;
this.label = label;
}
@@ -45,4 +45,4 @@ public class EdgeLabel {
this.isExactMatch = isExactMatch;
}
-} \ No newline at end of file
+}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/v1/DslListener.java b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/v1/DslListener.java
index 4bb093e..ad2899c 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/v1/DslListener.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/v1/DslListener.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -20,6 +20,11 @@
package org.onap.aai.rest.dsl.v1;
import com.google.common.collect.Lists;
+
+import java.util.*;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
import org.onap.aai.dsl.v1.AAIDslBaseListener;
import org.onap.aai.dsl.v1.AAIDslParser;
import org.onap.aai.edges.EdgeIngestor;
@@ -36,271 +41,274 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.*;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
/**
* The Class DslListener.
*/
public class DslListener extends AAIDslBaseListener {
- private static final Logger LOGGER = LoggerFactory.getLogger(DslListener.class);
-
- private boolean validationFlag = false;
- private EdgeIngestor edgeIngestor;
- private Loader loader;
- private Optional<DslValidator> queryValidator = Optional.empty();
- private boolean hasReturnValue = false;
-
- private String validationRules = "none";
-
- private Deque<DslQueryBuilder> dslQueryBuilders = new LinkedList<>();
- private Deque<String> traversedNodes = new LinkedList<>();
- private Deque<List<String>> returnedNodes = new LinkedList<>();
-
- private List<String> traversedEdgeLabels = new LinkedList<>();
-
- private boolean isAggregate = false;
-
- /*
- * Additional datastructures to store all nodeCount & looped edges
- */
- private int nodeCount = 0;
- private List<String> traversedEdges = new LinkedList<>();
-
- /**
- * Instantiates a new DslListener.
- */
- @Autowired
- public DslListener(EdgeIngestor edgeIngestor, SchemaVersions schemaVersions, LoaderFactory loaderFactory) {
- this.loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
- this.edgeIngestor = edgeIngestor;
- }
-
- public DslQueryBuilder builder() {
- return dslQueryBuilders.peekFirst();
- }
-
- public String getQuery() throws AAIException {
- if (!getException().isEmpty()) {
- AAIException aaiException = new AAIException("AAI_6149", getException());
- ErrorLogHelper.logException(aaiException);
- throw aaiException;
- }
-
- DslValidatorRule ruleValidator = new DslValidatorRule.Builder()
- .loop(getValidationRules() , traversedEdges)
- .nodeCount(getValidationRules(), nodeCount).build();
- if(queryValidator.isPresent() && !queryValidator.get().validate(ruleValidator)){
- AAIException aaiException = new AAIException("AAI_6151", "Validation error " + queryValidator.get().getErrorMessage() );
- ErrorLogHelper.logException(aaiException);
- throw aaiException;
- }
- return this.compile();
- }
-
- public String compile() {
- List<String> queries = dslQueryBuilders.stream().map(dslQb -> dslQb.getQuery().toString()).collect(Collectors.toList());
- return String.join("", Lists.reverse(queries));
- }
-
- public String getException() {
- List<String> exceptions = dslQueryBuilders.stream().map(dslQb -> dslQb.getQueryException().toString()).collect(Collectors.toList());
- return String.join("", Lists.reverse(exceptions));
- }
-
- @Override
- public void enterAaiquery(AAIDslParser.AaiqueryContext ctx) {
- dslQueryBuilders.push(new DslQueryBuilder(edgeIngestor, loader));
- }
-
- @Override
- public void exitAaiquery(AAIDslParser.AaiqueryContext ctx) {
- if (!hasReturnValue) {
- throw new RuntimeException(new AAIException("AAI_6149", "No nodes marked for output"));
- }
- }
-
- @Override
- public void enterStartStatement(AAIDslParser.StartStatementContext ctx) {
- builder().start();
- }
-
- @Override
- public void exitStartStatement(AAIDslParser.StartStatementContext ctx) {
- builder().end();
- if (!traversedNodes.isEmpty()) {
- traversedNodes.removeFirst();
- }
-
- }
-
- @Override
- public void exitLimit(AAIDslParser.LimitContext ctx) {
- builder().limit(ctx.num().getText());
- }
-
- @Override
- public void enterNestedStatement(AAIDslParser.NestedStatementContext ctx) {
- dslQueryBuilders.addFirst(new DslQueryBuilder(edgeIngestor, loader));
- builder().startInstance();
- }
-
- @Override
- public void exitNestedStatement(AAIDslParser.NestedStatementContext ctx) {
- int count = 1;
- if(!ctx.traversal().isEmpty()) {
- count += ctx.traversal().size() ;
- }
- String resultNode = traversedNodes.peekFirst();
-
- if (!traversedNodes.isEmpty()) {
- Stream<Integer> integers = Stream.iterate(0, i -> i + 1);
- integers.limit(count)
- .forEach(i -> traversedNodes.removeFirst());
- }
- List<String> resultNodes = returnedNodes.pop();
- resultNodes.add(resultNode);
- returnedNodes.addFirst(resultNodes);
- }
-
- @Override
- public void enterComma(AAIDslParser.CommaContext ctx) {
- builder().comma();
- }
-
- @Override
- public void enterVertex(AAIDslParser.VertexContext ctx) {
-
- if (!traversedNodes.isEmpty()) {
- builder().edgeQuery(traversedEdgeLabels, traversedNodes.peekFirst(), ctx.label().getText());
- traversedEdges.add(traversedNodes.peekFirst() + ctx.label().getText());
- } else {
- builder().nodeQuery(ctx.label().getText());
- }
-
- traversedNodes.addFirst(ctx.label().getText());
- }
-
- @Override
- public void exitVertex(AAIDslParser.VertexContext ctx) {
-
- /*TODO dont use context */
- if (ctx.getParent() instanceof AAIDslParser.StartStatementContext && isValidationFlag()) {
- List<String> allKeys = new ArrayList<>();
-
- if (ctx.filter() != null) {
- allKeys = ctx.filter().propertyFilter().stream().flatMap(
- pf -> pf.key().stream()).map(
- e -> e.getText().replaceFirst("\'", "").substring(0, e.getText().length() - 2)).collect(Collectors.toList());
-
- }
- builder().validateFilter(ctx.label().getText(), allKeys);
- }
- if (ctx.store() != null) {
- builder().store();
- hasReturnValue = true;
- }
- traversedEdgeLabels = new ArrayList<>();
- nodeCount++;
- }
-
-
- @Override
- public void enterUnionVertex(AAIDslParser.UnionVertexContext ctx) {
- returnedNodes.addFirst(new ArrayList<>());
- builder().union();
- }
-
- @Override
- public void exitUnionVertex(AAIDslParser.UnionVertexContext ctx) {
- String resultNode = returnedNodes.pop().get(0);
- traversedNodes.addFirst(resultNode);
- builder().endUnion();
- if (ctx.store() != null) {
- builder().store();
- hasReturnValue = true;
- }
- }
-
- @Override
- public void enterWhereFilter(AAIDslParser.WhereFilterContext ctx) {
- boolean isNot = ctx.not() != null && !ctx.not().isEmpty();
- returnedNodes.addFirst(new ArrayList<>());
- builder().where(isNot);
- }
-
- @Override
- public void exitWhereFilter(AAIDslParser.WhereFilterContext ctx) {
- if(!returnedNodes.isEmpty()) {
- returnedNodes.pop();
- }
- boolean isNot = ctx.not() != null && !ctx.not().isEmpty();
- builder().endWhere(isNot);
- }
-
- @Override
- public void enterEdgeFilter(AAIDslParser.EdgeFilterContext ctx) {
- traversedEdgeLabels = ctx.key().stream().map(value -> value.getText()).collect(Collectors.toList());
-
- }
-
- @Override
- public void enterPropertyFilter(AAIDslParser.PropertyFilterContext ctx) {
-
- List<AAIDslParser.KeyContext> valueList = ctx.key();
- String filterKey = valueList.get(0).getText();
-
- boolean isNot = ctx.not() != null && !ctx.not().isEmpty();
- List<AAIDslParser.NumContext> numberValues = ctx.num();
-
- List<AAIDslParser.BoolContext> booleanValues = ctx.bool();
-
- /*
- * Add all String values
- */
- List<String> values = valueList.stream().filter(value -> !filterKey.equals(value.getText()))
- .map(value -> value.getText()).collect(Collectors.toList());
-
- /*
- * Add all numeric values
- */
- values.addAll(numberValues.stream().filter(value -> !filterKey.equals(value.getText()))
- .map(value -> value.getText()).collect(Collectors.toList()));
-
- /*
- * Add all boolean values
- */
- values.addAll(booleanValues.stream().filter(value -> !filterKey.equals(value.getText()))
- .map(value -> value.getText().toLowerCase()).collect(Collectors.toList()));
-
- builder().filter(isNot, traversedNodes.peekFirst(), filterKey, values);
-
- }
-
- public boolean isValidationFlag() {
- return validationFlag;
- }
-
- public void setValidationFlag(boolean validationFlag) {
- this.validationFlag = validationFlag;
- }
-
- public void setQueryValidator(DslValidator queryValidator, String validationRules) {
- this.queryValidator = Optional.of(queryValidator);
- this.validationRules = validationRules;
- }
- public String getValidationRules() {
- return validationRules;
- }
-
- public void setAggregateFlag(boolean isAggregate) {
- this.isAggregate = isAggregate;
- }
-
- public boolean isAggregate(){
- return this.isAggregate;
- }
+ private static final Logger LOGGER = LoggerFactory.getLogger(DslListener.class);
+
+ private boolean validationFlag = false;
+ private EdgeIngestor edgeIngestor;
+ private Loader loader;
+ private Optional<DslValidator> queryValidator = Optional.empty();
+ private boolean hasReturnValue = false;
+
+ private String validationRules = "none";
+
+ private Deque<DslQueryBuilder> dslQueryBuilders = new LinkedList<>();
+ private Deque<String> traversedNodes = new LinkedList<>();
+ private Deque<List<String>> returnedNodes = new LinkedList<>();
+
+ private List<String> traversedEdgeLabels = new LinkedList<>();
+
+ private boolean isAggregate = false;
+
+ /*
+ * Additional datastructures to store all nodeCount & looped edges
+ */
+ private int nodeCount = 0;
+ private List<String> traversedEdges = new LinkedList<>();
+
+ /**
+ * Instantiates a new DslListener.
+ */
+ @Autowired
+ public DslListener(EdgeIngestor edgeIngestor, SchemaVersions schemaVersions,
+ LoaderFactory loaderFactory) {
+ this.loader = loaderFactory.createLoaderForVersion(ModelType.MOXY,
+ schemaVersions.getDefaultVersion());
+ this.edgeIngestor = edgeIngestor;
+ }
+
+ public DslQueryBuilder builder() {
+ return dslQueryBuilders.peekFirst();
+ }
+
+ public String getQuery() throws AAIException {
+ if (!getException().isEmpty()) {
+ AAIException aaiException = new AAIException("AAI_6149", getException());
+ ErrorLogHelper.logException(aaiException);
+ throw aaiException;
+ }
+
+ DslValidatorRule ruleValidator =
+ new DslValidatorRule.Builder().loop(getValidationRules(), traversedEdges)
+ .nodeCount(getValidationRules(), nodeCount).build();
+ if (queryValidator.isPresent() && !queryValidator.get().validate(ruleValidator)) {
+ AAIException aaiException = new AAIException("AAI_6151",
+ "Validation error " + queryValidator.get().getErrorMessage());
+ ErrorLogHelper.logException(aaiException);
+ throw aaiException;
+ }
+ return this.compile();
+ }
+
+ public String compile() {
+ List<String> queries = dslQueryBuilders.stream().map(dslQb -> dslQb.getQuery().toString())
+ .collect(Collectors.toList());
+ return String.join("", Lists.reverse(queries));
+ }
+
+ public String getException() {
+ List<String> exceptions = dslQueryBuilders.stream()
+ .map(dslQb -> dslQb.getQueryException().toString()).collect(Collectors.toList());
+ return String.join("", Lists.reverse(exceptions));
+ }
+
+ @Override
+ public void enterAaiquery(AAIDslParser.AaiqueryContext ctx) {
+ dslQueryBuilders.push(new DslQueryBuilder(edgeIngestor, loader));
+ }
+
+ @Override
+ public void exitAaiquery(AAIDslParser.AaiqueryContext ctx) {
+ if (!hasReturnValue) {
+ throw new RuntimeException(new AAIException("AAI_6149", "No nodes marked for output"));
+ }
+ }
+
+ @Override
+ public void enterStartStatement(AAIDslParser.StartStatementContext ctx) {
+ builder().start();
+ }
+
+ @Override
+ public void exitStartStatement(AAIDslParser.StartStatementContext ctx) {
+ builder().end();
+ if (!traversedNodes.isEmpty()) {
+ traversedNodes.removeFirst();
+ }
+
+ }
+
+ @Override
+ public void exitLimit(AAIDslParser.LimitContext ctx) {
+ builder().limit(ctx.num().getText());
+ }
+
+ @Override
+ public void enterNestedStatement(AAIDslParser.NestedStatementContext ctx) {
+ dslQueryBuilders.addFirst(new DslQueryBuilder(edgeIngestor, loader));
+ builder().startInstance();
+ }
+
+ @Override
+ public void exitNestedStatement(AAIDslParser.NestedStatementContext ctx) {
+ int count = 1;
+ if (!ctx.traversal().isEmpty()) {
+ count += ctx.traversal().size();
+ }
+ String resultNode = traversedNodes.peekFirst();
+
+ if (!traversedNodes.isEmpty()) {
+ Stream<Integer> integers = Stream.iterate(0, i -> i + 1);
+ integers.limit(count).forEach(i -> traversedNodes.removeFirst());
+ }
+ List<String> resultNodes = returnedNodes.pop();
+ resultNodes.add(resultNode);
+ returnedNodes.addFirst(resultNodes);
+ }
+
+ @Override
+ public void enterComma(AAIDslParser.CommaContext ctx) {
+ builder().comma();
+ }
+
+ @Override
+ public void enterVertex(AAIDslParser.VertexContext ctx) {
+
+ if (!traversedNodes.isEmpty()) {
+ builder().edgeQuery(traversedEdgeLabels, traversedNodes.peekFirst(),
+ ctx.label().getText());
+ traversedEdges.add(traversedNodes.peekFirst() + ctx.label().getText());
+ } else {
+ builder().nodeQuery(ctx.label().getText());
+ }
+
+ traversedNodes.addFirst(ctx.label().getText());
+ }
+
+ @Override
+ public void exitVertex(AAIDslParser.VertexContext ctx) {
+
+ /* TODO dont use context */
+ if (ctx.getParent() instanceof AAIDslParser.StartStatementContext && isValidationFlag()) {
+ List<String> allKeys = new ArrayList<>();
+
+ if (ctx.filter() != null) {
+ allKeys = ctx
+ .filter().propertyFilter().stream().flatMap(pf -> pf.key().stream()).map(e -> e
+ .getText().replaceFirst("\'", "").substring(0, e.getText().length() - 2))
+ .collect(Collectors.toList());
+
+ }
+ builder().validateFilter(ctx.label().getText(), allKeys);
+ }
+ if (ctx.store() != null) {
+ builder().store();
+ hasReturnValue = true;
+ }
+ traversedEdgeLabels = new ArrayList<>();
+ nodeCount++;
+ }
+
+ @Override
+ public void enterUnionVertex(AAIDslParser.UnionVertexContext ctx) {
+ returnedNodes.addFirst(new ArrayList<>());
+ builder().union();
+ }
+
+ @Override
+ public void exitUnionVertex(AAIDslParser.UnionVertexContext ctx) {
+ String resultNode = returnedNodes.pop().get(0);
+ traversedNodes.addFirst(resultNode);
+ builder().endUnion();
+ if (ctx.store() != null) {
+ builder().store();
+ hasReturnValue = true;
+ }
+ }
+
+ @Override
+ public void enterWhereFilter(AAIDslParser.WhereFilterContext ctx) {
+ boolean isNot = ctx.not() != null && !ctx.not().isEmpty();
+ returnedNodes.addFirst(new ArrayList<>());
+ builder().where(isNot);
+ }
+
+ @Override
+ public void exitWhereFilter(AAIDslParser.WhereFilterContext ctx) {
+ if (!returnedNodes.isEmpty()) {
+ returnedNodes.pop();
+ }
+ boolean isNot = ctx.not() != null && !ctx.not().isEmpty();
+ builder().endWhere(isNot);
+ }
+
+ @Override
+ public void enterEdgeFilter(AAIDslParser.EdgeFilterContext ctx) {
+ traversedEdgeLabels =
+ ctx.key().stream().map(value -> value.getText()).collect(Collectors.toList());
+
+ }
+
+ @Override
+ public void enterPropertyFilter(AAIDslParser.PropertyFilterContext ctx) {
+
+ List<AAIDslParser.KeyContext> valueList = ctx.key();
+ String filterKey = valueList.get(0).getText();
+
+ boolean isNot = ctx.not() != null && !ctx.not().isEmpty();
+ List<AAIDslParser.NumContext> numberValues = ctx.num();
+
+ List<AAIDslParser.BoolContext> booleanValues = ctx.bool();
+
+ /*
+ * Add all String values
+ */
+ List<String> values = valueList.stream().filter(value -> !filterKey.equals(value.getText()))
+ .map(value -> value.getText()).collect(Collectors.toList());
+
+ /*
+ * Add all numeric values
+ */
+ values.addAll(numberValues.stream().filter(value -> !filterKey.equals(value.getText()))
+ .map(value -> value.getText()).collect(Collectors.toList()));
+
+ /*
+ * Add all boolean values
+ */
+ values.addAll(booleanValues.stream().filter(value -> !filterKey.equals(value.getText()))
+ .map(value -> value.getText().toLowerCase()).collect(Collectors.toList()));
+
+ builder().filter(isNot, traversedNodes.peekFirst(), filterKey, values);
+
+ }
+
+ public boolean isValidationFlag() {
+ return validationFlag;
+ }
+
+ public void setValidationFlag(boolean validationFlag) {
+ this.validationFlag = validationFlag;
+ }
+
+ public void setQueryValidator(DslValidator queryValidator, String validationRules) {
+ this.queryValidator = Optional.of(queryValidator);
+ this.validationRules = validationRules;
+ }
+
+ public String getValidationRules() {
+ return validationRules;
+ }
+
+ public void setAggregateFlag(boolean isAggregate) {
+ this.isAggregate = isAggregate;
+ }
+
+ public boolean isAggregate() {
+ return this.isAggregate;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/v2/DslListener.java b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/v2/DslListener.java
index 66ca8a1..7e46c0b 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/v2/DslListener.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/v2/DslListener.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -20,6 +20,11 @@
package org.onap.aai.rest.dsl.v2;
import com.google.common.collect.Lists;
+
+import java.util.*;
+import java.util.stream.Collectors;
+import java.util.stream.Stream;
+
import org.onap.aai.dsl.v2.AAIDslBaseListener;
import org.onap.aai.dsl.v2.AAIDslParser;
import org.onap.aai.edges.EdgeIngestor;
@@ -39,273 +44,274 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import java.util.*;
-import java.util.stream.Collectors;
-import java.util.stream.Stream;
-
/**
* The Class DslListener.
*/
public class DslListener extends AAIDslBaseListener {
- private static final Logger LOGGER = LoggerFactory.getLogger(DslListener.class.getName());
-
- private boolean validationFlag = false;
- private EdgeIngestor edgeIngestor;
- private Loader loader;
- private Optional<DslValidator> queryValidator = Optional.empty();
- private boolean hasReturnValue = false;
-
- private String validationRules = "none";
-
- private Deque<DslQueryBuilder> dslQueryBuilders = new LinkedList<>();
- private Deque<String> traversedNodes = new LinkedList<>();
- private Deque<List<String>> returnedNodes = new LinkedList<>();
-
- private Deque<Edge> traversedEdges = new ArrayDeque<>();
- private long selectCounter = 0;
-
- /*
- * Additional datastructures to store all nodeCount & looped edges
- */
- int nodeCount = 0;
- private List<String> traversedEdgesOld = new LinkedList<>();
-
- private Map<String, List<String>> selectKeys = new HashMap<String, List<String>>();
- private boolean isAggregate;
-
- public Map<String, List<String>> getSelectKeys() {
- return selectKeys;
- }
-
- public void setSelectKeys(String nodeType, List<String> properties) {
- this.selectKeys.put(nodeType, properties);
- }
-
- /**
- * Instantiates a new DslListener.
- */
- @Autowired
- public DslListener(EdgeIngestor edgeIngestor, SchemaVersions schemaVersions, LoaderFactory loaderFactory) {
- this.loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
- this.edgeIngestor = edgeIngestor;
- }
-
- public DslQueryBuilder builder() {
- return dslQueryBuilders.peekFirst();
- }
-
- public String getQuery() throws AAIException {
- //TODO Change the exception reporting
- if (!getException().isEmpty()) {
- AAIException aaiException = new AAIException("AAI_6149", getException());
- ErrorLogHelper.logException(aaiException);
- throw aaiException;
- }
-
- DslValidatorRule ruleValidator = new DslValidatorRule.Builder()
- .loop(getValidationRules() , traversedEdgesOld)
- .nodeCount(getValidationRules(), nodeCount).build();
- if(queryValidator.isPresent() && !queryValidator.get().validate(ruleValidator)){
- AAIException aaiException = new AAIException("AAI_6151", "Validation error " + queryValidator.get().getErrorMessage() );
- ErrorLogHelper.logException(aaiException);
- throw aaiException;
- }
- return this.compile();
- }
-
- public String compile() {
- List<String> queries = dslQueryBuilders.stream().map(dslQb -> dslQb.getQuery().toString()).collect(Collectors.toList());
- return String.join("", Lists.reverse(queries));
- }
-
- public String getException() {
- List<String> exceptions = dslQueryBuilders.stream().map(dslQb -> dslQb.getQueryException().toString()).collect(Collectors.toList());
- return String.join("", Lists.reverse(exceptions));
- }
-
- @Override
- public void enterAaiquery(AAIDslParser.AaiqueryContext ctx) {
- dslQueryBuilders.push(new DslQueryBuilder(edgeIngestor, loader));
- }
-
- @Override
- public void exitAaiquery(AAIDslParser.AaiqueryContext ctx) {
- if (!hasReturnValue) {
- throw new RuntimeException(new AAIException("AAI_6149", "No nodes marked for output"));
- }
- }
-
- @Override
- public void enterStartStatement(AAIDslParser.StartStatementContext ctx) {
- builder().start();
- }
-
- @Override
- public void exitStartStatement(AAIDslParser.StartStatementContext ctx) {
- builder().end(selectCounter);
- if (!traversedNodes.isEmpty()) {
- traversedNodes.removeFirst();
- }
-
- }
-
- @Override
- public void exitLimit(AAIDslParser.LimitContext ctx) {
- builder().limit(ctx.num().getText());
- }
-
- @Override
- public void enterNestedStatement(AAIDslParser.NestedStatementContext ctx) {
- dslQueryBuilders.addFirst(new DslQueryBuilder(edgeIngestor, loader));
- builder().startInstance();
- }
-
- @Override
- public void exitNestedStatement(AAIDslParser.NestedStatementContext ctx) {
- int count = 1;
- if(!ctx.traversal().isEmpty()) {
- count = ctx.traversal().size() ;
- }
- String resultNode = traversedNodes.peekFirst();
-
- if (!traversedNodes.isEmpty()) {
- Stream<Integer> integers = Stream.iterate(0, i -> i + 1);
- integers.limit(count)
- .forEach(i -> traversedNodes.removeFirst());
- }
- List<String> resultNodes = returnedNodes.pop();
- resultNodes.add(resultNode);
- returnedNodes.addFirst(resultNodes);
- }
-
- @Override
- public void enterComma(AAIDslParser.CommaContext ctx) {
- builder().comma();
- }
-
- @Override
- public void enterVertex(AAIDslParser.VertexContext ctx) {
-
- if (!traversedEdges.isEmpty() && !traversedNodes.isEmpty()) {
- builder().edgeQuery(traversedEdges.peekFirst(), traversedNodes.peekFirst(), ctx.label().getText());
- traversedEdgesOld.add(traversedNodes.peekFirst() + ctx.label().getText());
- } else {
- builder().nodeQuery(ctx.label().getText());
- }
-
- traversedNodes.addFirst(ctx.label().getText());
- }
-
- @Override
- public void exitVertex(AAIDslParser.VertexContext ctx) {
-
- /*TODO dont use context */
- if (ctx.getParent() instanceof AAIDslParser.StartStatementContext && isValidationFlag()) {
- List<String> allKeys = new ArrayList<>();
-
- if (ctx.filter() != null) {
- allKeys = ctx.filter().propertyFilter().stream().flatMap(
- pf -> pf.key().stream()).map(
- e -> e.getText().replaceFirst("\'", "").substring(0, e.getText().length() - 2)).collect(Collectors.toList());
- }
- builder().validateFilter(ctx.label().getText(), allKeys);
- }
- if (ctx.store() != null) {
- if (isAggregate()) {
- builder().select(selectCounter++, null);
- }
- builder().store();
- hasReturnValue = true;
- }
- nodeCount++;
- }
-
-
- @Override
- public void enterUnionVertex(AAIDslParser.UnionVertexContext ctx) {
- returnedNodes.addFirst(new ArrayList<>());
- builder().union();
- }
-
- @Override
- public void exitUnionVertex(AAIDslParser.UnionVertexContext ctx) {
- String resultNode = returnedNodes.pop().get(0);
- traversedNodes.addFirst(resultNode);
- builder().endUnion();
- if (ctx.store() != null) {
- builder().store();
- hasReturnValue = true;
- }
- }
-
- @Override
- public void enterWhereFilter(AAIDslParser.WhereFilterContext ctx) {
- boolean isNot = ctx.not() != null && !ctx.not().isEmpty();
- returnedNodes.addFirst(new ArrayList<>());
- builder().where(isNot);
- }
-
- @Override
- public void exitWhereFilter(AAIDslParser.WhereFilterContext ctx) {
- if(!returnedNodes.isEmpty()) {
- returnedNodes.pop();
- }
- boolean isNot = ctx.not() != null && !ctx.not().isEmpty();
- builder().endWhere(isNot);
- }
-
- @Override
- public void enterEdge(AAIDslParser.EdgeContext ctx) {
- List<EdgeLabel> labels = new ArrayList<>();
-
- if(ctx.edgeFilter() != null) {
- labels.addAll(ctx.edgeFilter().key().stream().map(
- e -> new EdgeLabel(removeSingleQuotes(e.getText()), true))
- .collect(Collectors.toList()));
- }
- EdgeDirection direction = EdgeDirection.BOTH;
- if(ctx.DIRTRAVERSE() != null){
- direction = EdgeDirection.fromValue(ctx.DIRTRAVERSE().getText());
- }
- traversedEdges.addFirst(new Edge(direction, labels));
- }
-
- protected String removeSingleQuotes(String value) {
- return value.replaceFirst("^'(.*)'$", "$1");
- }
-
- @Override
- public void enterPropertyFilter(AAIDslParser.PropertyFilterContext ctx) {
-
- List<AAIDslParser.KeyContext> valueList = ctx.key();
- String filterKey = valueList.get(0).getText();
-
- boolean isNot = ctx.not() != null && !ctx.not().isEmpty();
- List<AAIDslParser.NumContext> numberValues = ctx.num();
-
- List<AAIDslParser.BoolContext> booleanValues = ctx.bool();
-
- /*
- * Add all String values
- */
- List<String> values = valueList.stream().filter(value -> !filterKey.equals(value.getText()))
- .map(value -> value.getText()).collect(Collectors.toList());
- /*
- * Add all numeric values
- */
- values.addAll(numberValues.stream().filter(value -> !filterKey.equals(value.getText()))
- .map(value -> value.getText()).collect(Collectors.toList()));
-
- /*
- * Add all boolean values
- */
- values.addAll(booleanValues.stream().filter(value -> !filterKey.equals(value.getText()))
- .map(value -> value.getText().toLowerCase()).collect(Collectors.toList()));
-
- builder().filter(isNot, traversedNodes.peekFirst(), filterKey, values);
-
- }
+ private static final Logger LOGGER = LoggerFactory.getLogger(DslListener.class.getName());
+
+ private boolean validationFlag = false;
+ private EdgeIngestor edgeIngestor;
+ private Loader loader;
+ private Optional<DslValidator> queryValidator = Optional.empty();
+ private boolean hasReturnValue = false;
+
+ private String validationRules = "none";
+
+ private Deque<DslQueryBuilder> dslQueryBuilders = new LinkedList<>();
+ private Deque<String> traversedNodes = new LinkedList<>();
+ private Deque<List<String>> returnedNodes = new LinkedList<>();
+
+ private Deque<Edge> traversedEdges = new ArrayDeque<>();
+ private long selectCounter = 0;
+
+ /*
+ * Additional datastructures to store all nodeCount & looped edges
+ */
+ int nodeCount = 0;
+ private List<String> traversedEdgesOld = new LinkedList<>();
+
+ private Map<String, List<String>> selectKeys = new HashMap<String, List<String>>();
+ private boolean isAggregate;
+
+ public Map<String, List<String>> getSelectKeys() {
+ return selectKeys;
+ }
+
+ public void setSelectKeys(String nodeType, List<String> properties) {
+ this.selectKeys.put(nodeType, properties);
+ }
+
+ /**
+ * Instantiates a new DslListener.
+ */
+ @Autowired
+ public DslListener(EdgeIngestor edgeIngestor, SchemaVersions schemaVersions,
+ LoaderFactory loaderFactory) {
+ this.loader = loaderFactory.createLoaderForVersion(ModelType.MOXY,
+ schemaVersions.getDefaultVersion());
+ this.edgeIngestor = edgeIngestor;
+ }
+
+ public DslQueryBuilder builder() {
+ return dslQueryBuilders.peekFirst();
+ }
+
+ public String getQuery() throws AAIException {
+ // TODO Change the exception reporting
+ if (!getException().isEmpty()) {
+ AAIException aaiException = new AAIException("AAI_6149", getException());
+ ErrorLogHelper.logException(aaiException);
+ throw aaiException;
+ }
+
+ DslValidatorRule ruleValidator =
+ new DslValidatorRule.Builder().loop(getValidationRules(), traversedEdgesOld)
+ .nodeCount(getValidationRules(), nodeCount).build();
+ if (queryValidator.isPresent() && !queryValidator.get().validate(ruleValidator)) {
+ AAIException aaiException = new AAIException("AAI_6151",
+ "Validation error " + queryValidator.get().getErrorMessage());
+ ErrorLogHelper.logException(aaiException);
+ throw aaiException;
+ }
+ return this.compile();
+ }
+
+ public String compile() {
+ List<String> queries = dslQueryBuilders.stream().map(dslQb -> dslQb.getQuery().toString())
+ .collect(Collectors.toList());
+ return String.join("", Lists.reverse(queries));
+ }
+
+ public String getException() {
+ List<String> exceptions = dslQueryBuilders.stream()
+ .map(dslQb -> dslQb.getQueryException().toString()).collect(Collectors.toList());
+ return String.join("", Lists.reverse(exceptions));
+ }
+
+ @Override
+ public void enterAaiquery(AAIDslParser.AaiqueryContext ctx) {
+ dslQueryBuilders.push(new DslQueryBuilder(edgeIngestor, loader));
+ }
+
+ @Override
+ public void exitAaiquery(AAIDslParser.AaiqueryContext ctx) {
+ if (!hasReturnValue) {
+ throw new RuntimeException(new AAIException("AAI_6149", "No nodes marked for output"));
+ }
+ }
+
+ @Override
+ public void enterStartStatement(AAIDslParser.StartStatementContext ctx) {
+ builder().start();
+ }
+
+ @Override
+ public void exitStartStatement(AAIDslParser.StartStatementContext ctx) {
+ builder().end(selectCounter);
+ if (!traversedNodes.isEmpty()) {
+ traversedNodes.removeFirst();
+ }
+
+ }
+
+ @Override
+ public void exitLimit(AAIDslParser.LimitContext ctx) {
+ builder().limit(ctx.num().getText());
+ }
+
+ @Override
+ public void enterNestedStatement(AAIDslParser.NestedStatementContext ctx) {
+ dslQueryBuilders.addFirst(new DslQueryBuilder(edgeIngestor, loader));
+ builder().startInstance();
+ }
+
+ @Override
+ public void exitNestedStatement(AAIDslParser.NestedStatementContext ctx) {
+ int count = 1;
+ if (!ctx.traversal().isEmpty()) {
+ count = ctx.traversal().size();
+ }
+ String resultNode = traversedNodes.peekFirst();
+
+ if (!traversedNodes.isEmpty()) {
+ Stream<Integer> integers = Stream.iterate(0, i -> i + 1);
+ integers.limit(count).forEach(i -> traversedNodes.removeFirst());
+ }
+ List<String> resultNodes = returnedNodes.pop();
+ resultNodes.add(resultNode);
+ returnedNodes.addFirst(resultNodes);
+ }
+
+ @Override
+ public void enterComma(AAIDslParser.CommaContext ctx) {
+ builder().comma();
+ }
+
+ @Override
+ public void enterVertex(AAIDslParser.VertexContext ctx) {
+
+ if (!traversedEdges.isEmpty() && !traversedNodes.isEmpty()) {
+ builder().edgeQuery(traversedEdges.peekFirst(), traversedNodes.peekFirst(),
+ ctx.label().getText());
+ traversedEdgesOld.add(traversedNodes.peekFirst() + ctx.label().getText());
+ } else {
+ builder().nodeQuery(ctx.label().getText());
+ }
+
+ traversedNodes.addFirst(ctx.label().getText());
+ }
+
+ @Override
+ public void exitVertex(AAIDslParser.VertexContext ctx) {
+
+ /* TODO dont use context */
+ if (ctx.getParent() instanceof AAIDslParser.StartStatementContext && isValidationFlag()) {
+ List<String> allKeys = new ArrayList<>();
+
+ if (ctx.filter() != null) {
+ allKeys = ctx
+ .filter().propertyFilter().stream().flatMap(pf -> pf.key().stream()).map(e -> e
+ .getText().replaceFirst("\'", "").substring(0, e.getText().length() - 2))
+ .collect(Collectors.toList());
+ }
+ builder().validateFilter(ctx.label().getText(), allKeys);
+ }
+ if (ctx.store() != null) {
+ if (isAggregate()) {
+ builder().select(selectCounter++, null);
+ }
+ builder().store();
+ hasReturnValue = true;
+ }
+ nodeCount++;
+ }
+
+ @Override
+ public void enterUnionVertex(AAIDslParser.UnionVertexContext ctx) {
+ returnedNodes.addFirst(new ArrayList<>());
+ builder().union();
+ }
+
+ @Override
+ public void exitUnionVertex(AAIDslParser.UnionVertexContext ctx) {
+ String resultNode = returnedNodes.pop().get(0);
+ traversedNodes.addFirst(resultNode);
+ builder().endUnion();
+ if (ctx.store() != null) {
+ builder().store();
+ hasReturnValue = true;
+ }
+ }
+
+ @Override
+ public void enterWhereFilter(AAIDslParser.WhereFilterContext ctx) {
+ boolean isNot = ctx.not() != null && !ctx.not().isEmpty();
+ returnedNodes.addFirst(new ArrayList<>());
+ builder().where(isNot);
+ }
+
+ @Override
+ public void exitWhereFilter(AAIDslParser.WhereFilterContext ctx) {
+ if (!returnedNodes.isEmpty()) {
+ returnedNodes.pop();
+ }
+ boolean isNot = ctx.not() != null && !ctx.not().isEmpty();
+ builder().endWhere(isNot);
+ }
+
+ @Override
+ public void enterEdge(AAIDslParser.EdgeContext ctx) {
+ List<EdgeLabel> labels = new ArrayList<>();
+
+ if (ctx.edgeFilter() != null) {
+ labels.addAll(ctx.edgeFilter().key().stream()
+ .map(e -> new EdgeLabel(removeSingleQuotes(e.getText()), true))
+ .collect(Collectors.toList()));
+ }
+ EdgeDirection direction = EdgeDirection.BOTH;
+ if (ctx.DIRTRAVERSE() != null) {
+ direction = EdgeDirection.fromValue(ctx.DIRTRAVERSE().getText());
+ }
+ traversedEdges.addFirst(new Edge(direction, labels));
+ }
+
+ protected String removeSingleQuotes(String value) {
+ return value.replaceFirst("^'(.*)'$", "$1");
+ }
+
+ @Override
+ public void enterPropertyFilter(AAIDslParser.PropertyFilterContext ctx) {
+
+ List<AAIDslParser.KeyContext> valueList = ctx.key();
+ String filterKey = valueList.get(0).getText();
+
+ boolean isNot = ctx.not() != null && !ctx.not().isEmpty();
+ List<AAIDslParser.NumContext> numberValues = ctx.num();
+
+ List<AAIDslParser.BoolContext> booleanValues = ctx.bool();
+
+ /*
+ * Add all String values
+ */
+ List<String> values = valueList.stream().filter(value -> !filterKey.equals(value.getText()))
+ .map(value -> value.getText()).collect(Collectors.toList());
+ /*
+ * Add all numeric values
+ */
+ values.addAll(numberValues.stream().filter(value -> !filterKey.equals(value.getText()))
+ .map(value -> value.getText()).collect(Collectors.toList()));
+
+ /*
+ * Add all boolean values
+ */
+ values.addAll(booleanValues.stream().filter(value -> !filterKey.equals(value.getText()))
+ .map(value -> value.getText().toLowerCase()).collect(Collectors.toList()));
+
+ builder().filter(isNot, traversedNodes.peekFirst(), filterKey, values);
+
+ }
@Override
public void enterSelectFilter(AAIDslParser.SelectFilterContext ctx) {
@@ -315,37 +321,40 @@ public class DslListener extends AAIDslBaseListener {
/*
* Add all String values
*/
- List<String> allKeys = keyList.stream().map(keyValue -> "'" + keyValue.getText().replace("'", "") + "'").collect(Collectors.toList());
- if (allKeys != null && !allKeys.isEmpty()){
- setSelectKeys(traversedNodes.getFirst(), allKeys);
- }
- if (isAggregate() && (traversedNodes.size() == nodeCount)) {
- builder().select(selectCounter++, allKeys);
- }
+ List<String> allKeys =
+ keyList.stream().map(keyValue -> "'" + keyValue.getText().replace("'", "") + "'")
+ .collect(Collectors.toList());
+ if (allKeys != null && !allKeys.isEmpty()) {
+ setSelectKeys(traversedNodes.getFirst(), allKeys);
+ }
+ if (isAggregate() && (traversedNodes.size() == nodeCount)) {
+ builder().select(selectCounter++, allKeys);
+ }
+ }
+
+ public boolean isValidationFlag() {
+ return validationFlag;
}
- public boolean isValidationFlag() {
- return validationFlag;
- }
-
- public void setValidationFlag(boolean validationFlag) {
- this.validationFlag = validationFlag;
- }
-
- public void setAggregateFlag(boolean isAggregate) {
- this.isAggregate = isAggregate;
- }
-
- public boolean isAggregate(){
- return this.isAggregate;
- }
-
- public void setQueryValidator(DslValidator queryValidator, String validationRules) {
- this.queryValidator = Optional.of(queryValidator);
- this.validationRules = validationRules;
- }
- public String getValidationRules() {
- return validationRules;
- }
+ public void setValidationFlag(boolean validationFlag) {
+ this.validationFlag = validationFlag;
+ }
+
+ public void setAggregateFlag(boolean isAggregate) {
+ this.isAggregate = isAggregate;
+ }
+
+ public boolean isAggregate() {
+ return this.isAggregate;
+ }
+
+ public void setQueryValidator(DslValidator queryValidator, String validationRules) {
+ this.queryValidator = Optional.of(queryValidator);
+ this.validationRules = validationRules;
+ }
+
+ public String getValidationRules() {
+ return validationRules;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslQueryValidator.java b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslQueryValidator.java
index 53f2c72..e82cfc2 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslQueryValidator.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslQueryValidator.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,13 +19,13 @@
*/
package org.onap.aai.rest.dsl.validation;
-import org.onap.aai.util.AAIConfig;
-import org.onap.aai.util.TraversalConstants;
-
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Set;
+import org.onap.aai.util.AAIConfig;
+import org.onap.aai.util.TraversalConstants;
+
public class DslQueryValidator extends DslValidator {
protected DslQueryValidator(Builder builder) {
@@ -34,7 +34,9 @@ public class DslQueryValidator extends DslValidator {
public boolean validate(DslValidatorRule dslValidatorRule) {
- return validateLoop(dslValidatorRule.isValidateLoop(), dslValidatorRule.getEdges()) && validateNodeCount(dslValidatorRule.isValidateNodeCount(), dslValidatorRule.getNodeCount());
+ return validateLoop(dslValidatorRule.isValidateLoop(), dslValidatorRule.getEdges())
+ && validateNodeCount(dslValidatorRule.isValidateNodeCount(),
+ dslValidatorRule.getNodeCount());
}
private boolean validateLoop(boolean isValidateLoop, List<String> edges) {
@@ -50,7 +52,8 @@ public class DslQueryValidator extends DslValidator {
}
private boolean validateNodeCount(boolean isValidateNodeCount, int nodeCount) {
- String maxNodeString = AAIConfig.get("aai.dsl.max.nodecount", TraversalConstants.DSL_MAX_NODE_COUNT);
+ String maxNodeString =
+ AAIConfig.get("aai.dsl.max.nodecount", TraversalConstants.DSL_MAX_NODE_COUNT);
int maxNodeCount = Integer.parseInt(maxNodeString);
if (isValidateNodeCount && nodeCount > maxNodeCount) {
this.errorMessage.append("NodeCount Validation failed");
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslSchemaValidator.java b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslSchemaValidator.java
index 54a2feb..15d8cca 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslSchemaValidator.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslSchemaValidator.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslValidator.java b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslValidator.java
index 128f8a8..7f14458 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslValidator.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslValidator.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -24,7 +24,6 @@ import org.onap.aai.exceptions.AAIException;
public abstract class DslValidator {
protected StringBuilder errorMessage = new StringBuilder("");
-
protected DslValidator(DslValidator.Builder builder) {
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslValidatorRule.java b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslValidatorRule.java
index 54d45bd..117c9a5 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslValidatorRule.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/dsl/validation/DslValidatorRule.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -84,7 +84,7 @@ public class DslValidatorRule {
public static class Builder {
- //todo optional
+ // todo optional
String query = "";
boolean validateLoop = false;
boolean validateNodeCount = false;
@@ -114,7 +114,8 @@ public class DslValidatorRule {
}
public Builder nodeCount(String validateNodeCount, int nodeCount) {
- if (validateNodeCount.contains(NODECOUNT_RULE) || validateNodeCount.contains(ALL_RULE)) {
+ if (validateNodeCount.contains(NODECOUNT_RULE)
+ || validateNodeCount.contains(ALL_RULE)) {
this.setValidateNodeCount(true);
this.nodeCount = nodeCount;
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/enums/EdgeDirection.java b/aai-traversal/src/main/java/org/onap/aai/rest/enums/EdgeDirection.java
index 61f35ac..8aa7a69 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/enums/EdgeDirection.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/enums/EdgeDirection.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -20,10 +20,7 @@
package org.onap.aai.rest.enums;
public enum EdgeDirection {
- OUT(">>"),
- IN("<<"),
- BOTH(">");
-
+ OUT(">>"), IN("<<"), BOTH(">");
private final String value;
@@ -31,7 +28,6 @@ public enum EdgeDirection {
this.value = value;
}
-
public static EdgeDirection fromValue(String value) {
for (EdgeDirection d : values()) {
@@ -41,8 +37,9 @@ public enum EdgeDirection {
}
return BOTH;
}
+
@Override
public String toString() {
return value;
}
-} \ No newline at end of file
+}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/enums/QueryVersion.java b/aai-traversal/src/main/java/org/onap/aai/rest/enums/QueryVersion.java
index 0e30f28..8ba2faf 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/enums/QueryVersion.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/enums/QueryVersion.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -20,6 +20,5 @@
package org.onap.aai.rest.enums;
public enum QueryVersion {
- V1,
- V2;
-} \ No newline at end of file
+ V1, V2;
+}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/CQConfig.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/CQConfig.java
index d17fb2b..e6f55eb 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/CQConfig.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/CQConfig.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -22,7 +22,7 @@ package org.onap.aai.rest.search;
public abstract class CQConfig {
protected GetCustomQueryConfig queryConfig;
- public GetCustomQueryConfig getCustomQueryConfig(){
+ public GetCustomQueryConfig getCustomQueryConfig() {
return queryConfig;
}
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryConfig.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryConfig.java
index 2fa7ec1..a7633ca 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryConfig.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryConfig.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -22,32 +22,35 @@ package org.onap.aai.rest.search;
import java.util.List;
public class CustomQueryConfig {
- public CustomQueryConfig() {
- // used by GetCustomQueryConfig
- }
-
-
- private String query;
- private List<String> queryOptionalProperties;
- private List<String> queryRequiredProperties;
-
- public void setQuery(String query) {
- this.query = query;
- }
- public String getQuery() {
- return this.query;
- }
-
- public void setQueryOptionalProperties( List<String> queryOptionalProperties) {
- this.queryOptionalProperties = queryOptionalProperties;
- }
- public List<String> getQueryOptionalProperties( ) {
- return queryOptionalProperties;
- }
- public void setQueryRequiredProperties( List<String> queryRequiredProperties) {
- this.queryRequiredProperties = queryRequiredProperties;
- }
- public List<String> getQueryRequiredProperties( ) {
- return queryRequiredProperties;
- }
+ public CustomQueryConfig() {
+ // used by GetCustomQueryConfig
+ }
+
+ private String query;
+ private List<String> queryOptionalProperties;
+ private List<String> queryRequiredProperties;
+
+ public void setQuery(String query) {
+ this.query = query;
+ }
+
+ public String getQuery() {
+ return this.query;
+ }
+
+ public void setQueryOptionalProperties(List<String> queryOptionalProperties) {
+ this.queryOptionalProperties = queryOptionalProperties;
+ }
+
+ public List<String> getQueryOptionalProperties() {
+ return queryOptionalProperties;
+ }
+
+ public void setQueryRequiredProperties(List<String> queryRequiredProperties) {
+ this.queryRequiredProperties = queryRequiredProperties;
+ }
+
+ public List<String> getQueryRequiredProperties() {
+ return queryRequiredProperties;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryConfigDTO.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryConfigDTO.java
index 30d8d30..7f90566 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryConfigDTO.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryConfigDTO.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -39,32 +39,32 @@ package org.onap.aai.rest.search;
* ============LICENSE_END=========================================================
*/
-import org.springframework.util.StringUtils;
-
import com.fasterxml.jackson.annotation.JsonProperty;
+import org.springframework.util.StringUtils;
+
public class CustomQueryConfigDTO {
- @JsonProperty("stored-query")
- private String storedQuery;
- @JsonProperty("query")
- private CustomQueryDTO queryDTO;
+ @JsonProperty("stored-query")
+ private String storedQuery;
+ @JsonProperty("query")
+ private CustomQueryDTO queryDTO;
+
+ public CustomQueryDTO getQueryDTO() {
+ if (queryDTO == null)
+ queryDTO = new CustomQueryDTO();
+ if (!StringUtils.isEmpty(storedQuery)) {
+ queryDTO.setQuery(storedQuery);
+ }
+ return queryDTO;
+ }
- public CustomQueryDTO getQueryDTO() {
- if(queryDTO == null)
- queryDTO = new CustomQueryDTO();
- if (!StringUtils.isEmpty(storedQuery)) {
- queryDTO.setQuery(storedQuery);
- }
- return queryDTO;
- }
+ public void setQueryDTO(CustomQueryDTO query) {
+ this.queryDTO = query;
+ }
- public void setQueryDTO(CustomQueryDTO query) {
- this.queryDTO = query;
- }
+ public void setStoredQuery(String storedQuery) {
+ this.storedQuery = storedQuery;
+ }
- public void setStoredQuery(String storedQuery) {
- this.storedQuery = storedQuery;
- }
-
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryDTO.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryDTO.java
index 16b1430..970e5b3 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryDTO.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryDTO.java
@@ -10,7 +10,7 @@ package org.onap.aai.rest.search;
* 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
+ * 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,
@@ -20,37 +20,41 @@ package org.onap.aai.rest.search;
* ============LICENSE_END=========================================================
*/
-import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
import com.google.common.collect.Lists;
+import java.util.List;
+
public class CustomQueryDTO {
- private String query;
- @JsonProperty("optional-properties")
- private List<String> queryOptionalProperties = Lists.newArrayList();
- @JsonProperty("required-properties")
- private List<String> queryRequiredProperties = Lists.newArrayList();;
-
- public void setQuery(String query) {
- this.query = query;
- }
- public String getQuery() {
- return this.query;
- }
-
- public void setQueryOptionalProperties( List<String> queryOptionalProperties) {
- this.queryOptionalProperties = queryOptionalProperties;
- }
- public List<String> getQueryOptionalProperties( ) {
- return queryOptionalProperties;
- }
- public void setQueryRequiredProperties( List<String> queryRequiredProperties) {
- this.queryRequiredProperties = queryRequiredProperties;
- }
- public List<String> getQueryRequiredProperties( ) {
- return queryRequiredProperties;
- }
+ private String query;
+ @JsonProperty("optional-properties")
+ private List<String> queryOptionalProperties = Lists.newArrayList();
+ @JsonProperty("required-properties")
+ private List<String> queryRequiredProperties = Lists.newArrayList();;
+
+ public void setQuery(String query) {
+ this.query = query;
+ }
+
+ public String getQuery() {
+ return this.query;
+ }
+
+ public void setQueryOptionalProperties(List<String> queryOptionalProperties) {
+ this.queryOptionalProperties = queryOptionalProperties;
+ }
+
+ public List<String> getQueryOptionalProperties() {
+ return queryOptionalProperties;
+ }
+
+ public void setQueryRequiredProperties(List<String> queryRequiredProperties) {
+ this.queryRequiredProperties = queryRequiredProperties;
+ }
+
+ public List<String> getQueryRequiredProperties() {
+ return queryRequiredProperties;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryTestDTO.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryTestDTO.java
index cdc9d15..b64f07f 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryTestDTO.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/CustomQueryTestDTO.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -39,83 +39,79 @@ package org.onap.aai.rest.search;
* ============LICENSE_END=========================================================
*/
+import com.beust.jcommander.internal.Maps;
+import com.fasterxml.jackson.annotation.JsonProperty;
+
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
-import com.beust.jcommander.internal.Maps;
-import com.fasterxml.jackson.annotation.JsonProperty;
-
public class CustomQueryTestDTO {
-
-
- @JsonProperty("stored-query")
- private String storedQuery;
-
- @JsonProperty("vertices")
- private List<LinkedHashMap<String, String>> verticesDtos;
-
- @JsonProperty("edges")
- private List<LinkedHashMap<String, String>> edgesDtos;
-
- @JsonProperty("optional-properties")
- private Map<String, String> queryOptionalProperties = Maps.newHashMap();
-
- @JsonProperty("required-properties")
- private Map<String, String> queryRequiredProperties = Maps.newHashMap();
-
- @JsonProperty("expected-result")
- private ExpectedResultsDto expectedResultsDtos;
-
- public String getStoredQuery() {
- return storedQuery;
- }
-
- public void setStoredQuery(String storedQuery) {
- this.storedQuery = storedQuery;
- }
-
- public List<LinkedHashMap<String, String>> getVerticesDtos() {
- return verticesDtos;
- }
-
- public void setVerticesDtos(List<LinkedHashMap<String, String>> verticesDtos) {
- this.verticesDtos = verticesDtos;
- }
-
- public List<LinkedHashMap<String, String>> getEdgesDtos() {
- return edgesDtos;
- }
-
- public void setEdgesDtos(List<LinkedHashMap<String, String>> edgesDtos) {
- this.edgesDtos = edgesDtos;
- }
-
- public Map<String, String> getQueryOptionalProperties() {
- return queryOptionalProperties;
- }
-
- public void setQueryOptionalProperties(
- Map<String, String> queryOptionalProperties) {
- this.queryOptionalProperties = queryOptionalProperties;
- }
-
- public Map<String, String> getQueryRequiredProperties() {
- return queryRequiredProperties;
- }
-
- public void setQueryRequiredProperties(
- Map<String, String> queryRequiredProperties) {
- this.queryRequiredProperties = queryRequiredProperties;
- }
-
- public ExpectedResultsDto getExpectedResultsDtos() {
- return expectedResultsDtos;
- }
-
- public void setExpectedResultsDtos(ExpectedResultsDto expectedResultsDtos) {
- this.expectedResultsDtos = expectedResultsDtos;
- }
-
-
+
+ @JsonProperty("stored-query")
+ private String storedQuery;
+
+ @JsonProperty("vertices")
+ private List<LinkedHashMap<String, String>> verticesDtos;
+
+ @JsonProperty("edges")
+ private List<LinkedHashMap<String, String>> edgesDtos;
+
+ @JsonProperty("optional-properties")
+ private Map<String, String> queryOptionalProperties = Maps.newHashMap();
+
+ @JsonProperty("required-properties")
+ private Map<String, String> queryRequiredProperties = Maps.newHashMap();
+
+ @JsonProperty("expected-result")
+ private ExpectedResultsDto expectedResultsDtos;
+
+ public String getStoredQuery() {
+ return storedQuery;
+ }
+
+ public void setStoredQuery(String storedQuery) {
+ this.storedQuery = storedQuery;
+ }
+
+ public List<LinkedHashMap<String, String>> getVerticesDtos() {
+ return verticesDtos;
+ }
+
+ public void setVerticesDtos(List<LinkedHashMap<String, String>> verticesDtos) {
+ this.verticesDtos = verticesDtos;
+ }
+
+ public List<LinkedHashMap<String, String>> getEdgesDtos() {
+ return edgesDtos;
+ }
+
+ public void setEdgesDtos(List<LinkedHashMap<String, String>> edgesDtos) {
+ this.edgesDtos = edgesDtos;
+ }
+
+ public Map<String, String> getQueryOptionalProperties() {
+ return queryOptionalProperties;
+ }
+
+ public void setQueryOptionalProperties(Map<String, String> queryOptionalProperties) {
+ this.queryOptionalProperties = queryOptionalProperties;
+ }
+
+ public Map<String, String> getQueryRequiredProperties() {
+ return queryRequiredProperties;
+ }
+
+ public void setQueryRequiredProperties(Map<String, String> queryRequiredProperties) {
+ this.queryRequiredProperties = queryRequiredProperties;
+ }
+
+ public ExpectedResultsDto getExpectedResultsDtos() {
+ return expectedResultsDtos;
+ }
+
+ public void setExpectedResultsDtos(ExpectedResultsDto expectedResultsDtos) {
+ this.expectedResultsDtos = expectedResultsDtos;
+ }
+
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/ExpectedResultsDto.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/ExpectedResultsDto.java
index 9c4c3b0..cda93fb 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/ExpectedResultsDto.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/ExpectedResultsDto.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -20,20 +20,20 @@
package org.onap.aai.rest.search;
-import java.util.List;
-
import com.fasterxml.jackson.annotation.JsonProperty;
+import java.util.List;
+
public class ExpectedResultsDto {
- @JsonProperty("ids")
- List<String> ids;
+ @JsonProperty("ids")
+ List<String> ids;
+
+ public List<String> getIds() {
+ return ids;
+ }
- public List<String> getIds() {
- return ids;
- }
+ public void setIds(List<String> ids) {
+ this.ids = ids;
+ }
- public void setIds(List<String> ids) {
- this.ids = ids;
- }
-
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/GenericQueryProcessor.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/GenericQueryProcessor.java
index 8e62900..d63b910 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/GenericQueryProcessor.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/GenericQueryProcessor.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,9 +19,17 @@
*/
package org.onap.aai.rest.search;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.att.eelf.configuration.EELFManager;
+
+import java.io.FileNotFoundException;
+import java.net.URI;
+import java.util.*;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
+
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
+
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
@@ -39,422 +47,431 @@ import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.serialization.queryformats.Format;
import org.onap.aai.serialization.queryformats.SubGraphStyle;
-
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
-import java.io.FileNotFoundException;
-import java.net.URI;
-import java.util.*;
-import java.util.regex.Matcher;
-import java.util.regex.Pattern;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public abstract class GenericQueryProcessor {
- private static Logger LOGGER = LoggerFactory.getLogger(GenericQueryProcessor.class);
-
- protected final Optional<URI> uri;
- protected final MultivaluedMap<String, String> queryParams;
- protected final Optional<Collection<Vertex>> vertices;
- protected static Pattern p = Pattern.compile("query/(.*+)");
- protected Optional<String> gremlin;
- protected final TransactionalGraphEngine dbEngine;
- protected GremlinServerSingleton gremlinServerSingleton;
- protected GroovyQueryBuilder groovyQueryBuilder = new GroovyQueryBuilder();
- protected final boolean isGremlin;
- protected Optional<DslQueryProcessor> dslQueryProcessorOptional;
-
- public Map<String, List<String>> getPropertiesMap() {
- return propertiesList;
- }
-
- public void setPropertiesMap(Map<String, List<String>> propertiesMap) {
- this.propertiesList = propertiesMap;
- }
-
- private Map<String, List<String>> propertiesList;
- /* dsl parameters to store dsl query and to check
-
- * if this is a DSL request
- */
- protected Optional<String> dsl;
- protected final boolean isDsl ;
- protected boolean isHistory;
- protected GraphTraversalSource traversalSource;
- protected QueryStyle style;
- protected QueryVersion dslApiVersion;
- protected Format format;
-
- protected GenericQueryProcessor(Builder builder) {
- this.uri = builder.getUri();
- this.dbEngine = builder.getDbEngine();
- this.vertices = builder.getVertices();
- this.gremlin = builder.getGremlin();
- this.isGremlin = builder.isGremlin();
- this.dsl = builder.getDsl();
- this.isDsl = builder.isDsl();
- this.gremlinServerSingleton = builder.getGremlinServerSingleton();
- this.dslQueryProcessorOptional = builder.getDslQueryProcessor();
- this.dslApiVersion = builder.getDslApiVersion();
-
- if (uri.isPresent()) {
- queryParams = URITools.getQueryMap(uri.get());
- } else if (builder.getUriParams() != null) {
- queryParams = builder.getUriParams();
- } else {
- queryParams = new MultivaluedHashMap<>();
- }
- this.traversalSource = builder.getTraversalSource();
- this.style = builder.getStyle();
- this.isHistory = builder.isHistory();
- this.format = builder.getFormat();
- }
-
- protected abstract GraphTraversal<?,?> runQuery(String query, Map<String, Object> params, GraphTraversalSource traversalSource);
-
- protected List<Object> processSubGraph(SubGraphStyle style, GraphTraversal<?,?> g) {
- final List<Object> resultVertices = new Vector<>();
- g.store("y");
-
- if (SubGraphStyle.prune.equals(style) || SubGraphStyle.star.equals(style)) {
- g.barrier().bothE();
- if (SubGraphStyle.prune.equals(style)) {
- g.where(__.otherV().where(P.within("y")));
- }
- g.dedup().subgraph("subGraph").cap("subGraph").map(x -> (Graph)x.get()).next().traversal().V().forEachRemaining(x -> {
- resultVertices.add(x);
- });
- } else {
- resultVertices.addAll(g.toList());
- }
- return resultVertices;
- }
-
- public List<Object> execute(SubGraphStyle style) throws FileNotFoundException, AAIException {
- final List<Object> resultVertices;
-
- Pair<String, Map<String, Object>> tuple = this.createQuery();
- String query = tuple.getValue0();
- if (queryParams.containsKey("as-tree")) {
- if (queryParams.getFirst("as-tree").equalsIgnoreCase("true")) {
- if (this.isDsl) { // If dsl query and as-tree parameter is true, remove "end" concatenation and append tree.
- query = removeDslQueryEnd(query);
- }
- query = query.concat(".tree()"); // Otherwise, normal gremlin query will just append tree
- }
- }
- Map<String, Object> params = tuple.getValue1();
-
- if (query.equals("") && (vertices.isPresent() && vertices.get().isEmpty())) {
- //nothing to do, just exit
- return new ArrayList<>();
- }
- GraphTraversal<?,?> g = this.runQuery(query, params, traversalSource);
-
- resultVertices = this.processSubGraph(style, g);
-
- return resultVertices;
- }
-
- private String removeDslQueryEnd(String query) {
- String end = ".cap('x').unfold().dedup()";
- if (query.length() <= end.length()) {
- return query;
- }
- if (query.contains(end)) {
- int startIndex = query.length() - end.length();
- for (int i = 0; startIndex - i >= 0; i++) { // remove tailing instance
- startIndex = query.length() - end.length() - i;
- int lastIndex = query.length() - i;
- if (query.substring(startIndex, lastIndex).equals(end)) {
- query = query.substring(0, startIndex) + query.substring(lastIndex);
- break;
- }
- }
- }
- return query;
- }
-
- protected Pair<String, Map<String, Object>> createQuery() throws AAIException {
- Map<String, Object> params = new HashMap<>();
- String query = "";
- if (this.isGremlin) {
- query = gremlin.get();
-
- }else if (this.isDsl) {
- String dslUserQuery = dsl.get();
- if(dslQueryProcessorOptional.isPresent()){
- Map<String, Object>resultMap = dslQueryProcessorOptional.get().parseAaiQuery(dslApiVersion, dslUserQuery);
- String dslQuery = resultMap.get("query").toString();
- Object propMap = resultMap.get("propertiesMap");
- if (propMap instanceof Map) {
- Map<String, List<String>> newPropMap = new HashMap<String, List<String>>();
- newPropMap = (Map<String, List<String>>)propMap;
- setPropertiesMap(newPropMap);
- }
- query = groovyQueryBuilder.executeTraversal(dbEngine, dslQuery, params, style, traversalSource);
- String startPrefix = "g.V()";
- query = startPrefix + query;
- }
- LOGGER.debug("Converted to gremlin query\n {}", query);
- }else {
- Matcher m = p.matcher(uri.get().getPath());
- String queryName = "";
- List<String> optionalParameters = Collections.emptyList();
- if (m.find()) {
- queryName = m.group(1);
- CustomQueryConfig queryConfig = gremlinServerSingleton.getCustomQueryConfig(queryName);
- if ( queryConfig != null ) {
- query = queryConfig.getQuery();
- optionalParameters = queryConfig.getQueryOptionalProperties();
- }
- }
-
- for (String key : queryParams.keySet()) {
- params.put(key, queryParams.getFirst(key));
- if ( optionalParameters.contains(key) ){
- optionalParameters.remove(key);
- }
- }
-
- if (!optionalParameters.isEmpty()){
- MissingOptionalParameter missingParameter = MissingOptionalParameter.getInstance();
- for ( String key : optionalParameters ) {
- params.put(key, missingParameter);
- }
- }
-
- if (vertices.isPresent() && !vertices.get().isEmpty()) {
-
- // Get the vertices and convert them into object array
- // The reason for this was .V() takes in an array of objects
- // not a list of objects so that needs to be converted
+ private static Logger LOGGER = LoggerFactory.getLogger(GenericQueryProcessor.class);
+
+ protected final Optional<URI> uri;
+ protected final MultivaluedMap<String, String> queryParams;
+ protected final Optional<Collection<Vertex>> vertices;
+ protected static Pattern p = Pattern.compile("query/(.*+)");
+ protected Optional<String> gremlin;
+ protected final TransactionalGraphEngine dbEngine;
+ protected GremlinServerSingleton gremlinServerSingleton;
+ protected GroovyQueryBuilder groovyQueryBuilder = new GroovyQueryBuilder();
+ protected final boolean isGremlin;
+ protected Optional<DslQueryProcessor> dslQueryProcessorOptional;
+
+ public Map<String, List<String>> getPropertiesMap() {
+ return propertiesList;
+ }
+
+ public void setPropertiesMap(Map<String, List<String>> propertiesMap) {
+ this.propertiesList = propertiesMap;
+ }
+
+ private Map<String, List<String>> propertiesList;
+ /*
+ * dsl parameters to store dsl query and to check
+ *
+ * if this is a DSL request
+ */
+ protected Optional<String> dsl;
+ protected final boolean isDsl;
+ protected boolean isHistory;
+ protected GraphTraversalSource traversalSource;
+ protected QueryStyle style;
+ protected QueryVersion dslApiVersion;
+ protected Format format;
+
+ protected GenericQueryProcessor(Builder builder) {
+ this.uri = builder.getUri();
+ this.dbEngine = builder.getDbEngine();
+ this.vertices = builder.getVertices();
+ this.gremlin = builder.getGremlin();
+ this.isGremlin = builder.isGremlin();
+ this.dsl = builder.getDsl();
+ this.isDsl = builder.isDsl();
+ this.gremlinServerSingleton = builder.getGremlinServerSingleton();
+ this.dslQueryProcessorOptional = builder.getDslQueryProcessor();
+ this.dslApiVersion = builder.getDslApiVersion();
+
+ if (uri.isPresent()) {
+ queryParams = URITools.getQueryMap(uri.get());
+ } else if (builder.getUriParams() != null) {
+ queryParams = builder.getUriParams();
+ } else {
+ queryParams = new MultivaluedHashMap<>();
+ }
+ this.traversalSource = builder.getTraversalSource();
+ this.style = builder.getStyle();
+ this.isHistory = builder.isHistory();
+ this.format = builder.getFormat();
+ }
+
+ protected abstract GraphTraversal<?, ?> runQuery(String query, Map<String, Object> params,
+ GraphTraversalSource traversalSource);
+
+ protected List<Object> processSubGraph(SubGraphStyle style, GraphTraversal<?, ?> g) {
+ final List<Object> resultVertices = new Vector<>();
+ g.store("y");
+
+ if (SubGraphStyle.prune.equals(style) || SubGraphStyle.star.equals(style)) {
+ g.barrier().bothE();
+ if (SubGraphStyle.prune.equals(style)) {
+ g.where(__.otherV().where(P.within("y")));
+ }
+ g.dedup().subgraph("subGraph").cap("subGraph").map(x -> (Graph) x.get()).next()
+ .traversal().V().forEachRemaining(x -> {
+ resultVertices.add(x);
+ });
+ } else {
+ resultVertices.addAll(g.toList());
+ }
+ return resultVertices;
+ }
+
+ public List<Object> execute(SubGraphStyle style) throws FileNotFoundException, AAIException {
+ final List<Object> resultVertices;
+
+ Pair<String, Map<String, Object>> tuple = this.createQuery();
+ String query = tuple.getValue0();
+ if (queryParams.containsKey("as-tree")) {
+ if (queryParams.getFirst("as-tree").equalsIgnoreCase("true")) {
+ if (this.isDsl) { // If dsl query and as-tree parameter is true, remove "end"
+ // concatenation and append tree.
+ query = removeDslQueryEnd(query);
+ }
+ query = query.concat(".tree()"); // Otherwise, normal gremlin query will just append
+ // tree
+ }
+ }
+ Map<String, Object> params = tuple.getValue1();
+
+ if (query.equals("") && (vertices.isPresent() && vertices.get().isEmpty())) {
+ // nothing to do, just exit
+ return new ArrayList<>();
+ }
+ GraphTraversal<?, ?> g = this.runQuery(query, params, traversalSource);
+
+ resultVertices = this.processSubGraph(style, g);
+
+ return resultVertices;
+ }
+
+ private String removeDslQueryEnd(String query) {
+ String end = ".cap('x').unfold().dedup()";
+ if (query.length() <= end.length()) {
+ return query;
+ }
+ if (query.contains(end)) {
+ int startIndex = query.length() - end.length();
+ for (int i = 0; startIndex - i >= 0; i++) { // remove tailing instance
+ startIndex = query.length() - end.length() - i;
+ int lastIndex = query.length() - i;
+ if (query.substring(startIndex, lastIndex).equals(end)) {
+ query = query.substring(0, startIndex) + query.substring(lastIndex);
+ break;
+ }
+ }
+ }
+ return query;
+ }
+
+ protected Pair<String, Map<String, Object>> createQuery() throws AAIException {
+ Map<String, Object> params = new HashMap<>();
+ String query = "";
+ if (this.isGremlin) {
+ query = gremlin.get();
+
+ } else if (this.isDsl) {
+ String dslUserQuery = dsl.get();
+ if (dslQueryProcessorOptional.isPresent()) {
+ Map<String, Object> resultMap =
+ dslQueryProcessorOptional.get().parseAaiQuery(dslApiVersion, dslUserQuery);
+ String dslQuery = resultMap.get("query").toString();
+ Object propMap = resultMap.get("propertiesMap");
+ if (propMap instanceof Map) {
+ Map<String, List<String>> newPropMap = new HashMap<String, List<String>>();
+ newPropMap = (Map<String, List<String>>) propMap;
+ setPropertiesMap(newPropMap);
+ }
+ query = groovyQueryBuilder.executeTraversal(dbEngine, dslQuery, params, style,
+ traversalSource);
+ String startPrefix = "g.V()";
+ query = startPrefix + query;
+ }
+ LOGGER.debug("Converted to gremlin query\n {}", query);
+ } else {
+ Matcher m = p.matcher(uri.get().getPath());
+ String queryName = "";
+ List<String> optionalParameters = Collections.emptyList();
+ if (m.find()) {
+ queryName = m.group(1);
+ CustomQueryConfig queryConfig =
+ gremlinServerSingleton.getCustomQueryConfig(queryName);
+ if (queryConfig != null) {
+ query = queryConfig.getQuery();
+ optionalParameters = queryConfig.getQueryOptionalProperties();
+ }
+ }
+
+ for (String key : queryParams.keySet()) {
+ params.put(key, queryParams.getFirst(key));
+ if (optionalParameters.contains(key)) {
+ optionalParameters.remove(key);
+ }
+ }
+
+ if (!optionalParameters.isEmpty()) {
+ MissingOptionalParameter missingParameter = MissingOptionalParameter.getInstance();
+ for (String key : optionalParameters) {
+ params.put(key, missingParameter);
+ }
+ }
+
+ if (vertices.isPresent() && !vertices.get().isEmpty()) {
+
+ // Get the vertices and convert them into object array
+ // The reason for this was .V() takes in an array of objects
+ // not a list of objects so that needs to be converted
// Also instead of statically creating the list which is a bad practice
- // We are binding the array dynamically to the groovy processor correctly
- // This will fix the memory issue of the method size too big
- // as statically creating a list string and passing is not appropriate
+ // We are binding the array dynamically to the groovy processor correctly
+ // This will fix the memory issue of the method size too big
+ // as statically creating a list string and passing is not appropriate
- Object [] startVertices = vertices.get().toArray();
+ Object[] startVertices = vertices.get().toArray();
- params.put("startVertexes", startVertices);
+ params.put("startVertexes", startVertices);
- if (query == null) {
- query = "";
- } else {
- query = groovyQueryBuilder.executeTraversal(dbEngine, query, params, style, traversalSource);
- }
+ if (query == null) {
+ query = "";
+ } else {
+ query = groovyQueryBuilder.executeTraversal(dbEngine, query, params, style,
+ traversalSource);
+ }
- String startPrefix = "g.V(startVertexes)";
+ String startPrefix = "g.V(startVertexes)";
- if (!"".equals(query)) {
- query = startPrefix + query;
- } else {
- query = startPrefix;
- }
+ if (!"".equals(query)) {
+ query = startPrefix + query;
+ } else {
+ query = startPrefix;
+ }
- // Getting all the vertices and logging them is not reasonable
- // As it could have performance impacts so doing a check here
- // to see if the logger is trace so only print the start vertexes
- // otherwise we would like to see what the gremlin query that was converted
+ // Getting all the vertices and logging them is not reasonable
+ // As it could have performance impacts so doing a check here
+ // to see if the logger is trace so only print the start vertexes
+ // otherwise we would like to see what the gremlin query that was converted
// So to check if the output matches the desired behavior
- // This way if to enable deeper logging, just changing logback would work
- if(LOGGER.isTraceEnabled()){
- String readQuery = query.replaceAll("startVertexes",
- Arrays.toString(startVertices).replaceAll("[^0-9,]", ""));
- LOGGER.trace("Converted to gremlin query including the start vertices \n {}", readQuery);
- }
- else if(LOGGER.isDebugEnabled()){
- LOGGER.debug("Converted to gremlin query without the start vertices \n {}", query);
- }
- } else {
- throw new AAIException("AAI_6148");
- }
-
- }
-
- return new Pair<>(query, params);
- }
-
- public static class Builder {
-
- private final TransactionalGraphEngine dbEngine;
- private Optional<URI> uri = Optional.empty();
- private Optional<String> gremlin = Optional.empty();
- private boolean isGremlin = false;
- private Optional<Collection<Vertex>> vertices = Optional.empty();
- private QueryProcessorType processorType = QueryProcessorType.GREMLIN_SERVER;
-
- private Optional<String> dsl = Optional.empty();
- private boolean isDsl = false;
- private DslQueryProcessor dslQueryProcessor;
- private GremlinServerSingleton gremlinServerSingleton;
- private Optional<String> nodeType = Optional.empty();
- private boolean isNodeTypeQuery = false;
- protected MultivaluedMap<String, String> uriParams;
- protected GraphTraversalSource traversalSource;
- protected boolean isHistory = false;
- protected QueryVersion dslApiVersion;
- protected Format format;
-
-
- protected QueryStyle style = QueryStyle.GREMLIN_TRAVERSAL;
-
- public Builder(TransactionalGraphEngine dbEngine, GremlinServerSingleton gremlinServerSingleton) {
- this.dbEngine = dbEngine;
- this.gremlinServerSingleton = gremlinServerSingleton;
- }
-
- public Builder queryFrom(URI uri) {
- this.uri = Optional.of(uri);
- this.isGremlin = false;
- return this;
- }
-
- public Builder startFrom(Collection<Vertex> vertices) {
- this.vertices = Optional.of(vertices);
- return this;
- }
-
- public Builder queryFrom( String query, String queryType) {
-
- if(queryType.equals("gremlin")){
- this.gremlin = Optional.of(query);
- this.isGremlin = true;
- }
- if(queryType.equals("dsl")){
- this.dsl = Optional.of(query);
- this.isDsl = true;
- }
- if(queryType.equals("nodeQuery")){
- this.nodeType = Optional.of(query);
- this.isNodeTypeQuery = true;
- }
- return this;
- }
-
- public Builder uriParams(MultivaluedMap<String, String> uriParams) {
- this.uriParams = uriParams;
- return this;
- }
-
- public Builder processWith(QueryProcessorType type) {
- this.processorType = type;
- return this;
- }
-
- public Builder format(Format format) {
- this.format = format;
- return this;
- }
-
- public Builder traversalSource(boolean isHistory, GraphTraversalSource source) {
- this.traversalSource = source;
- this.isHistory = isHistory;
- if(this.isHistory){
- this.style = QueryStyle.HISTORY_GREMLIN_TRAVERSAL;
- }
-
- return this;
- }
-
- public Builder queryProcessor(DslQueryProcessor dslQueryProcessor){
- this.dslQueryProcessor = dslQueryProcessor;
- return this;
- }
-
- public Builder version(QueryVersion version){
- this.dslApiVersion = version;
- return this;
- }
-
- public Optional<DslQueryProcessor> getDslQueryProcessor(){
- return Optional.ofNullable(this.dslQueryProcessor);
- }
- public TransactionalGraphEngine getDbEngine() {
- return dbEngine;
- }
-
- public Optional<URI> getUri() {
- return uri;
- }
-
- public MultivaluedMap<String, String> getUriParams() { return uriParams; }
-
- public Optional<String> getGremlin() {
- return gremlin;
- }
-
- public boolean isGremlin() {
- return isGremlin;
- }
-
- public Optional<String> getDsl() {
- return dsl;
- }
-
- public boolean isDsl() {
- return isDsl;
- }
-
- public Optional<Collection<Vertex>> getVertices() {
- return vertices;
- }
-
- public QueryProcessorType getProcessorType() {
- return processorType;
- }
-
- public GremlinServerSingleton getGremlinServerSingleton(){
- return gremlinServerSingleton;
- }
-
- public Optional<String> getNodeType() {
- return nodeType;
- }
-
- public boolean isNodeTypeQuery() {
- return isNodeTypeQuery;
- }
-
- public GenericQueryProcessor create() {
- if (isNodeTypeQuery()) {
- return new NodeQueryProcessor(this);
- }
- return new GroovyShellImpl(this);
- }
-
- public GraphTraversalSource getTraversalSource() {
- return traversalSource;
- }
-
- public void setTraversalSource(GraphTraversalSource traversalSource) {
- this.traversalSource = traversalSource;
- }
-
- public boolean isHistory() {
- return isHistory;
- }
-
- public void setHistory(boolean history) {
- isHistory = history;
- }
-
- public QueryStyle getStyle() {
- return style;
- }
-
- public void setStyle(QueryStyle style) {
- this.style = style;
- }
-
- public QueryVersion getDslApiVersion() {
- return dslApiVersion;
- }
-
- public void setDslApiVersion(QueryVersion dslApiVersion) {
- this.dslApiVersion = dslApiVersion;
- }
-
- public Format getFormat(){ return this.format; }
-
- }
+ // This way if to enable deeper logging, just changing logback would work
+ if (LOGGER.isTraceEnabled()) {
+ String readQuery = query.replaceAll("startVertexes",
+ Arrays.toString(startVertices).replaceAll("[^0-9,]", ""));
+ LOGGER.trace("Converted to gremlin query including the start vertices \n {}",
+ readQuery);
+ } else if (LOGGER.isDebugEnabled()) {
+ LOGGER.debug("Converted to gremlin query without the start vertices \n {}",
+ query);
+ }
+ } else {
+ throw new AAIException("AAI_6148");
+ }
+
+ }
+
+ return new Pair<>(query, params);
+ }
+
+ public static class Builder {
+
+ private final TransactionalGraphEngine dbEngine;
+ private Optional<URI> uri = Optional.empty();
+ private Optional<String> gremlin = Optional.empty();
+ private boolean isGremlin = false;
+ private Optional<Collection<Vertex>> vertices = Optional.empty();
+ private QueryProcessorType processorType = QueryProcessorType.GREMLIN_SERVER;
+
+ private Optional<String> dsl = Optional.empty();
+ private boolean isDsl = false;
+ private DslQueryProcessor dslQueryProcessor;
+ private GremlinServerSingleton gremlinServerSingleton;
+ private Optional<String> nodeType = Optional.empty();
+ private boolean isNodeTypeQuery = false;
+ protected MultivaluedMap<String, String> uriParams;
+ protected GraphTraversalSource traversalSource;
+ protected boolean isHistory = false;
+ protected QueryVersion dslApiVersion;
+ protected Format format;
+
+ protected QueryStyle style = QueryStyle.GREMLIN_TRAVERSAL;
+
+ public Builder(TransactionalGraphEngine dbEngine,
+ GremlinServerSingleton gremlinServerSingleton) {
+ this.dbEngine = dbEngine;
+ this.gremlinServerSingleton = gremlinServerSingleton;
+ }
+
+ public Builder queryFrom(URI uri) {
+ this.uri = Optional.of(uri);
+ this.isGremlin = false;
+ return this;
+ }
+
+ public Builder startFrom(Collection<Vertex> vertices) {
+ this.vertices = Optional.of(vertices);
+ return this;
+ }
+
+ public Builder queryFrom(String query, String queryType) {
+
+ if (queryType.equals("gremlin")) {
+ this.gremlin = Optional.of(query);
+ this.isGremlin = true;
+ }
+ if (queryType.equals("dsl")) {
+ this.dsl = Optional.of(query);
+ this.isDsl = true;
+ }
+ if (queryType.equals("nodeQuery")) {
+ this.nodeType = Optional.of(query);
+ this.isNodeTypeQuery = true;
+ }
+ return this;
+ }
+
+ public Builder uriParams(MultivaluedMap<String, String> uriParams) {
+ this.uriParams = uriParams;
+ return this;
+ }
+
+ public Builder processWith(QueryProcessorType type) {
+ this.processorType = type;
+ return this;
+ }
+
+ public Builder format(Format format) {
+ this.format = format;
+ return this;
+ }
+
+ public Builder traversalSource(boolean isHistory, GraphTraversalSource source) {
+ this.traversalSource = source;
+ this.isHistory = isHistory;
+ if (this.isHistory) {
+ this.style = QueryStyle.HISTORY_GREMLIN_TRAVERSAL;
+ }
+
+ return this;
+ }
+
+ public Builder queryProcessor(DslQueryProcessor dslQueryProcessor) {
+ this.dslQueryProcessor = dslQueryProcessor;
+ return this;
+ }
+
+ public Builder version(QueryVersion version) {
+ this.dslApiVersion = version;
+ return this;
+ }
+
+ public Optional<DslQueryProcessor> getDslQueryProcessor() {
+ return Optional.ofNullable(this.dslQueryProcessor);
+ }
+
+ public TransactionalGraphEngine getDbEngine() {
+ return dbEngine;
+ }
+
+ public Optional<URI> getUri() {
+ return uri;
+ }
+
+ public MultivaluedMap<String, String> getUriParams() {
+ return uriParams;
+ }
+
+ public Optional<String> getGremlin() {
+ return gremlin;
+ }
+
+ public boolean isGremlin() {
+ return isGremlin;
+ }
+
+ public Optional<String> getDsl() {
+ return dsl;
+ }
+
+ public boolean isDsl() {
+ return isDsl;
+ }
+
+ public Optional<Collection<Vertex>> getVertices() {
+ return vertices;
+ }
+
+ public QueryProcessorType getProcessorType() {
+ return processorType;
+ }
+
+ public GremlinServerSingleton getGremlinServerSingleton() {
+ return gremlinServerSingleton;
+ }
+
+ public Optional<String> getNodeType() {
+ return nodeType;
+ }
+
+ public boolean isNodeTypeQuery() {
+ return isNodeTypeQuery;
+ }
+
+ public GenericQueryProcessor create() {
+ if (isNodeTypeQuery()) {
+ return new NodeQueryProcessor(this);
+ }
+ return new GroovyShellImpl(this);
+ }
+
+ public GraphTraversalSource getTraversalSource() {
+ return traversalSource;
+ }
+
+ public void setTraversalSource(GraphTraversalSource traversalSource) {
+ this.traversalSource = traversalSource;
+ }
+
+ public boolean isHistory() {
+ return isHistory;
+ }
+
+ public void setHistory(boolean history) {
+ isHistory = history;
+ }
+
+ public QueryStyle getStyle() {
+ return style;
+ }
+
+ public void setStyle(QueryStyle style) {
+ this.style = style;
+ }
+
+ public QueryVersion getDslApiVersion() {
+ return dslApiVersion;
+ }
+
+ public void setDslApiVersion(QueryVersion dslApiVersion) {
+ this.dslApiVersion = dslApiVersion;
+ }
+
+ public Format getFormat() {
+ return this.format;
+ }
+
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/GetCustomQueryConfig.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/GetCustomQueryConfig.java
index 76ecd20..98eb551 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/GetCustomQueryConfig.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/GetCustomQueryConfig.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,11 +19,6 @@
*/
package org.onap.aai.rest.search;
-import java.lang.reflect.Type;
-import java.util.ArrayList;
-import java.util.List;
-
-
import com.google.gson.Gson;
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
@@ -31,108 +26,108 @@ import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
import com.google.gson.reflect.TypeToken;
+import java.lang.reflect.Type;
+import java.util.ArrayList;
+import java.util.List;
+
public class GetCustomQueryConfig {
- private JsonArray storedQueries = null;
- private CustomQueryConfig customQueryConfig;
-
-
- private static final String QUERY_CONFIG = "query";
- private static final String REQUIRED_CONFIG = "required-properties";
- private static final String OPTIONAL_CONFIG = "optional-properties";
- private static final String STORED_QUERIES_CONFIG = "stored-queries";
- private static final String STORED_QUERY_CONFIG = "stored-query";
-
- public GetCustomQueryConfig(String customQueryJson ) {
- init(customQueryJson);
- }
-
- private void init( String customQueryJson) {
- JsonParser parser = new JsonParser();
- JsonObject queriesObject = parser.parse(customQueryJson).getAsJsonObject();
- if (queriesObject.has(STORED_QUERIES_CONFIG)) {
-
- storedQueries = queriesObject.getAsJsonArray(STORED_QUERIES_CONFIG);
- }
- }
-
- private List<String> toStringList(JsonArray array) {
- Gson converter = new Gson();
- Type listType = new TypeToken<List<String>>() {}.getType();
- return converter.fromJson(array, listType);
- }
-
- private List<String> getPropertyList(JsonObject configObject, String config ) {
- JsonElement subqueryConfig;
- JsonArray props;
-
- if ( configObject.has(config)) {
- subqueryConfig = configObject.get(config);
- if ( subqueryConfig != null && !subqueryConfig.isJsonNull() ) {
- props = subqueryConfig.getAsJsonArray();
- if ( props != null ) {
- return toStringList(props);
- }
- }
- }
- return toStringList(null);
- }
-
- private void getStoredQueryBlock( JsonObject configObject, String config ) {
- if ( !configObject.has(config)) {
- customQueryConfig.setQueryRequiredProperties( new ArrayList<>() );
- customQueryConfig.setQueryOptionalProperties( new ArrayList<>() );
- return;
- }
-
- JsonElement queryConfig;
- JsonObject subObject;
- List<String> propertyList;
-
- queryConfig = configObject.get(config);
- subObject = queryConfig.getAsJsonObject();
- propertyList = getPropertyList(subObject, REQUIRED_CONFIG);
- if ( propertyList == null ) {
- propertyList = new ArrayList<>();
- }
- customQueryConfig.setQueryRequiredProperties( propertyList );
- propertyList = getPropertyList(subObject, OPTIONAL_CONFIG);
- if ( propertyList == null ) {
- propertyList = new ArrayList<>();
- }
- customQueryConfig.setQueryOptionalProperties( propertyList );
-
- }
-
-
- public CustomQueryConfig getStoredQuery(String queryName ) {
-
- customQueryConfig = null;
- JsonObject configObject;
- JsonElement query;
- JsonElement queryConfig;
-
- for (JsonElement storedQuery : storedQueries) {
- if (storedQuery.isJsonObject()) {
- JsonObject queryObject = storedQuery.getAsJsonObject();
- query = queryObject.get(queryName);
- if ( query != null ) {
- customQueryConfig = new CustomQueryConfig();
- configObject = query.getAsJsonObject();
- getStoredQueryBlock(configObject, QUERY_CONFIG);
- if ( configObject.has(STORED_QUERY_CONFIG)) {
- queryConfig = configObject.get(STORED_QUERY_CONFIG);
- customQueryConfig.setQuery(queryConfig.getAsString());
- }
- break;
- }
- }
- }
-
- return customQueryConfig;
-
- }
+ private JsonArray storedQueries = null;
+ private CustomQueryConfig customQueryConfig;
+
+ private static final String QUERY_CONFIG = "query";
+ private static final String REQUIRED_CONFIG = "required-properties";
+ private static final String OPTIONAL_CONFIG = "optional-properties";
+ private static final String STORED_QUERIES_CONFIG = "stored-queries";
+ private static final String STORED_QUERY_CONFIG = "stored-query";
+
+ public GetCustomQueryConfig(String customQueryJson) {
+ init(customQueryJson);
+ }
+
+ private void init(String customQueryJson) {
+ JsonParser parser = new JsonParser();
+ JsonObject queriesObject = parser.parse(customQueryJson).getAsJsonObject();
+ if (queriesObject.has(STORED_QUERIES_CONFIG)) {
+
+ storedQueries = queriesObject.getAsJsonArray(STORED_QUERIES_CONFIG);
+ }
+ }
+
+ private List<String> toStringList(JsonArray array) {
+ Gson converter = new Gson();
+ Type listType = new TypeToken<List<String>>() {}.getType();
+ return converter.fromJson(array, listType);
+ }
+
+ private List<String> getPropertyList(JsonObject configObject, String config) {
+ JsonElement subqueryConfig;
+ JsonArray props;
+
+ if (configObject.has(config)) {
+ subqueryConfig = configObject.get(config);
+ if (subqueryConfig != null && !subqueryConfig.isJsonNull()) {
+ props = subqueryConfig.getAsJsonArray();
+ if (props != null) {
+ return toStringList(props);
+ }
+ }
+ }
+ return toStringList(null);
+ }
+
+ private void getStoredQueryBlock(JsonObject configObject, String config) {
+ if (!configObject.has(config)) {
+ customQueryConfig.setQueryRequiredProperties(new ArrayList<>());
+ customQueryConfig.setQueryOptionalProperties(new ArrayList<>());
+ return;
+ }
+
+ JsonElement queryConfig;
+ JsonObject subObject;
+ List<String> propertyList;
+
+ queryConfig = configObject.get(config);
+ subObject = queryConfig.getAsJsonObject();
+ propertyList = getPropertyList(subObject, REQUIRED_CONFIG);
+ if (propertyList == null) {
+ propertyList = new ArrayList<>();
+ }
+ customQueryConfig.setQueryRequiredProperties(propertyList);
+ propertyList = getPropertyList(subObject, OPTIONAL_CONFIG);
+ if (propertyList == null) {
+ propertyList = new ArrayList<>();
+ }
+ customQueryConfig.setQueryOptionalProperties(propertyList);
+
+ }
+
+ public CustomQueryConfig getStoredQuery(String queryName) {
+
+ customQueryConfig = null;
+ JsonObject configObject;
+ JsonElement query;
+ JsonElement queryConfig;
+
+ for (JsonElement storedQuery : storedQueries) {
+ if (storedQuery.isJsonObject()) {
+ JsonObject queryObject = storedQuery.getAsJsonObject();
+ query = queryObject.get(queryName);
+ if (query != null) {
+ customQueryConfig = new CustomQueryConfig();
+ configObject = query.getAsJsonObject();
+ getStoredQueryBlock(configObject, QUERY_CONFIG);
+ if (configObject.has(STORED_QUERY_CONFIG)) {
+ queryConfig = configObject.get(STORED_QUERY_CONFIG);
+ customQueryConfig.setQuery(queryConfig.getAsString());
+ }
+ break;
+ }
+ }
+ }
+ return customQueryConfig;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/GremlinServerSingleton.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/GremlinServerSingleton.java
index e30f13f..a3bb074 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/GremlinServerSingleton.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/GremlinServerSingleton.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,16 +19,8 @@
*/
package org.onap.aai.rest.search;
-import org.onap.aai.logging.LogFormatTools;
-import org.onap.aai.util.AAIConstants;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.att.eelf.configuration.EELFManager;
-import org.apache.tinkerpop.gremlin.driver.Cluster;
-import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
-import javax.annotation.PostConstruct;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
@@ -41,6 +33,16 @@ import java.util.Properties;
import java.util.Timer;
import java.util.TimerTask;
+import javax.annotation.PostConstruct;
+
+import org.apache.tinkerpop.gremlin.driver.Cluster;
+import org.onap.aai.logging.LogFormatTools;
+import org.onap.aai.util.AAIConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Autowired;
+import org.springframework.beans.factory.annotation.Value;
+
public class GremlinServerSingleton {
private static Logger logger = LoggerFactory.getLogger(GremlinServerSingleton.class);
@@ -48,8 +50,8 @@ public class GremlinServerSingleton {
private boolean timerSet;
private Timer timer;
-
CQConfig customQueryInfo;
+
/**
* Initializes the gremlin server singleton
* Loads the configuration of the gremlin server and creates a cluster
@@ -60,29 +62,29 @@ public class GremlinServerSingleton {
*
*/
@Autowired
- public GremlinServerSingleton(CQConfig customQueryInfo){
- this.customQueryInfo = customQueryInfo;
+ public GremlinServerSingleton(CQConfig customQueryInfo) {
+ this.customQueryInfo = customQueryInfo;
}
/**
* Gets the query using CustomQueryConfig
+ *
* @param key
* @return
*/
- public String getStoredQueryFromConfig(String key){
+ public String getStoredQueryFromConfig(String key) {
GetCustomQueryConfig queryConfig = customQueryInfo.getCustomQueryConfig();
- CustomQueryConfig customQueryConfig = queryConfig.getStoredQuery(key);
- if ( customQueryConfig == null ) {
- return null;
- }
- return customQueryConfig.getQuery();
+ CustomQueryConfig customQueryConfig = queryConfig.getStoredQuery(key);
+ if (customQueryConfig == null) {
+ return null;
+ }
+ return customQueryConfig.getQuery();
}
-
+
public CustomQueryConfig getCustomQueryConfig(String key) {
GetCustomQueryConfig queryConfig = customQueryInfo.getCustomQueryConfig();
- return queryConfig.getStoredQuery(key);
+ return queryConfig.getStoredQuery(key);
}
-
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/GroovyShellImpl.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/GroovyShellImpl.java
index 340c525..126d754 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/GroovyShellImpl.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/GroovyShellImpl.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -21,36 +21,35 @@ package org.onap.aai.rest.search;
import java.util.Map;
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
+import javax.ws.rs.core.MultivaluedHashMap;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.onap.aai.aailog.logs.AaiDBTraversalMetricLog;
import org.onap.aai.restcore.search.GremlinGroovyShell;
import org.onap.aai.restcore.util.URITools;
import org.onap.aai.util.AAIConstants;
-import javax.ws.rs.core.MultivaluedHashMap;
-
public class GroovyShellImpl extends GenericQueryProcessor {
- protected GroovyShellImpl(Builder builder) {
- super(builder);
- }
-
- @Override
- protected GraphTraversal<?,?> runQuery(String query, Map<String, Object> params, GraphTraversalSource traversalSource) {
+ protected GroovyShellImpl(Builder builder) {
+ super(builder);
+ }
- AaiDBTraversalMetricLog metricLog = new AaiDBTraversalMetricLog (AAIConstants.AAI_TRAVERSAL_MS);
- metricLog.pre(uri);
+ @Override
+ protected GraphTraversal<?, ?> runQuery(String query, Map<String, Object> params,
+ GraphTraversalSource traversalSource) {
- params.put("g", traversalSource);
- GremlinGroovyShell shell = new GremlinGroovyShell();
- GraphTraversal<?,?> graphTraversal = shell.executeTraversal(query, params);
+ AaiDBTraversalMetricLog metricLog =
+ new AaiDBTraversalMetricLog(AAIConstants.AAI_TRAVERSAL_MS);
+ metricLog.pre(uri);
- metricLog.post();
- return graphTraversal;
- }
-
-}
+ params.put("g", traversalSource);
+ GremlinGroovyShell shell = new GremlinGroovyShell();
+ GraphTraversal<?, ?> graphTraversal = shell.executeTraversal(query, params);
+ metricLog.post();
+ return graphTraversal;
+ }
+}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/LocalCQConfig.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/LocalCQConfig.java
index 42d88af..ebf49d7 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/LocalCQConfig.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/LocalCQConfig.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,16 +19,8 @@
*/
package org.onap.aai.rest.search;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.logging.ErrorLogHelper;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.att.eelf.configuration.EELFManager;
-import org.onap.aai.logging.LogFormatTools;
-import org.onap.aai.util.AAIConstants;
-import org.springframework.beans.factory.annotation.Value;
-import javax.annotation.PostConstruct;
import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
@@ -38,6 +30,16 @@ import java.util.Date;
import java.util.Timer;
import java.util.TimerTask;
+import javax.annotation.PostConstruct;
+
+import org.onap.aai.exceptions.AAIException;
+import org.onap.aai.logging.ErrorLogHelper;
+import org.onap.aai.logging.LogFormatTools;
+import org.onap.aai.util.AAIConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.beans.factory.annotation.Value;
+
public class LocalCQConfig extends CQConfig {
private static Logger logger = LoggerFactory.getLogger(LocalCQConfig.class);
@@ -51,7 +53,8 @@ public class LocalCQConfig extends CQConfig {
public void init() {
try {
- String filepath = storedQueriesLocation + AAIConstants.AAI_FILESEP + "stored-queries.json";
+ String filepath =
+ storedQueriesLocation + AAIConstants.AAI_FILESEP + "stored-queries.json";
logger.info("Using the Local stored queries");
Path path = Paths.get(filepath);
String customQueryConfigJson = new String(Files.readAllBytes(path));
@@ -60,7 +63,8 @@ public class LocalCQConfig extends CQConfig {
} catch (IOException e) {
AAIException aaiException = new AAIException("AAI_4002", e);
ErrorLogHelper.logException(aaiException);
- //logger.error("Error occurred during the processing of query json file: " + LogFormatTools.getStackTop(e));
+ // logger.error("Error occurred during the processing of query json file: " +
+ // LogFormatTools.getStackTop(e));
}
TimerTask task = new FileWatcher(new File(storedQueriesLocation)) {
@@ -75,7 +79,8 @@ public class LocalCQConfig extends CQConfig {
} catch (IOException e) {
AAIException aaiException = new AAIException("AAI_4002", e);
ErrorLogHelper.logException(aaiException);
- //logger.error("Error occurred during the processing of query json file: " + LogFormatTools.getStackTop(e));
+ // logger.error("Error occurred during the processing of query json file: " +
+ // LogFormatTools.getStackTop(e));
}
}
};
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/ModelAndNamedQueryRestProvider.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/ModelAndNamedQueryRestProvider.java
index 821cb09..5c8b055 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/ModelAndNamedQueryRestProvider.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/ModelAndNamedQueryRestProvider.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,12 +19,23 @@
*/
package org.onap.aai.rest.search;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.Optional;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.POST;
+import javax.ws.rs.Path;
+import javax.ws.rs.Produces;
+import javax.ws.rs.QueryParam;
+import javax.ws.rs.core.*;
+import javax.ws.rs.core.Response.Status;
+
import org.onap.aai.aailog.logs.AaiDBTraversalMetricLog;
import org.onap.aai.concurrent.AaiCallable;
import org.onap.aai.dbgraphmap.SearchGraph;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.logging.ErrorLogHelper;
-
import org.onap.aai.rest.util.AAIExtensionMap;
import org.onap.aai.restcore.HttpMethod;
import org.onap.aai.restcore.RESTAPI;
@@ -35,17 +46,6 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.POST;
-import javax.ws.rs.Path;
-import javax.ws.rs.Produces;
-import javax.ws.rs.QueryParam;
-import javax.ws.rs.core.*;
-import javax.ws.rs.core.Response.Status;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.Optional;
-
/**
* Implements the search subdomain in the REST API. All API calls must include
* X-FromAppId and X-TransactionId in the header.
@@ -54,213 +54,199 @@ import java.util.Optional;
@Path("/search")
public class ModelAndNamedQueryRestProvider extends RESTAPI {
- private static final Logger LOGGER = LoggerFactory.getLogger(ModelAndNamedQueryRestProvider.class);
-
- public static final String NAMED_QUERY = "/named-query";
-
- public static final String MODEL_QUERY = "/model";
-
-
- private SearchGraph searchGraph;
-
- private SchemaVersions schemaVersions;
-
- @Autowired
- public ModelAndNamedQueryRestProvider(SearchGraph searchGraph, SchemaVersions schemaVersions){
- this.searchGraph = searchGraph;
- this.schemaVersions = schemaVersions;
- }
-
- /**
- * Gets the named query response.
- *
- * @param headers the headers
- * @param req the req
- * @param queryParameters the query parameters
- * @return the named query response
- */
- /* ---------------- Start Named Query --------------------- */
- @POST
- @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
- @Path(NAMED_QUERY)
- public Response getNamedQueryResponse(@Context HttpHeaders headers,
- @Context HttpServletRequest req,
- String queryParameters,
- @Context UriInfo info) {
- return runner(TraversalConstants.AAI_TRAVERSAL_TIMEOUT_ENABLED,
- TraversalConstants.AAI_TRAVERSAL_TIMEOUT_APP,
- TraversalConstants.AAI_TRAVERSAL_TIMEOUT_LIMIT,
- headers,
- info,
- HttpMethod.GET,
- new AaiCallable<Response>() {
- @Override
- public Response process() {
- return processNamedQueryResponse(headers, req, queryParameters);
- }
- }
- );
- }
-
- public Response processNamedQueryResponse(@Context HttpHeaders headers,
- @Context HttpServletRequest req,
- String queryParameters) {
- AAIException ex = null;
- Response response;
- String fromAppId;
- String transId;
-
- ArrayList<String> templateVars = new ArrayList<>();
- try {
- fromAppId = getFromAppId(headers);
- transId = getTransId(headers);
-
- AAIExtensionMap aaiExtMap = new AAIExtensionMap();
- aaiExtMap.setHttpHeaders(headers);
- aaiExtMap.setServletRequest(req);
- aaiExtMap.setApiVersion(schemaVersions.getDefaultVersion().toString());
- //only consider header value for search
-
-
- AaiDBTraversalMetricLog metricLog = new AaiDBTraversalMetricLog (AAIConstants.AAI_TRAVERSAL_MS);
- String uriString = req.getRequestURI();
- Optional<URI> o;
- if (uriString != null) {
- o = Optional.of(new URI(uriString));
- }
- else {
- o = Optional.empty();
- }
- metricLog.pre(o);
-
- response = searchGraph.runNamedQuery(fromAppId, transId, queryParameters, aaiExtMap);
- metricLog.post();
-
- } catch (AAIException e) {
- // send error response
- ex = e;
- templateVars.add("POST Search");
- templateVars.add("getNamedQueryResponse");
- response = Response
- .status(e.getErrorObject().getHTTPResponseCode())
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars))
- .build();
- } catch (Exception e) {
- // send error response
- ex = new AAIException("AAI_4000", e);
- templateVars.add("POST Search");
- templateVars.add("getNamedQueryResponse");
- response = Response
- .status(Status.INTERNAL_SERVER_ERROR)
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
- .build();
- } finally {
- // log success or failure
- if (ex != null) {
- ErrorLogHelper.logException(ex);
- }
- }
- return response;
- }
-
- /**
- * Gets the model query response.
- *
- * @param headers the headers
- * @param req the req
- * @param inboundPayload the inbound payload
- * @param action the action
- * @return the model query response
- */
- /* ---------------- Start Named Query --------------------- */
- @POST
- @Produces({ MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML })
- @Path(MODEL_QUERY)
- public Response getModelQueryResponse(@Context HttpHeaders headers,
- @Context HttpServletRequest req,
- String inboundPayload,
- @QueryParam("action") String action,
- @Context UriInfo info) {
- return runner(TraversalConstants.AAI_TRAVERSAL_TIMEOUT_ENABLED,
- TraversalConstants.AAI_TRAVERSAL_TIMEOUT_APP,
- TraversalConstants.AAI_TRAVERSAL_TIMEOUT_LIMIT,
- headers,
- info,
- HttpMethod.GET,
- new AaiCallable<Response>() {
- @Override
- public Response process() {
- return processModelQueryResponse(headers, req, inboundPayload, action);
- }
- }
- );
- }
-
- public Response processModelQueryResponse(@Context HttpHeaders headers,
- @Context HttpServletRequest req,
- String inboundPayload,
- @QueryParam("action") String action) {
- AAIException ex = null;
- Response response;
- String fromAppId;
- String transId;
- ArrayList<String> templateVars = new ArrayList<>();
- try {
- fromAppId = getFromAppId(headers);
- transId = getTransId(headers);
-
- AAIExtensionMap aaiExtMap = new AAIExtensionMap();
- aaiExtMap.setHttpHeaders(headers);
- aaiExtMap.setServletRequest(req);
- aaiExtMap.setApiVersion(schemaVersions.getDefaultVersion().toString());
- aaiExtMap.setFromAppId(fromAppId);
- aaiExtMap.setTransId(transId);
-
- //only consider header value for search
-
-
- AaiDBTraversalMetricLog metricLog = new AaiDBTraversalMetricLog (AAIConstants.AAI_TRAVERSAL_MS);
- String uriString = req.getRequestURI();
- Optional<URI> o;
- if (uriString != null) {
- o = Optional.of(new URI(uriString));
- }
- else {
- o = Optional.empty();
- }
- metricLog.pre(o);
- if (action != null && action.equalsIgnoreCase("DELETE")) {
- response = searchGraph.executeModelOperation(fromAppId, transId, inboundPayload, true, aaiExtMap);
- } else {
- response = searchGraph.executeModelOperation(fromAppId, transId, inboundPayload, false, aaiExtMap);
- }
- metricLog.post();
-
- } catch (AAIException e) {
- // send error response
- ex = e;
- templateVars.add("POST Search");
- templateVars.add("getModelQueryResponse");
- response = Response
- .status(e.getErrorObject().getHTTPResponseCode())
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars))
- .build();
- } catch (Exception e) {
- // send error response
- ex = new AAIException("AAI_4000", e);
- templateVars.add("POST Search");
- templateVars.add("getModelQueryResponse");
- response = Response
- .status(Status.INTERNAL_SERVER_ERROR)
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
- .build();
- } finally {
- // log success or failure
- if (ex != null) {
- ErrorLogHelper.logException(ex);
- }
- }
- return response;
- }
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(ModelAndNamedQueryRestProvider.class);
+
+ public static final String NAMED_QUERY = "/named-query";
+
+ public static final String MODEL_QUERY = "/model";
+
+ private SearchGraph searchGraph;
+
+ private SchemaVersions schemaVersions;
+
+ @Autowired
+ public ModelAndNamedQueryRestProvider(SearchGraph searchGraph, SchemaVersions schemaVersions) {
+ this.searchGraph = searchGraph;
+ this.schemaVersions = schemaVersions;
+ }
+
+ /**
+ * Gets the named query response.
+ *
+ * @param headers the headers
+ * @param req the req
+ * @param queryParameters the query parameters
+ * @return the named query response
+ */
+ /* ---------------- Start Named Query --------------------- */
+ @POST
+ @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
+ @Path(NAMED_QUERY)
+ public Response getNamedQueryResponse(@Context HttpHeaders headers,
+ @Context HttpServletRequest req, String queryParameters, @Context UriInfo info) {
+ return runner(TraversalConstants.AAI_TRAVERSAL_TIMEOUT_ENABLED,
+ TraversalConstants.AAI_TRAVERSAL_TIMEOUT_APP,
+ TraversalConstants.AAI_TRAVERSAL_TIMEOUT_LIMIT, headers, info, HttpMethod.GET,
+ new AaiCallable<Response>() {
+ @Override
+ public Response process() {
+ return processNamedQueryResponse(headers, req, queryParameters);
+ }
+ });
+ }
+
+ public Response processNamedQueryResponse(@Context HttpHeaders headers,
+ @Context HttpServletRequest req, String queryParameters) {
+ AAIException ex = null;
+ Response response;
+ String fromAppId;
+ String transId;
+
+ ArrayList<String> templateVars = new ArrayList<>();
+ try {
+ fromAppId = getFromAppId(headers);
+ transId = getTransId(headers);
+
+ AAIExtensionMap aaiExtMap = new AAIExtensionMap();
+ aaiExtMap.setHttpHeaders(headers);
+ aaiExtMap.setServletRequest(req);
+ aaiExtMap.setApiVersion(schemaVersions.getDefaultVersion().toString());
+ // only consider header value for search
+
+ AaiDBTraversalMetricLog metricLog =
+ new AaiDBTraversalMetricLog(AAIConstants.AAI_TRAVERSAL_MS);
+ String uriString = req.getRequestURI();
+ Optional<URI> o;
+ if (uriString != null) {
+ o = Optional.of(new URI(uriString));
+ } else {
+ o = Optional.empty();
+ }
+ metricLog.pre(o);
+
+ response = searchGraph.runNamedQuery(fromAppId, transId, queryParameters, aaiExtMap);
+ metricLog.post();
+
+ } catch (AAIException e) {
+ // send error response
+ ex = e;
+ templateVars.add("POST Search");
+ templateVars.add("getNamedQueryResponse");
+ response = Response
+ .status(e.getErrorObject().getHTTPResponseCode()).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars))
+ .build();
+ } catch (Exception e) {
+ // send error response
+ ex = new AAIException("AAI_4000", e);
+ templateVars.add("POST Search");
+ templateVars.add("getNamedQueryResponse");
+ response = Response
+ .status(Status.INTERNAL_SERVER_ERROR).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
+ .build();
+ } finally {
+ // log success or failure
+ if (ex != null) {
+ ErrorLogHelper.logException(ex);
+ }
+ }
+ return response;
+ }
+
+ /**
+ * Gets the model query response.
+ *
+ * @param headers the headers
+ * @param req the req
+ * @param inboundPayload the inbound payload
+ * @param action the action
+ * @return the model query response
+ */
+ /* ---------------- Start Named Query --------------------- */
+ @POST
+ @Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
+ @Path(MODEL_QUERY)
+ public Response getModelQueryResponse(@Context HttpHeaders headers,
+ @Context HttpServletRequest req, String inboundPayload, @QueryParam("action") String action,
+ @Context UriInfo info) {
+ return runner(TraversalConstants.AAI_TRAVERSAL_TIMEOUT_ENABLED,
+ TraversalConstants.AAI_TRAVERSAL_TIMEOUT_APP,
+ TraversalConstants.AAI_TRAVERSAL_TIMEOUT_LIMIT, headers, info, HttpMethod.GET,
+ new AaiCallable<Response>() {
+ @Override
+ public Response process() {
+ return processModelQueryResponse(headers, req, inboundPayload, action);
+ }
+ });
+ }
+
+ public Response processModelQueryResponse(@Context HttpHeaders headers,
+ @Context HttpServletRequest req, String inboundPayload,
+ @QueryParam("action") String action) {
+ AAIException ex = null;
+ Response response;
+ String fromAppId;
+ String transId;
+ ArrayList<String> templateVars = new ArrayList<>();
+ try {
+ fromAppId = getFromAppId(headers);
+ transId = getTransId(headers);
+
+ AAIExtensionMap aaiExtMap = new AAIExtensionMap();
+ aaiExtMap.setHttpHeaders(headers);
+ aaiExtMap.setServletRequest(req);
+ aaiExtMap.setApiVersion(schemaVersions.getDefaultVersion().toString());
+ aaiExtMap.setFromAppId(fromAppId);
+ aaiExtMap.setTransId(transId);
+
+ // only consider header value for search
+
+ AaiDBTraversalMetricLog metricLog =
+ new AaiDBTraversalMetricLog(AAIConstants.AAI_TRAVERSAL_MS);
+ String uriString = req.getRequestURI();
+ Optional<URI> o;
+ if (uriString != null) {
+ o = Optional.of(new URI(uriString));
+ } else {
+ o = Optional.empty();
+ }
+ metricLog.pre(o);
+ if (action != null && action.equalsIgnoreCase("DELETE")) {
+ response = searchGraph.executeModelOperation(fromAppId, transId, inboundPayload,
+ true, aaiExtMap);
+ } else {
+ response = searchGraph.executeModelOperation(fromAppId, transId, inboundPayload,
+ false, aaiExtMap);
+ }
+ metricLog.post();
+
+ } catch (AAIException e) {
+ // send error response
+ ex = e;
+ templateVars.add("POST Search");
+ templateVars.add("getModelQueryResponse");
+ response = Response
+ .status(e.getErrorObject().getHTTPResponseCode()).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars))
+ .build();
+ } catch (Exception e) {
+ // send error response
+ ex = new AAIException("AAI_4000", e);
+ templateVars.add("POST Search");
+ templateVars.add("getModelQueryResponse");
+ response = Response
+ .status(Status.INTERNAL_SERVER_ERROR).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
+ .build();
+ } finally {
+ // log success or failure
+ if (ex != null) {
+ ErrorLogHelper.logException(ex);
+ }
+ }
+ return response;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/NodeQueryProcessor.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/NodeQueryProcessor.java
index 366e7df..fc3847e 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/NodeQueryProcessor.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/NodeQueryProcessor.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,11 +19,15 @@
*/
package org.onap.aai.rest.search;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
import edu.emory.mathcs.backport.java.util.concurrent.TimeUnit;
+import java.io.FileNotFoundException;
+import java.util.*;
+import java.util.regex.Pattern;
+
+import javax.ws.rs.core.MultivaluedHashMap;
+import javax.ws.rs.core.MultivaluedMap;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.javatuples.Pair;
@@ -31,87 +35,84 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.restcore.search.GroovyQueryBuilder;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.serialization.queryformats.SubGraphStyle;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
-import java.io.FileNotFoundException;
-import java.util.*;
-import java.util.regex.Pattern;
+public class NodeQueryProcessor extends GroovyShellImpl {
-import javax.ws.rs.core.MultivaluedHashMap;
-import javax.ws.rs.core.MultivaluedMap;
+ private static Logger logger = LoggerFactory.getLogger(NodeQueryProcessor.class);
-public class NodeQueryProcessor extends GroovyShellImpl {
+ protected String nodeType;
+ private MultivaluedMap<String, String> nodeQueryParams = new MultivaluedHashMap<>();
+ protected final Optional<Collection<Vertex>> vertices;
+ protected static Pattern p = Pattern.compile("query/(.*+)");
+ protected Optional<String> gremlin;
+ protected final TransactionalGraphEngine dbEngine;
+ protected GroovyQueryBuilder queryBuilder = new GroovyQueryBuilder();
+
+ protected NodeQueryProcessor(Builder builder) {
+ super(builder);
+ this.nodeQueryParams = builder.uriParams;
+ if (builder.getNodeType().isPresent()) {
+ this.nodeType = builder.getNodeType().get();
+ }
+ this.dbEngine = builder.getDbEngine();
+ this.vertices = builder.getVertices();
+
+ }
+
+ public Pair<String, Map<String, Object>> createQuery() throws AAIException {
+ Map<String, Object> params = new HashMap<>();
+
+ Long timeNowInMilliSecs = System.currentTimeMillis();
+ Long startTime = 0L;
+ if (nodeQueryParams.containsKey("hours")) {
+ Long hoursInMilliSec =
+ TimeUnit.HOURS.toMillis(Long.parseLong(nodeQueryParams.getFirst("hours")));
+ startTime = timeNowInMilliSecs - hoursInMilliSec;
+ } else if (nodeQueryParams.containsKey("date-time")) {
+ Long dateTime = Long.parseLong(nodeQueryParams.getFirst("date-time"));
+ startTime = dateTime;
+ }
+
+ String query = "builder.getVerticesByProperty('aai-node-type', nodeType)"
+ + ".or(builder.newInstance().getVerticesGreaterThanProperty('aai-created-ts',startTime),"
+ + " builder.newInstance().getVerticesGreaterThanProperty('aai-last-mod-ts',startTime)"
+ + ")";
+
+ params.put("startTime", startTime);
+ params.put("nodeType", nodeType);
+
+ query = queryBuilder.executeTraversal(dbEngine, query, params);
+
+ String startPrefix = "g.V()";
+
+ query = startPrefix + query;
+
+ if (logger.isDebugEnabled()) {
+ logger.debug("Converted to gremlin query without the start vertices \n {}", query);
+ }
+
+ return new Pair<>(query, params);
+ }
+
+ public List<Object> execute(SubGraphStyle style) throws FileNotFoundException, AAIException {
+ final List<Object> resultVertices = new Vector<>();
+
+ Pair<String, Map<String, Object>> tuple = this.createQuery();
+ String query = tuple.getValue0();
+ Map<String, Object> params = tuple.getValue1();
+
+ if (query.equals("")) {
+ // nothing to do, just exit
+ return new ArrayList<>();
+ }
+ GraphTraversal<?, ?> g =
+ this.runQuery(query, params, dbEngine.asAdmin().getTraversalSource());
+
+ resultVertices.addAll(g.toList());
- private static Logger logger = LoggerFactory.getLogger(NodeQueryProcessor.class);
-
- protected String nodeType;
- private MultivaluedMap<String, String> nodeQueryParams = new MultivaluedHashMap<>();
- protected final Optional<Collection<Vertex>> vertices;
- protected static Pattern p = Pattern.compile("query/(.*+)");
- protected Optional<String> gremlin;
- protected final TransactionalGraphEngine dbEngine;
- protected GroovyQueryBuilder queryBuilder = new GroovyQueryBuilder();
-
- protected NodeQueryProcessor(Builder builder) {
- super(builder);
- this.nodeQueryParams = builder.uriParams;
- if(builder.getNodeType().isPresent()) {
- this.nodeType = builder.getNodeType().get();
- }
- this.dbEngine = builder.getDbEngine();
- this.vertices = builder.getVertices();
-
- }
-
- public Pair<String, Map<String, Object>> createQuery() throws AAIException {
- Map<String, Object> params = new HashMap<>();
-
- Long timeNowInMilliSecs = System.currentTimeMillis();
- Long startTime = 0L;
- if(nodeQueryParams.containsKey("hours")){
- Long hoursInMilliSec = TimeUnit.HOURS.toMillis(Long.parseLong(nodeQueryParams.getFirst("hours")));
- startTime = timeNowInMilliSecs - hoursInMilliSec;
- }
- else if(nodeQueryParams.containsKey("date-time")){
- Long dateTime = Long.parseLong(nodeQueryParams.getFirst("date-time"));
- startTime = dateTime;
- }
-
- String query = "builder.getVerticesByProperty('aai-node-type', nodeType)"
- + ".or(builder.newInstance().getVerticesGreaterThanProperty('aai-created-ts',startTime),"
- + " builder.newInstance().getVerticesGreaterThanProperty('aai-last-mod-ts',startTime)" + ")";
-
- params.put("startTime", startTime);
- params.put("nodeType", nodeType);
-
- query = queryBuilder.executeTraversal(dbEngine, query, params);
-
- String startPrefix = "g.V()";
-
- query = startPrefix + query;
-
- if (logger.isDebugEnabled()) {
- logger.debug("Converted to gremlin query without the start vertices \n {}", query);
- }
-
- return new Pair<>(query, params);
- }
-
- public List<Object> execute(SubGraphStyle style) throws FileNotFoundException, AAIException {
- final List<Object> resultVertices = new Vector<>();
-
- Pair<String, Map<String, Object>> tuple = this.createQuery();
- String query = tuple.getValue0();
- Map<String, Object> params = tuple.getValue1();
-
- if (query.equals("")) {
- // nothing to do, just exit
- return new ArrayList<>();
- }
- GraphTraversal<?, ?> g = this.runQuery(query, params, dbEngine.asAdmin().getTraversalSource());
-
- resultVertices.addAll(g.toList());
-
- return resultVertices;
- }
+ return resultVertices;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/QueryProcessorType.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/QueryProcessorType.java
index c8e1d14..8e4c7cf 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/QueryProcessorType.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/QueryProcessorType.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -21,6 +21,5 @@ package org.onap.aai.rest.search;
public enum QueryProcessorType {
- GREMLIN_SERVER,
- LOCAL_GROOVY
+ GREMLIN_SERVER, LOCAL_GROOVY
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/SchemaServiceCQConfig.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/SchemaServiceCQConfig.java
index ea1b62f..49986de 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/SchemaServiceCQConfig.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/SchemaServiceCQConfig.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,19 +19,21 @@
*/
package org.onap.aai.rest.search;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
import com.att.eelf.configuration.EELFManager;
+
+import java.util.HashMap;
+import java.util.Map;
+
+import javax.annotation.PostConstruct;
+
import org.onap.aai.restclient.RestClient;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.beans.factory.annotation.Value;
import org.springframework.beans.factory.annotation.Qualifier;
+import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
-import javax.annotation.PostConstruct;
-import java.util.HashMap;
-import java.util.Map;
-
public class SchemaServiceCQConfig extends CQConfig {
private static Logger logger = LoggerFactory.getLogger(SchemaServiceCQConfig.class);
@@ -46,19 +48,20 @@ public class SchemaServiceCQConfig extends CQConfig {
@PostConstruct
public void initialize() {
- //Call SchemaService to get custom queries
+ // Call SchemaService to get custom queries
retrieveCustomQueries();
}
public void retrieveCustomQueries() {
- /*
- Call Schema MS to get custom queries using RestTemplate
- */
+ /*
+ * Call Schema MS to get custom queries using RestTemplate
+ */
logger.info("Calling the SchemaService to retrieve stored queries");
String content = "";
Map<String, String> headersMap = new HashMap<>();
- ResponseEntity<String> schemaResponse = restClient.getGetRequest(content, customQueriesUri, headersMap);
+ ResponseEntity<String> schemaResponse =
+ restClient.getGetRequest(content, customQueriesUri, headersMap);
queryConfig = new GetCustomQueryConfig(schemaResponse.getBody());
}
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/search/SearchProvider.java b/aai-traversal/src/main/java/org/onap/aai/rest/search/SearchProvider.java
index 1db2699..17edbc5 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/search/SearchProvider.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/search/SearchProvider.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -20,6 +20,17 @@
package org.onap.aai.rest.search;
import io.micrometer.core.annotation.Timed;
+
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.Optional;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.*;
+import javax.ws.rs.core.*;
+import javax.ws.rs.core.Response.Status;
+
import org.onap.aai.aailog.logs.AaiDBTraversalMetricLog;
import org.onap.aai.concurrent.AaiCallable;
import org.onap.aai.dbgraphmap.SearchGraph;
@@ -46,15 +57,6 @@ import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.*;
-import javax.ws.rs.core.*;
-import javax.ws.rs.core.Response.Status;
-import java.net.URI;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.Optional;
-
/**
* Implements the search subdomain in the REST API. All API calls must include X-FromAppId and
* X-TransactionId in the header.
@@ -78,8 +80,8 @@ public class SearchProvider extends RESTAPI {
private String basePath;
@Autowired
- public SearchProvider(LoaderFactory loaderFactory, SearchGraph searchGraph, SchemaVersions schemaVersions,
- @Value("${schema.uri.base.path}") String basePath) {
+ public SearchProvider(LoaderFactory loaderFactory, SearchGraph searchGraph,
+ SchemaVersions schemaVersions, @Value("${schema.uri.base.path}") String basePath) {
this.loaderFactory = loaderFactory;
this.searchGraph = searchGraph;
this.schemaVersions = schemaVersions;
@@ -101,27 +103,29 @@ public class SearchProvider extends RESTAPI {
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path(GENERIC_QUERY)
- public Response getGenericQueryResponse(@Context HttpHeaders headers, @Context HttpServletRequest req,
- @QueryParam("start-node-type") final String startNodeType,
- @QueryParam("key") final List<String> startNodeKeyParams,
- @QueryParam("include") final List<String> includeNodeTypes, @QueryParam("depth") final int depth,
- @PathParam("version") String versionParam, @Context UriInfo info) {
- return runner(TraversalConstants.AAI_TRAVERSAL_TIMEOUT_ENABLED, TraversalConstants.AAI_TRAVERSAL_TIMEOUT_APP,
- TraversalConstants.AAI_TRAVERSAL_TIMEOUT_LIMIT, headers, info, HttpMethod.GET,
- new AaiCallable<Response>() {
- @Override
- public Response process() {
- return processGenericQueryResponse(headers, req, startNodeType, startNodeKeyParams,
- includeNodeTypes, depth, versionParam);
- }
- });
+ public Response getGenericQueryResponse(@Context HttpHeaders headers,
+ @Context HttpServletRequest req, @QueryParam("start-node-type") final String startNodeType,
+ @QueryParam("key") final List<String> startNodeKeyParams,
+ @QueryParam("include") final List<String> includeNodeTypes,
+ @QueryParam("depth") final int depth, @PathParam("version") String versionParam,
+ @Context UriInfo info) {
+ return runner(TraversalConstants.AAI_TRAVERSAL_TIMEOUT_ENABLED,
+ TraversalConstants.AAI_TRAVERSAL_TIMEOUT_APP,
+ TraversalConstants.AAI_TRAVERSAL_TIMEOUT_LIMIT, headers, info, HttpMethod.GET,
+ new AaiCallable<Response>() {
+ @Override
+ public Response process() {
+ return processGenericQueryResponse(headers, req, startNodeType,
+ startNodeKeyParams, includeNodeTypes, depth, versionParam);
+ }
+ });
}
- public Response processGenericQueryResponse(@Context HttpHeaders headers, @Context HttpServletRequest req,
- @QueryParam("start-node-type") final String startNodeType,
- @QueryParam("key") final List<String> startNodeKeyParams,
- @QueryParam("include") final List<String> includeNodeTypes, @QueryParam("depth") final int depth,
- @PathParam("version") String versionParam) {
+ public Response processGenericQueryResponse(@Context HttpHeaders headers,
+ @Context HttpServletRequest req, @QueryParam("start-node-type") final String startNodeType,
+ @QueryParam("key") final List<String> startNodeKeyParams,
+ @QueryParam("include") final List<String> includeNodeTypes,
+ @QueryParam("depth") final int depth, @PathParam("version") String versionParam) {
AAIException ex = null;
Response searchResult;
@@ -137,17 +141,20 @@ public class SearchProvider extends RESTAPI {
final ModelType factoryType = ModelType.MOXY;
Loader loader = loaderFactory.createLoaderForVersion(factoryType, version);
- TransactionalGraphEngine dbEngine = new JanusGraphDBEngine(QueryStyle.TRAVERSAL, loader);
+ TransactionalGraphEngine dbEngine =
+ new JanusGraphDBEngine(QueryStyle.TRAVERSAL, loader);
DBSerializer dbSerializer = new DBSerializer(version, dbEngine, factoryType, fromAppId);
- UrlBuilder urlBuilder = new UrlBuilder(version, dbSerializer, schemaVersions, this.basePath);
+ UrlBuilder urlBuilder =
+ new UrlBuilder(version, dbSerializer, schemaVersions, this.basePath);
- AaiDBTraversalMetricLog metricLog = new AaiDBTraversalMetricLog (AAIConstants.AAI_TRAVERSAL_MS);
+ AaiDBTraversalMetricLog metricLog =
+ new AaiDBTraversalMetricLog(AAIConstants.AAI_TRAVERSAL_MS);
metricLog.pre(Optional.of(new URI(req.getRequestURI())));
- searchResult = searchGraph
- .runGenericQuery(new GenericQueryBuilder().setHeaders(headers).setStartNodeType(startNodeType)
- .setStartNodeKeyParams(startNodeKeyParams).setIncludeNodeTypes(includeNodeTypes)
- .setDepth(depth).setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
+ searchResult = searchGraph.runGenericQuery(new GenericQueryBuilder().setHeaders(headers)
+ .setStartNodeType(startNodeType).setStartNodeKeyParams(startNodeKeyParams)
+ .setIncludeNodeTypes(includeNodeTypes).setDepth(depth).setDbEngine(dbEngine)
+ .setLoader(loader).setUrlBuilder(urlBuilder));
metricLog.post();
@@ -156,17 +163,19 @@ public class SearchProvider extends RESTAPI {
ex = e;
templateVars.add("GET Search");
templateVars.add("getGenericQueryResponse");
- searchResult = Response.status(e.getErrorObject().getHTTPResponseCode())
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars))
- .build();
+ searchResult = Response
+ .status(e.getErrorObject().getHTTPResponseCode()).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars))
+ .build();
} catch (Exception e) {
// send error response
ex = new AAIException("AAI_4000", e);
templateVars.add("GET Search");
templateVars.add("getGenericQueryResponse");
- searchResult = Response.status(Status.INTERNAL_SERVER_ERROR)
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
- .build();
+ searchResult = Response
+ .status(Status.INTERNAL_SERVER_ERROR).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
+ .build();
} finally {
// log success or failure
if (ex != null) {
@@ -193,28 +202,32 @@ public class SearchProvider extends RESTAPI {
@GET
@Produces({MediaType.APPLICATION_JSON, MediaType.APPLICATION_XML})
@Path(NODES_QUERY)
- public Response getNodesQueryResponse(@Context HttpHeaders headers, @Context HttpServletRequest req,
- @QueryParam("search-node-type") final String searchNodeType,
- @QueryParam("edge-filter") final List<String> edgeFilterList,
- @QueryParam("filter") final List<String> filterList, @PathParam("version") String versionParam,
- @Context UriInfo info)
+ public Response getNodesQueryResponse(@Context HttpHeaders headers,
+ @Context HttpServletRequest req,
+ @QueryParam("search-node-type") final String searchNodeType,
+ @QueryParam("edge-filter") final List<String> edgeFilterList,
+ @QueryParam("filter") final List<String> filterList,
+ @PathParam("version") String versionParam, @Context UriInfo info)
{
- return runner(TraversalConstants.AAI_TRAVERSAL_TIMEOUT_ENABLED, TraversalConstants.AAI_TRAVERSAL_TIMEOUT_APP,
- TraversalConstants.AAI_TRAVERSAL_TIMEOUT_LIMIT, headers, info, HttpMethod.GET,
- new AaiCallable<Response>() {
- @Override
- public Response process() {
- return processNodesQueryResponse(headers, req, searchNodeType, edgeFilterList, filterList,
- versionParam);
- }
- });
+ return runner(TraversalConstants.AAI_TRAVERSAL_TIMEOUT_ENABLED,
+ TraversalConstants.AAI_TRAVERSAL_TIMEOUT_APP,
+ TraversalConstants.AAI_TRAVERSAL_TIMEOUT_LIMIT, headers, info, HttpMethod.GET,
+ new AaiCallable<Response>() {
+ @Override
+ public Response process() {
+ return processNodesQueryResponse(headers, req, searchNodeType, edgeFilterList,
+ filterList, versionParam);
+ }
+ });
}
- public Response processNodesQueryResponse(@Context HttpHeaders headers, @Context HttpServletRequest req,
- @QueryParam("search-node-type") final String searchNodeType,
- @QueryParam("edge-filter") final List<String> edgeFilterList,
- @QueryParam("filter") final List<String> filterList, @PathParam("version") String versionParam) {
+ public Response processNodesQueryResponse(@Context HttpHeaders headers,
+ @Context HttpServletRequest req,
+ @QueryParam("search-node-type") final String searchNodeType,
+ @QueryParam("edge-filter") final List<String> edgeFilterList,
+ @QueryParam("filter") final List<String> filterList,
+ @PathParam("version") String versionParam) {
AAIException ex = null;
Response searchResult;
@@ -231,15 +244,18 @@ public class SearchProvider extends RESTAPI {
final ModelType factoryType = ModelType.MOXY;
Loader loader = loaderFactory.createLoaderForVersion(factoryType, version);
- TransactionalGraphEngine dbEngine = new JanusGraphDBEngine(QueryStyle.TRAVERSAL, loader);
+ TransactionalGraphEngine dbEngine =
+ new JanusGraphDBEngine(QueryStyle.TRAVERSAL, loader);
DBSerializer dbSerializer = new DBSerializer(version, dbEngine, factoryType, fromAppId);
- UrlBuilder urlBuilder = new UrlBuilder(version, dbSerializer, schemaVersions, this.basePath);
-
+ UrlBuilder urlBuilder =
+ new UrlBuilder(version, dbSerializer, schemaVersions, this.basePath);
- AaiDBTraversalMetricLog metricLog = new AaiDBTraversalMetricLog (AAIConstants.AAI_TRAVERSAL_MS);
+ AaiDBTraversalMetricLog metricLog =
+ new AaiDBTraversalMetricLog(AAIConstants.AAI_TRAVERSAL_MS);
metricLog.pre(Optional.of(new URI(req.getRequestURI())));
- searchResult = searchGraph.runNodesQuery(new NodesQueryBuilder().setHeaders(headers)
- .setTargetNodeType(searchNodeType).setEdgeFilterParams(edgeFilterList).setFilterParams(filterList)
+ searchResult = searchGraph.runNodesQuery(
+ new NodesQueryBuilder().setHeaders(headers).setTargetNodeType(searchNodeType)
+ .setEdgeFilterParams(edgeFilterList).setFilterParams(filterList)
.setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
metricLog.post();
@@ -249,17 +265,19 @@ public class SearchProvider extends RESTAPI {
ex = e;
templateVars.add("GET Search");
templateVars.add("getNodesQueryResponse");
- searchResult = Response.status(e.getErrorObject().getHTTPResponseCode())
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars))
- .build();
+ searchResult = Response
+ .status(e.getErrorObject().getHTTPResponseCode()).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars))
+ .build();
} catch (Exception e) {
// send error response
ex = new AAIException("AAI_4000", e);
templateVars.add("GET Search");
templateVars.add("getNodesQueryResponse");
- searchResult = Response.status(Status.INTERNAL_SERVER_ERROR)
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
- .build();
+ searchResult = Response
+ .status(Status.INTERNAL_SERVER_ERROR).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
+ .build();
} finally {
// log success or failure
if (ex != null) {
@@ -269,6 +287,4 @@ public class SearchProvider extends RESTAPI {
return searchResult;
}
-
-
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/security/WebSecurityConfig.java b/aai-traversal/src/main/java/org/onap/aai/rest/security/WebSecurityConfig.java
index c92d818..e24013b 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/security/WebSecurityConfig.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/security/WebSecurityConfig.java
@@ -11,7 +11,7 @@
* 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
+ * 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,
@@ -23,6 +23,7 @@
* ============LICENSE_END=========================================================
*/
package org.onap.aai.rest.security;
+
import org.keycloak.adapters.springboot.KeycloakSpringBootConfigResolver;
import org.keycloak.adapters.springsecurity.KeycloakConfiguration;
import org.keycloak.adapters.springsecurity.authentication.KeycloakAuthenticationProvider;
@@ -40,35 +41,36 @@ import org.springframework.security.core.session.SessionRegistryImpl;
import org.springframework.security.web.authentication.session.RegisterSessionAuthenticationStrategy;
import org.springframework.security.web.authentication.session.SessionAuthenticationStrategy;
import org.springframework.security.web.session.HttpSessionEventPublisher;
+
@Profile("keycloak")
@KeycloakConfiguration
@Import({KeycloakSpringBootConfigResolver.class})
public class WebSecurityConfig extends KeycloakWebSecurityConfigurerAdapter {
@Autowired
public void configureGlobal(AuthenticationManagerBuilder auth) {
- KeycloakAuthenticationProvider keycloakAuthenticationProvider
- = keycloakAuthenticationProvider();
- keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(
- new SimpleAuthorityMapper());
+ KeycloakAuthenticationProvider keycloakAuthenticationProvider =
+ keycloakAuthenticationProvider();
+ keycloakAuthenticationProvider.setGrantedAuthoritiesMapper(new SimpleAuthorityMapper());
auth.authenticationProvider(keycloakAuthenticationProvider);
}
+
@Bean
public ServletListenerRegistrationBean<HttpSessionEventPublisher> httpSessionEventPublisher() {
return new ServletListenerRegistrationBean<>(new HttpSessionEventPublisher());
}
+
@Bean
@Override
protected SessionAuthenticationStrategy sessionAuthenticationStrategy() {
- return new RegisterSessionAuthenticationStrategy(
- new SessionRegistryImpl());
+ return new RegisterSessionAuthenticationStrategy(new SessionRegistryImpl());
}
+
@Override
protected void configure(HttpSecurity http) throws Exception {
super.configure(http);
- http.authorizeRequests()
- .antMatchers("/**")
- .permitAll().and().csrf().disable();
+ http.authorizeRequests().antMatchers("/**").permitAll().and().csrf().disable();
}
+
@Override
public void configure(WebSecurity web) throws Exception {
web.ignoring().regexMatchers("^.*/util/echo$");
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/util/AAIExtensionMap.java b/aai-traversal/src/main/java/org/onap/aai/rest/util/AAIExtensionMap.java
index 0aa70e3..4e5651d 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/util/AAIExtensionMap.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/util/AAIExtensionMap.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -20,6 +20,14 @@
package org.onap.aai.rest.util;
+import java.lang.reflect.Method;
+import java.util.ArrayList;
+import java.util.HashMap;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.HttpHeaders;
+import javax.ws.rs.core.UriInfo;
+
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.eclipse.persistence.jaxb.dynamic.DynamicJAXBContext;
@@ -29,13 +37,6 @@ import org.onap.aai.rest.db.DBRequest;
import org.onap.aai.rest.db.HttpEntry;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.HttpHeaders;
-import javax.ws.rs.core.UriInfo;
-import java.lang.reflect.Method;
-import java.util.ArrayList;
-import java.util.HashMap;
-
public class AAIExtensionMap {
// =======================================================================
// Attribute | Type
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/util/ConvertQueryPropertiesToJson.java b/aai-traversal/src/main/java/org/onap/aai/rest/util/ConvertQueryPropertiesToJson.java
index f16e700..f3ec5f8 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/util/ConvertQueryPropertiesToJson.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/util/ConvertQueryPropertiesToJson.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,86 +26,88 @@ import java.util.List;
import java.util.Properties;
public class ConvertQueryPropertiesToJson {
-
- private static final int MAX_FILE_SIZE = 256000;
-
- private void addStart( StringBuilder sb ) {
- sb.append("{\n \"stored-queries\":[{\n");
- }
-
- private void addRequiredQueryProperties( StringBuilder sb, List<String> rqd ) {
- Iterator it = rqd.iterator();
- sb.append(" \"query\":{\n \"required-properties\":[");
- while( it.hasNext()) {
- sb.append("\"" + it.next() + "\"");
- if ( it.hasNext()) {
- sb.append(",");
- }
- }
- sb.append("]\n },\n");
- }
-
- private void addAnotherQuery( StringBuilder sb, String queryName, String query, List<String> rqd ) {
- sb.append(" \"" + queryName + "\":{\n");
- if ( !rqd.isEmpty()) {
- addRequiredQueryProperties( sb, rqd);
- }
- sb.append(" \"stored-query\":\"" + query + "\"\n }\n },{\n");
- }
-
- private void addLastQuery( StringBuilder sb, String queryName, String query, List<String> rqd ) {
- sb.append(" \"" + queryName + "\":{\n");
- if ( !rqd.isEmpty() ) {
- addRequiredQueryProperties( sb, rqd);
- }
- sb.append(" \"stored-query\":\"" + query + "\"\n }\n }]\n}\n");
- }
-
- private String get2ndParameter( String paramString) {
- String endParams = paramString.substring(0, paramString.indexOf(')'));
- String result = endParams.substring(endParams.indexOf(',') + 1 );
- String lastParam = result.trim();
- if ( lastParam.startsWith("\\") || lastParam.startsWith("'") || lastParam.startsWith("new ") ){
- return null;
- }
-
- return lastParam;
- }
-
- private List<String> findRqdProperties( String query) {
- String[] parts = query.split("getVerticesByProperty");
- List<String> result = new ArrayList<>();
- if ( parts.length == 1 )
- return result;
- int count = 0;
- String foundRqdProperty;
- while ( count++ < parts.length - 1 ) {
- foundRqdProperty = get2ndParameter(parts[count]);
- if ( foundRqdProperty != null && !result.contains(foundRqdProperty)) {
- result.add(foundRqdProperty);
- }
- }
- return result;
- }
- public String convertProperties( Properties props ) {
- Enumeration<?> e = props.propertyNames();
- StringBuilder sb = new StringBuilder(MAX_FILE_SIZE);
- String queryName;
- String query;
- addStart( sb );
- List<String> rqd;
- while ( e.hasMoreElements()) {
- queryName = (String)e.nextElement();
- query = props.getProperty(queryName).trim().replace("\"", "\\\"");
- rqd = findRqdProperties( query);
- if ( e.hasMoreElements()) {
- addAnotherQuery( sb, queryName, query, rqd);
- } else {
- addLastQuery( sb, queryName, query, rqd);
- }
- }
-
+ private static final int MAX_FILE_SIZE = 256000;
+
+ private void addStart(StringBuilder sb) {
+ sb.append("{\n \"stored-queries\":[{\n");
+ }
+
+ private void addRequiredQueryProperties(StringBuilder sb, List<String> rqd) {
+ Iterator it = rqd.iterator();
+ sb.append(" \"query\":{\n \"required-properties\":[");
+ while (it.hasNext()) {
+ sb.append("\"" + it.next() + "\"");
+ if (it.hasNext()) {
+ sb.append(",");
+ }
+ }
+ sb.append("]\n },\n");
+ }
+
+ private void addAnotherQuery(StringBuilder sb, String queryName, String query,
+ List<String> rqd) {
+ sb.append(" \"" + queryName + "\":{\n");
+ if (!rqd.isEmpty()) {
+ addRequiredQueryProperties(sb, rqd);
+ }
+ sb.append(" \"stored-query\":\"" + query + "\"\n }\n },{\n");
+ }
+
+ private void addLastQuery(StringBuilder sb, String queryName, String query, List<String> rqd) {
+ sb.append(" \"" + queryName + "\":{\n");
+ if (!rqd.isEmpty()) {
+ addRequiredQueryProperties(sb, rqd);
+ }
+ sb.append(" \"stored-query\":\"" + query + "\"\n }\n }]\n}\n");
+ }
+
+ private String get2ndParameter(String paramString) {
+ String endParams = paramString.substring(0, paramString.indexOf(')'));
+ String result = endParams.substring(endParams.indexOf(',') + 1);
+ String lastParam = result.trim();
+ if (lastParam.startsWith("\\") || lastParam.startsWith("'")
+ || lastParam.startsWith("new ")) {
+ return null;
+ }
+
+ return lastParam;
+ }
+
+ private List<String> findRqdProperties(String query) {
+ String[] parts = query.split("getVerticesByProperty");
+ List<String> result = new ArrayList<>();
+ if (parts.length == 1)
+ return result;
+ int count = 0;
+ String foundRqdProperty;
+ while (count++ < parts.length - 1) {
+ foundRqdProperty = get2ndParameter(parts[count]);
+ if (foundRqdProperty != null && !result.contains(foundRqdProperty)) {
+ result.add(foundRqdProperty);
+ }
+ }
+ return result;
+ }
+
+ public String convertProperties(Properties props) {
+ Enumeration<?> e = props.propertyNames();
+ StringBuilder sb = new StringBuilder(MAX_FILE_SIZE);
+ String queryName;
+ String query;
+ addStart(sb);
+ List<String> rqd;
+ while (e.hasMoreElements()) {
+ queryName = (String) e.nextElement();
+ query = props.getProperty(queryName).trim().replace("\"", "\\\"");
+ rqd = findRqdProperties(query);
+ if (e.hasMoreElements()) {
+ addAnotherQuery(sb, queryName, query, rqd);
+ } else {
+ addLastQuery(sb, queryName, query, rqd);
+ }
+ }
+
return sb.toString();
- }
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/util/EchoResponse.java b/aai-traversal/src/main/java/org/onap/aai/rest/util/EchoResponse.java
index 16c2618..d0ba708 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/util/EchoResponse.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/util/EchoResponse.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -42,79 +42,79 @@ import org.onap.aai.restcore.RESTAPI;
*/
@Path("/util")
public class EchoResponse extends RESTAPI {
-
- protected static String authPolicyFunctionName = "util";
-
- public static final String ECHO_PATH = "/echo";
-
- /**
- * Simple health-check API that echos back the X-FromAppId and X-TransactionId to clients.
- * If there is a query string, a transaction gets logged into hbase, proving the application is connected to the data store.
- * If there is no query string, no transacction logging is done to hbase.
- *
- * @param headers the headers
- * @param req the req
- * @param myAction if exists will cause transaction to be logged to hbase
- * @return the response
- */
- @GET
- @Produces( { MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON })
- @Path(ECHO_PATH)
- public Response echoResult(@Context HttpHeaders headers, @Context HttpServletRequest req,
- @QueryParam("action") String myAction) {
- AAIException ex = null;
- Response response;
- String fromAppId;
- String transId;
-
- try {
- fromAppId = getFromAppId(headers );
- transId = getTransId(headers);
- } catch (AAIException e) {
- ArrayList<String> templateVars = new ArrayList<>();
- templateVars.add("PUT uebProvider");
- templateVars.add("addTopic");
- return Response
- .status(e.getErrorObject().getHTTPResponseCode())
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars))
- .build();
- }
-
- try {
-
- HashMap<AAIException, ArrayList<String>> exceptionList = new HashMap<>();
-
- ArrayList<String> templateVars = new ArrayList<>();
- templateVars.add(fromAppId);
- templateVars.add(transId);
-
- exceptionList.put(new AAIException("AAI_0002", "OK"), templateVars);
-
- response = Response.status(Status.OK)
- .entity(ErrorLogHelper.getRESTAPIInfoResponse(
- headers.getAcceptableMediaTypes(), exceptionList))
- .build();
-
- } catch (Exception e) {
- ex = new AAIException("AAI_4000", e);
- ArrayList<String> templateVars = new ArrayList<>();
- templateVars.add(Action.GET.name());
- templateVars.add(fromAppId +" "+transId);
-
- response = Response
- .status(Status.INTERNAL_SERVER_ERROR)
- .entity(ErrorLogHelper.getRESTAPIErrorResponse(
- headers.getAcceptableMediaTypes(), ex,
- templateVars)).build();
-
- } finally {
- if (ex != null) {
- ErrorLogHelper.logException(ex);
- }
-
- }
-
- return response;
- }
+
+ protected static String authPolicyFunctionName = "util";
+
+ public static final String ECHO_PATH = "/echo";
+
+ /**
+ * Simple health-check API that echos back the X-FromAppId and X-TransactionId to clients.
+ * If there is a query string, a transaction gets logged into hbase, proving the application is
+ * connected to the data store.
+ * If there is no query string, no transacction logging is done to hbase.
+ *
+ * @param headers the headers
+ * @param req the req
+ * @param myAction if exists will cause transaction to be logged to hbase
+ * @return the response
+ */
+ @GET
+ @Produces({MediaType.APPLICATION_XML, MediaType.APPLICATION_JSON})
+ @Path(ECHO_PATH)
+ public Response echoResult(@Context HttpHeaders headers, @Context HttpServletRequest req,
+ @QueryParam("action") String myAction) {
+ AAIException ex = null;
+ Response response;
+ String fromAppId;
+ String transId;
+
+ try {
+ fromAppId = getFromAppId(headers);
+ transId = getTransId(headers);
+ } catch (AAIException e) {
+ ArrayList<String> templateVars = new ArrayList<>();
+ templateVars.add("PUT uebProvider");
+ templateVars.add("addTopic");
+ return Response
+ .status(e.getErrorObject().getHTTPResponseCode()).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), e, templateVars))
+ .build();
+ }
+
+ try {
+
+ HashMap<AAIException, ArrayList<String>> exceptionList = new HashMap<>();
+
+ ArrayList<String> templateVars = new ArrayList<>();
+ templateVars.add(fromAppId);
+ templateVars.add(transId);
+
+ exceptionList.put(new AAIException("AAI_0002", "OK"), templateVars);
+
+ response = Response
+ .status(Status.OK).entity(ErrorLogHelper
+ .getRESTAPIInfoResponse(headers.getAcceptableMediaTypes(), exceptionList))
+ .build();
+
+ } catch (Exception e) {
+ ex = new AAIException("AAI_4000", e);
+ ArrayList<String> templateVars = new ArrayList<>();
+ templateVars.add(Action.GET.name());
+ templateVars.add(fromAppId + " " + transId);
+
+ response = Response
+ .status(Status.INTERNAL_SERVER_ERROR).entity(ErrorLogHelper
+ .getRESTAPIErrorResponse(headers.getAcceptableMediaTypes(), ex, templateVars))
+ .build();
+
+ } finally {
+ if (ex != null) {
+ ErrorLogHelper.logException(ex);
+ }
+
+ }
+
+ return response;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/util/LogFormatTools.java b/aai-traversal/src/main/java/org/onap/aai/rest/util/LogFormatTools.java
index 931ab0b..f7539a0 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/util/LogFormatTools.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/util/LogFormatTools.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -25,11 +25,11 @@ import java.time.format.DateTimeFormatter;
public class LogFormatTools {
- private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
- private static final DateTimeFormatter DTF = DateTimeFormatter.ofPattern(DATE_FORMAT)
- .withZone(ZoneOffset.UTC);
-
- public static String getCurrentDateTime() {
- return DTF.format(ZonedDateTime.now());
- }
+ private static final String DATE_FORMAT = "yyyy-MM-dd'T'HH:mm:ss.SSSZ";
+ private static final DateTimeFormatter DTF =
+ DateTimeFormatter.ofPattern(DATE_FORMAT).withZone(ZoneOffset.UTC);
+
+ public static String getCurrentDateTime() {
+ return DTF.format(ZonedDateTime.now());
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/rest/util/ValidateEncoding.java b/aai-traversal/src/main/java/org/onap/aai/rest/util/ValidateEncoding.java
index 7d04bf7..fcf7e42 100644
--- a/aai-traversal/src/main/java/org/onap/aai/rest/util/ValidateEncoding.java
+++ b/aai-traversal/src/main/java/org/onap/aai/rest/util/ValidateEncoding.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -32,131 +32,133 @@ import org.springframework.web.util.UriUtils;
*/
public class ValidateEncoding {
- private final String encoding = "UTF-8";
-
- /**
- * Instantiates a new validate encoding.
- */
- private ValidateEncoding() {
-
- }
-
- /**
- * The Class Helper.
- */
- private static class Helper {
-
- /** The Constant INSTANCE. */
- private static final ValidateEncoding INSTANCE = new ValidateEncoding();
- }
-
- /**
- * Gets the single instance of ValidateEncoding.
- *
- * @return single instance of ValidateEncoding
- */
- public static ValidateEncoding getInstance() {
- return Helper.INSTANCE;
- }
-
- /**
- * Validate.
- *
- * @param uri the uri
- * @return true, if successful
- * @throws UnsupportedEncodingException the unsupported encoding exception
- */
- public boolean validate(URI uri) throws UnsupportedEncodingException {
- boolean result = true;
- if (!validatePath(uri.getRawPath())) {
- result = false;
- }
- /*if (!validateQueryParams(uri.getRawQuery())) {
- result = false;
- } //TODO
- */
-
- return result;
- }
-
- /**
- * Validate.
- *
- * @param info the info
- * @return true, if successful
- * @throws UnsupportedEncodingException the unsupported encoding exception
- */
- public boolean validate(UriInfo info) throws UnsupportedEncodingException {
- boolean result = true;
- if (!validatePath(info.getPath(false))) {
- result = false;
- }
- if (!validateQueryParams(info.getQueryParameters(false))) {
- result = false;
- }
-
- return result;
- }
-
- /**
- * Validate path.
- *
- * @param path the path
- * @return true, if successful
- * @throws UnsupportedEncodingException the unsupported encoding exception
- */
- private boolean validatePath(String path) throws UnsupportedEncodingException {
- String[] segments = path.split("/");
- boolean valid = true;
- for (String segment : segments) {
- if (!this.checkEncoding(segment)) {
- valid = false;
- }
- }
-
- return valid;
-
- }
-
- /**
- * Validate query params.
- *
- * @param params the params
- * @return true, if successful
- * @throws UnsupportedEncodingException the unsupported encoding exception
- */
- private boolean validateQueryParams(MultivaluedMap<String, String> params) throws UnsupportedEncodingException {
- boolean valid = true;
-
- for (String key : params.keySet()) {
- if (!this.checkEncoding(key)) {
- valid = false;
- }
- for (String item : params.get(key)) {
- if(item.contains("+")){
- item = item.replaceAll("\\+", "%20");
- }
- if (!this.checkEncoding(item)) {
- valid = false;
- }
- }
- }
- return valid;
- }
-
- /**
- * Check encoding.
- *
- * @param segment the segment
- * @return true, if successful
- * @throws UnsupportedEncodingException the unsupported encoding exception
- */
- private boolean checkEncoding(String segment) throws UnsupportedEncodingException {
- boolean result = false;
- String decode = UriUtils.decode(segment, encoding);
- String encode = UriUtils.encode(decode, encoding);
- result = segment.equals(encode);
-
- return result;
- }
+ private final String encoding = "UTF-8";
+
+ /**
+ * Instantiates a new validate encoding.
+ */
+ private ValidateEncoding() {
+
+ }
+
+ /**
+ * The Class Helper.
+ */
+ private static class Helper {
+
+ /** The Constant INSTANCE. */
+ private static final ValidateEncoding INSTANCE = new ValidateEncoding();
+ }
+
+ /**
+ * Gets the single instance of ValidateEncoding.
+ *
+ * @return single instance of ValidateEncoding
+ */
+ public static ValidateEncoding getInstance() {
+ return Helper.INSTANCE;
+ }
+
+ /**
+ * Validate.
+ *
+ * @param uri the uri
+ * @return true, if successful
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ */
+ public boolean validate(URI uri) throws UnsupportedEncodingException {
+ boolean result = true;
+ if (!validatePath(uri.getRawPath())) {
+ result = false;
+ }
+ /*
+ * if (!validateQueryParams(uri.getRawQuery())) {
+ * result = false;
+ * } //TODO
+ */
+
+ return result;
+ }
+
+ /**
+ * Validate.
+ *
+ * @param info the info
+ * @return true, if successful
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ */
+ public boolean validate(UriInfo info) throws UnsupportedEncodingException {
+ boolean result = true;
+ if (!validatePath(info.getPath(false))) {
+ result = false;
+ }
+ if (!validateQueryParams(info.getQueryParameters(false))) {
+ result = false;
+ }
+
+ return result;
+ }
+
+ /**
+ * Validate path.
+ *
+ * @param path the path
+ * @return true, if successful
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ */
+ private boolean validatePath(String path) throws UnsupportedEncodingException {
+ String[] segments = path.split("/");
+ boolean valid = true;
+ for (String segment : segments) {
+ if (!this.checkEncoding(segment)) {
+ valid = false;
+ }
+ }
+
+ return valid;
+
+ }
+
+ /**
+ * Validate query params.
+ *
+ * @param params the params
+ * @return true, if successful
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ */
+ private boolean validateQueryParams(MultivaluedMap<String, String> params)
+ throws UnsupportedEncodingException {
+ boolean valid = true;
+
+ for (String key : params.keySet()) {
+ if (!this.checkEncoding(key)) {
+ valid = false;
+ }
+ for (String item : params.get(key)) {
+ if (item.contains("+")) {
+ item = item.replaceAll("\\+", "%20");
+ }
+ if (!this.checkEncoding(item)) {
+ valid = false;
+ }
+ }
+ }
+ return valid;
+ }
+
+ /**
+ * Check encoding.
+ *
+ * @param segment the segment
+ * @return true, if successful
+ * @throws UnsupportedEncodingException the unsupported encoding exception
+ */
+ private boolean checkEncoding(String segment) throws UnsupportedEncodingException {
+ boolean result = false;
+ String decode = UriUtils.decode(segment, encoding);
+ String encode = UriUtils.encode(decode, encoding);
+ result = segment.equals(encode);
+
+ return result;
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/service/AuthorizationService.java b/aai-traversal/src/main/java/org/onap/aai/service/AuthorizationService.java
index b4fa996..b448bc8 100644
--- a/aai-traversal/src/main/java/org/onap/aai/service/AuthorizationService.java
+++ b/aai-traversal/src/main/java/org/onap/aai/service/AuthorizationService.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,15 +19,6 @@
*/
package org.onap.aai.service;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import org.eclipse.jetty.util.security.Password;
-import org.onap.aai.Profiles;
-import org.onap.aai.util.AAIConstants;
-import org.springframework.context.annotation.Profile;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.PostConstruct;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
@@ -37,6 +28,16 @@ import java.util.HashMap;
import java.util.Map;
import java.util.stream.Stream;
+import javax.annotation.PostConstruct;
+
+import org.eclipse.jetty.util.security.Password;
+import org.onap.aai.Profiles;
+import org.onap.aai.util.AAIConstants;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.context.annotation.Profile;
+import org.springframework.stereotype.Service;
+
@Service
@Profile(Profiles.ONE_WAY_SSL)
public class AuthorizationService {
@@ -48,45 +49,47 @@ public class AuthorizationService {
private static final Base64.Encoder ENCODER = Base64.getEncoder();
@PostConstruct
- public void init(){
+ public void init() {
String basicAuthFile = getBasicAuthFilePath();
- try(Stream<String> stream = Files.lines(Paths.get(basicAuthFile))){
+ try (Stream<String> stream = Files.lines(Paths.get(basicAuthFile))) {
stream.filter(line -> !line.startsWith("#")).forEach(str -> {
- byte [] bytes = null;
+ byte[] bytes = null;
String usernamePassword = null;
String accessType = null;
- String [] userAccessType = str.split(",");
+ String[] userAccessType = str.split(",");
- if(userAccessType.length != 2){
- throw new RuntimeException("Please check the realm.properties file as it is not conforming to the basic auth");
+ if (userAccessType.length != 2) {
+ throw new RuntimeException(
+ "Please check the realm.properties file as it is not conforming to the basic auth");
}
usernamePassword = userAccessType[0];
- accessType = userAccessType[1];
+ accessType = userAccessType[1];
String[] usernamePasswordArray = usernamePassword.split(":");
- if(usernamePasswordArray.length != 3){
- throw new RuntimeException("This username / pwd is not a valid entry in realm.properties");
+ if (usernamePasswordArray.length != 3) {
+ throw new RuntimeException(
+ "This username / pwd is not a valid entry in realm.properties");
}
String username = usernamePasswordArray[0];
String password = null;
- if(str.contains("OBF:")){
+ if (str.contains("OBF:")) {
password = usernamePasswordArray[1] + ":" + usernamePasswordArray[2];
password = Password.deobfuscate(password);
}
- bytes = ENCODER.encode((username + ":" + password).getBytes(StandardCharsets.UTF_8));
+ bytes =
+ ENCODER.encode((username + ":" + password).getBytes(StandardCharsets.UTF_8));
authorizedUsers.put(new String(bytes), accessType);
-
authorizedUsers.put(new String(ENCODER.encode(bytes)), accessType);
});
} catch (IOException e) {
@@ -94,11 +97,12 @@ public class AuthorizationService {
}
}
- public boolean checkIfUserAuthorized(String authorization){
- return authorizedUsers.containsKey(authorization) && "admin".equals(authorizedUsers.get(authorization));
+ public boolean checkIfUserAuthorized(String authorization) {
+ return authorizedUsers.containsKey(authorization)
+ && "admin".equals(authorizedUsers.get(authorization));
}
- public String getBasicAuthFilePath(){
+ public String getBasicAuthFilePath() {
return AAIConstants.AAI_HOME_ETC_AUTH + AAIConstants.AAI_FILESEP + "realm.properties";
}
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/service/RetiredService.java b/aai-traversal/src/main/java/org/onap/aai/service/RetiredService.java
index 5989e31..b40c328 100644
--- a/aai-traversal/src/main/java/org/onap/aai/service/RetiredService.java
+++ b/aai-traversal/src/main/java/org/onap/aai/service/RetiredService.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,16 +19,17 @@
*/
package org.onap.aai.service;
-import org.springframework.beans.factory.annotation.Value;
-import org.springframework.context.annotation.PropertySource;
-import org.springframework.stereotype.Service;
-
-import javax.annotation.PostConstruct;
import java.util.Arrays;
import java.util.List;
import java.util.regex.Pattern;
import java.util.stream.Collectors;
+import javax.annotation.PostConstruct;
+
+import org.springframework.beans.factory.annotation.Value;
+import org.springframework.context.annotation.PropertySource;
+import org.springframework.stereotype.Service;
+
@Service
@PropertySource("classpath:retired.properties")
@PropertySource(value = "file:${server.local.startpath}/retired.properties")
@@ -42,26 +43,28 @@ public class RetiredService {
private List<Pattern> retiredAllVersionList;
@PostConstruct
- public void initialize(){
- this.retiredPatternsList = Arrays.stream(retiredPatterns.split(",")).map(Pattern::compile).collect(Collectors.toList());
- this.retiredAllVersionList = Arrays.stream(retiredAllVersions.split(",")).map(Pattern::compile).collect(Collectors.toList());
+ public void initialize() {
+ this.retiredPatternsList = Arrays.stream(retiredPatterns.split(",")).map(Pattern::compile)
+ .collect(Collectors.toList());
+ this.retiredAllVersionList = Arrays.stream(retiredAllVersions.split(","))
+ .map(Pattern::compile).collect(Collectors.toList());
}
@Value("${retired.api.pattern.list}")
- public void setRetiredPatterns(String retiredPatterns){
+ public void setRetiredPatterns(String retiredPatterns) {
this.retiredPatterns = retiredPatterns;
}
- public List<Pattern> getRetiredPatterns(){
+ public List<Pattern> getRetiredPatterns() {
return retiredPatternsList;
}
@Value("${retired.api.all.versions}")
- public void setRetiredAllVersions(String retiredPatterns){
+ public void setRetiredAllVersions(String retiredPatterns) {
this.retiredAllVersions = retiredPatterns;
}
- public List<Pattern> getRetiredAllVersionList(){
+ public List<Pattern> getRetiredAllVersionList() {
return retiredAllVersionList;
}
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/transforms/Converter.java b/aai-traversal/src/main/java/org/onap/aai/transforms/Converter.java
index 676c910..1fe66fe 100644
--- a/aai-traversal/src/main/java/org/onap/aai/transforms/Converter.java
+++ b/aai-traversal/src/main/java/org/onap/aai/transforms/Converter.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
diff --git a/aai-traversal/src/main/java/org/onap/aai/transforms/LowerCamelToLowerHyphenConverter.java b/aai-traversal/src/main/java/org/onap/aai/transforms/LowerCamelToLowerHyphenConverter.java
index aae42b5..6387deb 100644
--- a/aai-traversal/src/main/java/org/onap/aai/transforms/LowerCamelToLowerHyphenConverter.java
+++ b/aai-traversal/src/main/java/org/onap/aai/transforms/LowerCamelToLowerHyphenConverter.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -25,7 +25,7 @@ public class LowerCamelToLowerHyphenConverter implements Converter {
@Override
public String convert(String input) {
- if(input == null){
+ if (input == null) {
return null;
}
return CaseFormat.LOWER_CAMEL.to(CaseFormat.LOWER_HYPHEN, input);
diff --git a/aai-traversal/src/main/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverter.java b/aai-traversal/src/main/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverter.java
index b4baa0c..804326f 100644
--- a/aai-traversal/src/main/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverter.java
+++ b/aai-traversal/src/main/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverter.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -24,10 +24,10 @@ package org.onap.aai.transforms;
* for converting from the lower hyphen to lower camel case
* <p>
* Examples:
- * lower-test => lowerTest
- * lower-Test => lowerTest
- * lowerTest => lowerTest
- * lower-test-val => lowerTestVal
+ * lower-test => lowerTest
+ * lower-Test => lowerTest
+ * lowerTest => lowerTest
+ * lower-test-val => lowerTestVal
* <p>
*
*/
@@ -46,11 +46,11 @@ public class LowerHyphenToLowerCamelConverter implements Converter {
*
* @param input the input string to convert to camel case
* @return a string that is converted to camel case
- * if the input is null, then it returns null
+ * if the input is null, then it returns null
*/
@Override
public String convert(String input) {
- if(input == null){
+ if (input == null) {
return null;
}
@@ -59,17 +59,17 @@ public class LowerHyphenToLowerCamelConverter implements Converter {
boolean isPreviousCharDash = false;
- for(int index = 0; index < size; ++index){
+ for (int index = 0; index < size; ++index) {
char ch = input.charAt(index);
- if(ch == '-'){
+ if (ch == '-') {
isPreviousCharDash = true;
continue;
}
- if(isPreviousCharDash){
+ if (isPreviousCharDash) {
builder.append(Character.toUpperCase(ch));
isPreviousCharDash = false;
- } else{
+ } else {
builder.append(ch);
}
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/transforms/MapTraverser.java b/aai-traversal/src/main/java/org/onap/aai/transforms/MapTraverser.java
index f59fb10..24d5a83 100644
--- a/aai-traversal/src/main/java/org/onap/aai/transforms/MapTraverser.java
+++ b/aai-traversal/src/main/java/org/onap/aai/transforms/MapTraverser.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,23 +19,22 @@
*/
package org.onap.aai.transforms;
-
-import joptsimple.internal.Objects;
-
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
+import joptsimple.internal.Objects;
+
public class MapTraverser {
private Converter converter;
- public MapTraverser(Converter converter){
+ public MapTraverser(Converter converter) {
this.converter = converter;
}
- public Map<String, Object> convertKeys(Map<String, Object> map){
+ public Map<String, Object> convertKeys(Map<String, Object> map) {
Objects.ensureNotNull(map);
@@ -45,15 +44,16 @@ public class MapTraverser {
return modifiedMap;
}
- private Map<String, Object> convertKeys(Map<String, Object> original, Map<String, Object> modified){
+ private Map<String, Object> convertKeys(Map<String, Object> original,
+ Map<String, Object> modified) {
- for(Map.Entry<String, Object> entry : original.entrySet()){
+ for (Map.Entry<String, Object> entry : original.entrySet()) {
String key = entry.getKey();
key = converter.convert(key);
Object value = entry.getValue();
- if(value instanceof Map){
+ if (value instanceof Map) {
modified.put(key, convertKeys((Map<String, Object>) value, new HashMap<>()));
- } else if(value instanceof List){
+ } else if (value instanceof List) {
modified.put(key, convertKeys((List<Object>) value));
} else {
modified.put(key, value);
@@ -63,16 +63,16 @@ public class MapTraverser {
return modified;
}
- public List<Object> convertKeys(List<Object> list){
+ public List<Object> convertKeys(List<Object> list) {
List<Object> modifiedList = new ArrayList<>();
- if(list != null && !list.isEmpty()){
+ if (list != null && !list.isEmpty()) {
- for(Object o : list){
- if(o instanceof Map){
+ for (Object o : list) {
+ if (o instanceof Map) {
Map<String, Object> map = (Map<String, Object>) o;
modifiedList.add(convertKeys(map));
- } else if(o instanceof List){
+ } else if (o instanceof List) {
List<Object> l = (List<Object>) o;
modifiedList.add(convertKeys(l));
} else {
diff --git a/aai-traversal/src/main/java/org/onap/aai/util/GenericQueryBuilder.java b/aai-traversal/src/main/java/org/onap/aai/util/GenericQueryBuilder.java
index 8570fe4..82ccc73 100644
--- a/aai-traversal/src/main/java/org/onap/aai/util/GenericQueryBuilder.java
+++ b/aai-traversal/src/main/java/org/onap/aai/util/GenericQueryBuilder.java
@@ -19,11 +19,13 @@
*/
package org.onap.aai.util;
-import javax.ws.rs.core.HttpHeaders;
import java.util.List;
+
+import javax.ws.rs.core.HttpHeaders;
+
import org.onap.aai.introspection.Loader;
-import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
+import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
/**
* Builder Class used to minimize number of formal parameters.
diff --git a/aai-traversal/src/main/java/org/onap/aai/util/MakeNamedQuery.java b/aai-traversal/src/main/java/org/onap/aai/util/MakeNamedQuery.java
index 17207f3..7bda3bb 100644
--- a/aai-traversal/src/main/java/org/onap/aai/util/MakeNamedQuery.java
+++ b/aai-traversal/src/main/java/org/onap/aai/util/MakeNamedQuery.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -18,15 +18,14 @@
* ============LICENSE_END=========================================================
*/
package org.onap.aai.util;
-import java.io.File;
+import com.att.eelf.configuration.EELFManager;
+
+import java.io.File;
import java.nio.charset.Charset;
import java.util.*;
import java.util.Map.Entry;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import com.att.eelf.configuration.EELFManager;
import org.apache.commons.io.FileUtils;
import org.onap.aai.config.SpringContextAware;
import org.onap.aai.introspection.Introspector;
@@ -36,217 +35,230 @@ import org.onap.aai.introspection.ModelType;
import org.onap.aai.introspection.exceptions.AAIUnknownObjectException;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.SchemaVersions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
public class MakeNamedQuery {
-
- private static final Logger logger = LoggerFactory.getLogger(MakeNamedQuery.class.getName());
-
- public static void main(String[] args) throws Exception {
- String _apiVersion = AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP);
- String widgetJsonDir = null;
- String modelVersion = null;
- String namedQueryUuid = UUID.randomUUID().toString();
- if (args.length > 0) {
- if (args[0] != null) {
- _apiVersion = args[0];
- }
- if (args[1] != null) {
- widgetJsonDir = args[1];
- }
- if (args[2] != null) {
- modelVersion = args[2];
- }
- if (args[3] != null) {
- namedQueryUuid = args[3];
- }
- }
-
- if (widgetJsonDir == null) {
- System.err.println("You must specify a directory for widgetModelJson");
- System.exit(0);
- }
- if (modelVersion == null) {
- System.err.println("You must specify a modelVersion");
- System.exit(0);
- }
-
- AnnotationConfigApplicationContext ctx = new AnnotationConfigApplicationContext(
- "org.onap.aai.config",
- "org.onap.aai.setup"
- );
-
- LoaderFactory loaderFactory = ctx.getBean(LoaderFactory.class);
- SchemaVersions schemaVersions = ctx.getBean(SchemaVersions.class);
-
- if(schemaVersions.getVersions().contains(_apiVersion)){
-
- Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, new SchemaVersion(_apiVersion));
-
- // iterate the collection of resources
-
- ArrayList<String> processedWidgets = new ArrayList<>();
-
-
- HashMap<String, List<Introspector>> widgetToRelationship = new HashMap<>();
- for (Entry<String, Introspector> aaiResEnt : loader.getAllObjects().entrySet()) {
- Introspector meObject;
- // no need for a ModelVers DynamicEntity
-
- Introspector aaiRes = aaiResEnt.getValue();
-
- if (!(aaiRes.isContainer() || aaiRes.getName().equals("aai-internal"))) {
- String resource = aaiRes.getName();
-
- if (processedWidgets.contains(resource)) {
- continue;
- }
- processedWidgets.add(resource);
-
- String widgetName = resource;
- String filePathString = widgetJsonDir + "/" + widgetName + "-" + modelVersion + ".json";
- File f = new File(filePathString);
- if (f.exists()) {
- System.out.println(f.toString());
- String json = FileUtils.readFileToString(f, Charset.defaultCharset());
-
- meObject = loader.unmarshal("Model", json);
- String modelInvariantId = meObject.getValue("model-invariant-id");
- if (meObject.hasProperty("model-vers")) {
- Introspector modelVers = meObject.getWrappedValue("model-vers");
- List<Introspector> modelVerList = modelVers.getWrappedListValue("model-ver");
- for (Introspector modelVer : modelVerList) {
-
- List<Introspector> relList = new ArrayList<>();
- Introspector widgetRelationship = makeWidgetRelationship(loader, modelInvariantId,
- modelVer.getValue("model-version-id").toString());
- relList.add(widgetRelationship);
-
- widgetToRelationship.put(widgetName, relList);
- }
- }
- }
- }
- }
-
- //source vnf-id, related service-instance-id, all related vnfs in this service-instance-id
- //this should be abstracted and moved to a file
-
- List<Introspector> genericVnfRelationship = widgetToRelationship.get("generic-vnf");
- List<Introspector> vserverRelationship = widgetToRelationship.get("vserver");
- List<Introspector> tenantRelationship = widgetToRelationship.get("tenant");
- List<Introspector> cloudRegionRelationship = widgetToRelationship.get("cloud-region");
- List<Introspector> esrSystemInfoRelationship = widgetToRelationship.get("esr-system-info");
-
- Introspector namedQueryObj = loader.introspectorFromName("named-query");
- namedQueryObj.setValue("named-query-uuid", namedQueryUuid);
- namedQueryObj.setValue("named-query-name", "vnf-to-esr-system-info");
- namedQueryObj.setValue("named-query-version", "1.0");
- namedQueryObj.setValue("description", "Named Query - VNF to ESR System Info");
-
- Introspector genericVnfNQE = setupNQElements(namedQueryObj, genericVnfRelationship);
-
- Introspector vserverNQE = setupNQElements(genericVnfNQE, vserverRelationship);
-
- Introspector tenantNQE = setupNQElements(vserverNQE, tenantRelationship);
-
- Introspector cloudRegionNQE = setupNQElements(tenantNQE, cloudRegionRelationship);
-
- Introspector esrSystemInfoNQE = setupNQElements(cloudRegionNQE, esrSystemInfoRelationship);
-
- System.out.println(namedQueryObj.marshal(true));
-
- }
-
- System.exit(0);
-
- }
-
- private static Introspector setupNQElements (Introspector nqeObj, List<Introspector> listOfRelationships) {
- Introspector newNQElement = null;
- try {
- Introspector newNQElements = null;
- List<Object> nqElementList = null;
- if (nqeObj.getWrappedValue("named-query-elements") != null) {
- newNQElements = nqeObj.getWrappedValue("named-query-elements");
- nqElementList = newNQElements.getValue("named-query-element");
- } else {
- newNQElements = nqeObj.newIntrospectorInstanceOfProperty("named-query-elements");
- nqeObj.setValue("named-query-elements", newNQElements.getUnderlyingObject());
- nqElementList = newNQElements.getValue("named-query-element");
- }
- newNQElement = loadNQElement(newNQElements, listOfRelationships);
- if (newNQElement != null) {
- nqElementList.add(newNQElement.getUnderlyingObject());
- }
-
- } catch (AAIUnknownObjectException e) {
- logger.info("AAIUnknownObjectException in MakeNamedQuery.setupNQElements() "+e);
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- logger.info("IllegalArgumentException in MakeNamedQuery.setupNQElements() "+e);
- e.printStackTrace();
- }
- return newNQElement;
- }
-
- private static Introspector loadNQElement (Introspector nqElements, List<Introspector> listOfRelationships) {
- Introspector newNqElement = null;
- try {
- newNqElement = nqElements.getLoader().introspectorFromName("named-query-element");
-
- //newNqElement.setValue("named-query-element-uuid", UUID.randomUUID().toString());
-
- Introspector newRelationshipList = newNqElement.getLoader().introspectorFromName("relationship-list");
- newNqElement.setValue("relationship-list", newRelationshipList.getUnderlyingObject());
-
- List<Object> newRelationshipListList = newRelationshipList.getValue("relationship");
-
- for (Introspector rel : listOfRelationships) {
- newRelationshipListList.add(rel.getUnderlyingObject());
- }
-
- } catch (AAIUnknownObjectException e) {
- logger.info("AAIUnknownObjectException in MakeNamedQuery.loadNQElement() "+e);
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- logger.info("IllegalArgumentException in MakeNamedQuery.loadNQElement() "+e);
- e.printStackTrace();
- }
- return newNqElement;
-
- }
- private static Introspector makeWidgetRelationship(Loader loader, String modelInvariantId, String modelVersionId) {
-
- Introspector newRelationship = null;
- try {
- newRelationship = loader.introspectorFromName("relationship");
-
- List<Object> newRelationshipData = newRelationship.getValue("relationship-data");
-
- newRelationship.setValue("related-to", "model");
-
- Introspector newRelationshipDatum1 = newRelationship.getLoader().introspectorFromName("relationship-data");
- Introspector newRelationshipDatum2 = newRelationship.getLoader().introspectorFromName("relationship-data");
-
-
- newRelationshipDatum1.setValue("relationship-key", "model.model-invariant-id");
- newRelationshipDatum1.setValue("relationship-value", modelInvariantId);
-
- //newRelationshipDatum2.setValue("relationship-key", "model-ver.model-version-id");
- //newRelationshipDatum2.setValue("relationship-value", modelVersionId);
-
- newRelationshipData.add(newRelationshipDatum1.getUnderlyingObject());
- //newRelationshipData.add(newRelationshipDatum2.getUnderlyingObject());
- } catch (AAIUnknownObjectException e) {
- logger.info("AAIUnknownObjectException in MakeNamedQuery.makeWidgetRelationship() "+e);
- e.printStackTrace();
- } catch (IllegalArgumentException e) {
- logger.info("IllegalArgumentException in MakeNamedQuery.makeWidgetRelationship() "+e);
- e.printStackTrace();
- }
-
- return newRelationship;
- }
-
-} \ No newline at end of file
+
+ private static final Logger logger = LoggerFactory.getLogger(MakeNamedQuery.class.getName());
+
+ public static void main(String[] args) throws Exception {
+ String _apiVersion = AAIConfig.get(AAIConstants.AAI_DEFAULT_API_VERSION_PROP);
+ String widgetJsonDir = null;
+ String modelVersion = null;
+ String namedQueryUuid = UUID.randomUUID().toString();
+ if (args.length > 0) {
+ if (args[0] != null) {
+ _apiVersion = args[0];
+ }
+ if (args[1] != null) {
+ widgetJsonDir = args[1];
+ }
+ if (args[2] != null) {
+ modelVersion = args[2];
+ }
+ if (args[3] != null) {
+ namedQueryUuid = args[3];
+ }
+ }
+
+ if (widgetJsonDir == null) {
+ System.err.println("You must specify a directory for widgetModelJson");
+ System.exit(0);
+ }
+ if (modelVersion == null) {
+ System.err.println("You must specify a modelVersion");
+ System.exit(0);
+ }
+
+ AnnotationConfigApplicationContext ctx =
+ new AnnotationConfigApplicationContext("org.onap.aai.config", "org.onap.aai.setup");
+
+ LoaderFactory loaderFactory = ctx.getBean(LoaderFactory.class);
+ SchemaVersions schemaVersions = ctx.getBean(SchemaVersions.class);
+
+ if (schemaVersions.getVersions().contains(_apiVersion)) {
+
+ Loader loader = loaderFactory.createLoaderForVersion(ModelType.MOXY,
+ new SchemaVersion(_apiVersion));
+
+ // iterate the collection of resources
+
+ ArrayList<String> processedWidgets = new ArrayList<>();
+
+ HashMap<String, List<Introspector>> widgetToRelationship = new HashMap<>();
+ for (Entry<String, Introspector> aaiResEnt : loader.getAllObjects().entrySet()) {
+ Introspector meObject;
+ // no need for a ModelVers DynamicEntity
+
+ Introspector aaiRes = aaiResEnt.getValue();
+
+ if (!(aaiRes.isContainer() || aaiRes.getName().equals("aai-internal"))) {
+ String resource = aaiRes.getName();
+
+ if (processedWidgets.contains(resource)) {
+ continue;
+ }
+ processedWidgets.add(resource);
+
+ String widgetName = resource;
+ String filePathString =
+ widgetJsonDir + "/" + widgetName + "-" + modelVersion + ".json";
+ File f = new File(filePathString);
+ if (f.exists()) {
+ System.out.println(f.toString());
+ String json = FileUtils.readFileToString(f, Charset.defaultCharset());
+
+ meObject = loader.unmarshal("Model", json);
+ String modelInvariantId = meObject.getValue("model-invariant-id");
+ if (meObject.hasProperty("model-vers")) {
+ Introspector modelVers = meObject.getWrappedValue("model-vers");
+ List<Introspector> modelVerList =
+ modelVers.getWrappedListValue("model-ver");
+ for (Introspector modelVer : modelVerList) {
+
+ List<Introspector> relList = new ArrayList<>();
+ Introspector widgetRelationship =
+ makeWidgetRelationship(loader, modelInvariantId,
+ modelVer.getValue("model-version-id").toString());
+ relList.add(widgetRelationship);
+
+ widgetToRelationship.put(widgetName, relList);
+ }
+ }
+ }
+ }
+ }
+
+ // source vnf-id, related service-instance-id, all related vnfs in this
+ // service-instance-id
+ // this should be abstracted and moved to a file
+
+ List<Introspector> genericVnfRelationship = widgetToRelationship.get("generic-vnf");
+ List<Introspector> vserverRelationship = widgetToRelationship.get("vserver");
+ List<Introspector> tenantRelationship = widgetToRelationship.get("tenant");
+ List<Introspector> cloudRegionRelationship = widgetToRelationship.get("cloud-region");
+ List<Introspector> esrSystemInfoRelationship =
+ widgetToRelationship.get("esr-system-info");
+
+ Introspector namedQueryObj = loader.introspectorFromName("named-query");
+ namedQueryObj.setValue("named-query-uuid", namedQueryUuid);
+ namedQueryObj.setValue("named-query-name", "vnf-to-esr-system-info");
+ namedQueryObj.setValue("named-query-version", "1.0");
+ namedQueryObj.setValue("description", "Named Query - VNF to ESR System Info");
+
+ Introspector genericVnfNQE = setupNQElements(namedQueryObj, genericVnfRelationship);
+
+ Introspector vserverNQE = setupNQElements(genericVnfNQE, vserverRelationship);
+
+ Introspector tenantNQE = setupNQElements(vserverNQE, tenantRelationship);
+
+ Introspector cloudRegionNQE = setupNQElements(tenantNQE, cloudRegionRelationship);
+
+ Introspector esrSystemInfoNQE =
+ setupNQElements(cloudRegionNQE, esrSystemInfoRelationship);
+
+ System.out.println(namedQueryObj.marshal(true));
+
+ }
+
+ System.exit(0);
+
+ }
+
+ private static Introspector setupNQElements(Introspector nqeObj,
+ List<Introspector> listOfRelationships) {
+ Introspector newNQElement = null;
+ try {
+ Introspector newNQElements = null;
+ List<Object> nqElementList = null;
+ if (nqeObj.getWrappedValue("named-query-elements") != null) {
+ newNQElements = nqeObj.getWrappedValue("named-query-elements");
+ nqElementList = newNQElements.getValue("named-query-element");
+ } else {
+ newNQElements = nqeObj.newIntrospectorInstanceOfProperty("named-query-elements");
+ nqeObj.setValue("named-query-elements", newNQElements.getUnderlyingObject());
+ nqElementList = newNQElements.getValue("named-query-element");
+ }
+ newNQElement = loadNQElement(newNQElements, listOfRelationships);
+ if (newNQElement != null) {
+ nqElementList.add(newNQElement.getUnderlyingObject());
+ }
+
+ } catch (AAIUnknownObjectException e) {
+ logger.info("AAIUnknownObjectException in MakeNamedQuery.setupNQElements() " + e);
+ e.printStackTrace();
+ } catch (IllegalArgumentException e) {
+ logger.info("IllegalArgumentException in MakeNamedQuery.setupNQElements() " + e);
+ e.printStackTrace();
+ }
+ return newNQElement;
+ }
+
+ private static Introspector loadNQElement(Introspector nqElements,
+ List<Introspector> listOfRelationships) {
+ Introspector newNqElement = null;
+ try {
+ newNqElement = nqElements.getLoader().introspectorFromName("named-query-element");
+
+ // newNqElement.setValue("named-query-element-uuid", UUID.randomUUID().toString());
+
+ Introspector newRelationshipList =
+ newNqElement.getLoader().introspectorFromName("relationship-list");
+ newNqElement.setValue("relationship-list", newRelationshipList.getUnderlyingObject());
+
+ List<Object> newRelationshipListList = newRelationshipList.getValue("relationship");
+
+ for (Introspector rel : listOfRelationships) {
+ newRelationshipListList.add(rel.getUnderlyingObject());
+ }
+
+ } catch (AAIUnknownObjectException e) {
+ logger.info("AAIUnknownObjectException in MakeNamedQuery.loadNQElement() " + e);
+ e.printStackTrace();
+ } catch (IllegalArgumentException e) {
+ logger.info("IllegalArgumentException in MakeNamedQuery.loadNQElement() " + e);
+ e.printStackTrace();
+ }
+ return newNqElement;
+
+ }
+
+ private static Introspector makeWidgetRelationship(Loader loader, String modelInvariantId,
+ String modelVersionId) {
+
+ Introspector newRelationship = null;
+ try {
+ newRelationship = loader.introspectorFromName("relationship");
+
+ List<Object> newRelationshipData = newRelationship.getValue("relationship-data");
+
+ newRelationship.setValue("related-to", "model");
+
+ Introspector newRelationshipDatum1 =
+ newRelationship.getLoader().introspectorFromName("relationship-data");
+ Introspector newRelationshipDatum2 =
+ newRelationship.getLoader().introspectorFromName("relationship-data");
+
+ newRelationshipDatum1.setValue("relationship-key", "model.model-invariant-id");
+ newRelationshipDatum1.setValue("relationship-value", modelInvariantId);
+
+ // newRelationshipDatum2.setValue("relationship-key", "model-ver.model-version-id");
+ // newRelationshipDatum2.setValue("relationship-value", modelVersionId);
+
+ newRelationshipData.add(newRelationshipDatum1.getUnderlyingObject());
+ // newRelationshipData.add(newRelationshipDatum2.getUnderlyingObject());
+ } catch (AAIUnknownObjectException e) {
+ logger
+ .info("AAIUnknownObjectException in MakeNamedQuery.makeWidgetRelationship() " + e);
+ e.printStackTrace();
+ } catch (IllegalArgumentException e) {
+ logger.info("IllegalArgumentException in MakeNamedQuery.makeWidgetRelationship() " + e);
+ e.printStackTrace();
+ }
+
+ return newRelationship;
+ }
+
+}
diff --git a/aai-traversal/src/main/java/org/onap/aai/util/NodesQueryBuilder.java b/aai-traversal/src/main/java/org/onap/aai/util/NodesQueryBuilder.java
index 978e484..1250270 100644
--- a/aai-traversal/src/main/java/org/onap/aai/util/NodesQueryBuilder.java
+++ b/aai-traversal/src/main/java/org/onap/aai/util/NodesQueryBuilder.java
@@ -20,10 +20,12 @@
package org.onap.aai.util;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import javax.ws.rs.core.HttpHeaders;
import java.util.List;
+
+import javax.ws.rs.core.HttpHeaders;
+
import org.onap.aai.introspection.Loader;
+import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
/**
diff --git a/aai-traversal/src/main/java/org/onap/aai/util/TraversalConstants.java b/aai-traversal/src/main/java/org/onap/aai/util/TraversalConstants.java
index fdeefe1..0094bc2 100644
--- a/aai-traversal/src/main/java/org/onap/aai/util/TraversalConstants.java
+++ b/aai-traversal/src/main/java/org/onap/aai/util/TraversalConstants.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -20,23 +20,25 @@
package org.onap.aai.util;
public final class TraversalConstants {
- public static final int AAI_QUERY_PORT = 8446;
-
- public static final String AAI_TRAVERSAL_TIMEOUT_LIMIT = "aai.traversal.timeoutlimit";
- public static final String AAI_TRAVERSAL_TIMEOUT_ENABLED = "aai.traversal.timeoutenabled";
- public static final String AAI_TRAVERSAL_TIMEOUT_APP = "aai.traversal.timeout.appspecific";
-
- public static final String AAI_TRAVERSAL_DSL_TIMEOUT_LIMIT = "aai.traversal.dsl.timeoutlimit";
- public static final String AAI_TRAVERSAL_DSL_TIMEOUT_ENABLED = "aai.traversal.dsl.timeoutenabled";
- public static final String AAI_TRAVERSAL_DSL_TIMEOUT_APP = "aai.traversal.dsl.timeout.appspecific";
- public static final String DSL_NOVALIDATION_CLIENTS = "aai.traversal.dsl.novalidation.clients";
- public static final String DSL_OVERRIDE = "aai.dsl.override";
- public static final String DSL_MAX_NODE_COUNT = "15";
+ public static final int AAI_QUERY_PORT = 8446;
+
+ public static final String AAI_TRAVERSAL_TIMEOUT_LIMIT = "aai.traversal.timeoutlimit";
+ public static final String AAI_TRAVERSAL_TIMEOUT_ENABLED = "aai.traversal.timeoutenabled";
+ public static final String AAI_TRAVERSAL_TIMEOUT_APP = "aai.traversal.timeout.appspecific";
+
+ public static final String AAI_TRAVERSAL_DSL_TIMEOUT_LIMIT = "aai.traversal.dsl.timeoutlimit";
+ public static final String AAI_TRAVERSAL_DSL_TIMEOUT_ENABLED =
+ "aai.traversal.dsl.timeoutenabled";
+ public static final String AAI_TRAVERSAL_DSL_TIMEOUT_APP =
+ "aai.traversal.dsl.timeout.appspecific";
+ public static final String DSL_NOVALIDATION_CLIENTS = "aai.traversal.dsl.novalidation.clients";
+ public static final String DSL_OVERRIDE = "aai.dsl.override";
+ public static final String DSL_MAX_NODE_COUNT = "15";
public static final long HISTORY_MAX_HOURS = 192;
-
- private TraversalConstants() {
- // prevent instantiation
- }
+
+ private TraversalConstants() {
+ // prevent instantiation
+ }
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/web/JerseyConfiguration.java b/aai-traversal/src/main/java/org/onap/aai/web/JerseyConfiguration.java
index 39aa31c..87d6d8f 100644
--- a/aai-traversal/src/main/java/org/onap/aai/web/JerseyConfiguration.java
+++ b/aai-traversal/src/main/java/org/onap/aai/web/JerseyConfiguration.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,7 +19,19 @@
*/
package org.onap.aai.web;
+import static java.lang.Boolean.parseBoolean;
+import static java.util.Comparator.comparingInt;
+
import com.google.common.collect.Sets;
+
+import java.lang.reflect.AnnotatedElement;
+import java.util.Collection;
+import java.util.Comparator;
+import java.util.Set;
+import java.util.logging.Logger;
+
+import javax.annotation.Priority;
+
import org.glassfish.jersey.server.ResourceConfig;
import org.onap.aai.rest.*;
import org.onap.aai.rest.search.ModelAndNamedQueryRestProvider;
@@ -32,21 +44,12 @@ import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.Profile;
import org.springframework.core.env.Environment;
-import javax.annotation.Priority;
-import java.lang.reflect.AnnotatedElement;
-import java.util.Collection;
-import java.util.Comparator;
-import java.util.Set;
-import java.util.logging.Logger;
-
-import static java.lang.Boolean.parseBoolean;
-import static java.util.Comparator.comparingInt;
-
@Configuration
public class JerseyConfiguration {
private static final Logger log = Logger.getLogger(JerseyConfiguration.class.getName());
- private static final org.slf4j.Logger logger = LoggerFactory.getLogger(JerseyConfiguration.class.getName());
+ private static final org.slf4j.Logger logger =
+ LoggerFactory.getLogger(JerseyConfiguration.class.getName());
private static final String LOGGING_ENABLED_PROPERTY = "aai.request.logging.enabled";
private static final boolean ENABLE_RESPONSE_LOGGING = false;
@@ -62,18 +65,11 @@ public class JerseyConfiguration {
public ResourceConfig resourceConfig() {
ResourceConfig resourceConfig = new ResourceConfig();
- Set<Class<?>> classes = Sets.newHashSet(
- SearchProvider.class,
- ModelAndNamedQueryRestProvider.class,
- QueryConsumer.class,
- RecentAPIConsumer.class,
- DslConsumer.class,
- EchoResponse.class,
- CQ2Gremlin.class,
- CQ2GremlinTest.class
- );
- Set<Class<?>> filterClasses = Sets.newHashSet(
- org.onap.aai.interceptors.pre.RequestTransactionLogging.class,
+ Set<Class<?>> classes = Sets.newHashSet(SearchProvider.class,
+ ModelAndNamedQueryRestProvider.class, QueryConsumer.class, RecentAPIConsumer.class,
+ DslConsumer.class, EchoResponse.class, CQ2Gremlin.class, CQ2GremlinTest.class);
+ Set<Class<?>> filterClasses =
+ Sets.newHashSet(org.onap.aai.interceptors.pre.RequestTransactionLogging.class,
org.onap.aai.interceptors.pre.HeaderValidation.class,
org.onap.aai.interceptors.pre.HttpHeaderInterceptor.class,
org.onap.aai.interceptors.pre.OneWaySslAuthorization.class,
@@ -84,28 +80,24 @@ public class JerseyConfiguration {
org.onap.aai.interceptors.pre.RequestModification.class,
org.onap.aai.interceptors.post.InvalidResponseStatus.class,
org.onap.aai.interceptors.post.ResponseTransactionLogging.class,
- org.onap.aai.interceptors.post.ResponseHeaderManipulation.class
- );
+ org.onap.aai.interceptors.post.ResponseHeaderManipulation.class);
resourceConfig.registerClasses(classes);
logger.debug("REGISTERED CLASSES " + classes.toString());
throwIfPriorityAnnotationAbsent(filterClasses);
- filterClasses.stream()
- .filter(this::isEnabledByActiveProfiles)
- .sorted(priorityComparator())
- .forEach(resourceConfig::register);
-
- filterClasses.stream()
- .filter(this::isEnabledByActiveProfiles)
- .sorted(priorityComparator())
- .forEach(s -> logger.debug("REGISTERED FILTERS " + s.getName()));
+ filterClasses.stream().filter(this::isEnabledByActiveProfiles).sorted(priorityComparator())
+ .forEach(resourceConfig::register);
+
+ filterClasses.stream().filter(this::isEnabledByActiveProfiles).sorted(priorityComparator())
+ .forEach(s -> logger.debug("REGISTERED FILTERS " + s.getName()));
return resourceConfig;
}
private <T> void throwIfPriorityAnnotationAbsent(Collection<Class<? extends T>> classes) {
for (Class clazz : classes) {
if (!clazz.isAnnotationPresent(Priority.class)) {
- logger.debug("throwIfPriorityAnnotationAbsent: missing filter priority for : " + clazz.getName());
+ logger.debug("throwIfPriorityAnnotationAbsent: missing filter priority for : "
+ + clazz.getName());
throw new MissingFilterPriorityException(clazz);
}
}
@@ -120,9 +112,10 @@ public class JerseyConfiguration {
}
private boolean isEnabledByActiveProfiles(AnnotatedElement annotatedElement) {
- boolean result = !annotatedElement.isAnnotationPresent(Profile.class) ||
- environment.acceptsProfiles(annotatedElement.getAnnotation(Profile.class).value());
- logger.debug("isEnabledByActiveProfiles: annotatedElement: " + annotatedElement.toString() + " result=" + result);
+ boolean result = !annotatedElement.isAnnotationPresent(Profile.class)
+ || environment.acceptsProfiles(annotatedElement.getAnnotation(Profile.class).value());
+ logger.debug("isEnabledByActiveProfiles: annotatedElement: " + annotatedElement.toString()
+ + " result=" + result);
return result;
}
@@ -131,4 +124,4 @@ public class JerseyConfiguration {
super("Container filter " + clazz.getName() + " does not have @Priority annotation");
}
}
-} \ No newline at end of file
+}
diff --git a/aai-traversal/src/main/java/org/onap/aai/web/LocalHostAccessLog.java b/aai-traversal/src/main/java/org/onap/aai/web/LocalHostAccessLog.java
index d2a4e89..cea7fc5 100644
--- a/aai-traversal/src/main/java/org/onap/aai/web/LocalHostAccessLog.java
+++ b/aai-traversal/src/main/java/org/onap/aai/web/LocalHostAccessLog.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -20,6 +20,9 @@
package org.onap.aai.web;
import ch.qos.logback.access.jetty.RequestLogImpl;
+
+import java.util.Arrays;
+
import org.eclipse.jetty.server.handler.HandlerCollection;
import org.eclipse.jetty.server.handler.RequestLogHandler;
import org.eclipse.jetty.util.thread.QueuedThreadPool;
@@ -29,39 +32,37 @@ import org.springframework.boot.web.servlet.server.AbstractServletWebServerFacto
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
-import java.util.Arrays;
-
@Configuration
public class LocalHostAccessLog {
@Bean
public AbstractServletWebServerFactory jettyConfigBean(
- @Value("${jetty.threadPool.maxThreads:200}") final String maxThreads,
- @Value("${jetty.threadPool.minThreads:8}") final String minThreads
- ){
+ @Value("${jetty.threadPool.maxThreads:200}") final String maxThreads,
+ @Value("${jetty.threadPool.minThreads:8}") final String minThreads) {
JettyServletWebServerFactory jef = new JettyServletWebServerFactory();
- jef.addServerCustomizers((org.springframework.boot.web.embedded.jetty.JettyServerCustomizer) server -> {
+ jef.addServerCustomizers(
+ (org.springframework.boot.web.embedded.jetty.JettyServerCustomizer) server -> {
- HandlerCollection handlers = new HandlerCollection();
+ HandlerCollection handlers = new HandlerCollection();
- Arrays.stream(server.getHandlers()).forEach(handlers::addHandler);
+ Arrays.stream(server.getHandlers()).forEach(handlers::addHandler);
- RequestLogHandler requestLogHandler = new RequestLogHandler();
- requestLogHandler.setServer(server);
+ RequestLogHandler requestLogHandler = new RequestLogHandler();
+ requestLogHandler.setServer(server);
- RequestLogImpl requestLogImpl = new RequestLogImpl();
- requestLogImpl.setResource("/localhost-access-logback.xml");
- requestLogImpl.start();
+ RequestLogImpl requestLogImpl = new RequestLogImpl();
+ requestLogImpl.setResource("/localhost-access-logback.xml");
+ requestLogImpl.start();
- requestLogHandler.setRequestLog(requestLogImpl);
- handlers.addHandler(requestLogHandler);
- server.setHandler(handlers);
+ requestLogHandler.setRequestLog(requestLogImpl);
+ handlers.addHandler(requestLogHandler);
+ server.setHandler(handlers);
- final QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class);
- threadPool.setMaxThreads(Integer.valueOf(maxThreads));
- threadPool.setMinThreads(Integer.valueOf(minThreads));
- });
+ final QueuedThreadPool threadPool = server.getBean(QueuedThreadPool.class);
+ threadPool.setMaxThreads(Integer.valueOf(maxThreads));
+ threadPool.setMinThreads(Integer.valueOf(minThreads));
+ });
return jef;
}
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/web/MicrometerConfiguration.java b/aai-traversal/src/main/java/org/onap/aai/web/MicrometerConfiguration.java
index 7c93e7d..77dbe96 100644
--- a/aai-traversal/src/main/java/org/onap/aai/web/MicrometerConfiguration.java
+++ b/aai-traversal/src/main/java/org/onap/aai/web/MicrometerConfiguration.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -18,23 +18,24 @@
* ============LICENSE_END=========================================================
*/
package org.onap.aai.web;
+
import io.micrometer.core.instrument.Tag;
import io.micrometer.core.instrument.Tags;
import io.micrometer.jersey2.server.JerseyTags;
import io.micrometer.jersey2.server.JerseyTagsProvider;
-import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
+
import org.glassfish.jersey.server.ContainerResponse;
import org.glassfish.jersey.server.monitoring.RequestEvent;
+import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
/**
- * Configuration Class to add customized tags to http metrics scraped in /actuator/prometheus endpoint
+ * Configuration Class to add customized tags to http metrics scraped in /actuator/prometheus
+ * endpoint
*/
@Configuration
-@ConditionalOnProperty(
- value="scrape.uri.metrics",
- havingValue = "true")
+@ConditionalOnProperty(value = "scrape.uri.metrics", havingValue = "true")
public class MicrometerConfiguration {
private static final String TAG_AAI_URI = "aai_uri";
private static final String NOT_AVAILABLE = "NOT AVAILABLE";
@@ -46,8 +47,10 @@ public class MicrometerConfiguration {
public Iterable httpRequestTags(RequestEvent event) {
ContainerResponse response = event.getContainerResponse();
return Tags.of(JerseyTags.method(event.getContainerRequest()),
- JerseyTags.exception(event), JerseyTags.status(response), JerseyTags.outcome(response), getAaiUriTag(event));
+ JerseyTags.exception(event), JerseyTags.status(response),
+ JerseyTags.outcome(response), getAaiUriTag(event));
}
+
private Tag getAaiUriTag(RequestEvent event) {
String aai_uri = event.getUriInfo().getRequestUri().toString();
if (aai_uri == null) {
@@ -55,9 +58,11 @@ public class MicrometerConfiguration {
}
return Tag.of(TAG_AAI_URI, aai_uri);
}
+
@Override
public Iterable<Tag> httpLongRequestTags(RequestEvent event) {
- return Tags.of(JerseyTags.method(event.getContainerRequest()), JerseyTags.uri(event));
+ return Tags.of(JerseyTags.method(event.getContainerRequest()),
+ JerseyTags.uri(event));
}
};
}
diff --git a/aai-traversal/src/main/java/org/onap/aai/web/WebConfiguration.java b/aai-traversal/src/main/java/org/onap/aai/web/WebConfiguration.java
index 5300611..a2a4271 100644
--- a/aai-traversal/src/main/java/org/onap/aai/web/WebConfiguration.java
+++ b/aai-traversal/src/main/java/org/onap/aai/web/WebConfiguration.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -27,20 +27,16 @@ import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter
@Configuration
public class WebConfiguration {
- @Bean
- public WebMvcConfigurerAdapter forwardToIndex() {
- return new WebMvcConfigurerAdapter() {
- @Override
- public void addViewControllers(ViewControllerRegistry registry) {
- registry.addViewController("/swagger").setViewName(
- "redirect:/swagger/index.html");
- registry.addViewController("/swagger/").setViewName(
- "redirect:/swagger/index.html");
- registry.addViewController("/docs").setViewName(
- "redirect:/docs/html/index.html");
- registry.addViewController("/docs/").setViewName(
- "redirect:/docs/html/index.html");
- }
- };
- }
-} \ No newline at end of file
+ @Bean
+ public WebMvcConfigurerAdapter forwardToIndex() {
+ return new WebMvcConfigurerAdapter() {
+ @Override
+ public void addViewControllers(ViewControllerRegistry registry) {
+ registry.addViewController("/swagger").setViewName("redirect:/swagger/index.html");
+ registry.addViewController("/swagger/").setViewName("redirect:/swagger/index.html");
+ registry.addViewController("/docs").setViewName("redirect:/docs/html/index.html");
+ registry.addViewController("/docs/").setViewName("redirect:/docs/html/index.html");
+ }
+ };
+ }
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/AAIGremlinQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/AAIGremlinQueryTest.java
index 2009389..266cb60 100644
--- a/aai-traversal/src/test/java/org/onap/aai/AAIGremlinQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/AAIGremlinQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,7 +19,16 @@
*/
package org.onap.aai;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.hamcrest.core.IsNot.not;
+import static org.junit.Assert.fail;
+
import com.jayway.jsonpath.JsonPath;
+
+import java.util.*;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.JanusGraphTransaction;
@@ -32,8 +41,8 @@ import org.onap.aai.util.AAIConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.annotation.Import;
import org.springframework.http.*;
import org.springframework.test.context.ContextConfiguration;
@@ -42,14 +51,6 @@ import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
import org.springframework.web.client.RestTemplate;
-import java.util.*;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.hamcrest.core.IsNot.not;
-import static org.junit.Assert.fail;
-
/**
* A sample junit test using spring boot that provides the ability to spin
* up the application from the junit layer and run rest requests against
@@ -61,7 +62,9 @@ import static org.junit.Assert.fail;
* 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
*/
-@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = TraversalApp.class)
+@SpringBootTest(
+ webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+ classes = TraversalApp.class)
@TestPropertySource(locations = "classpath:application-test.properties")
@ContextConfiguration(initializers = PropertyPasswordConfiguration.class)
@Import(TraversalTestConfiguration.class)
@@ -94,7 +97,7 @@ public class AAIGremlinQueryTest {
AAIConfig.init();
}
- public void createGraph(){
+ public void createGraph() {
JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
@@ -104,18 +107,14 @@ public class AAIGremlinQueryTest {
GraphTraversalSource g = transaction.traversal();
- g.addV()
- .property("aai-node-type", "pserver")
- .property("hostname", "test-pserver")
- .property("in-maint", false)
- .property("source-of-truth", "JUNIT")
- .property("aai-uri", "/cloud-infrastructure/pservers/pserver/test-pserver")
- .next();
+ g.addV().property("aai-node-type", "pserver").property("hostname", "test-pserver")
+ .property("in-maint", false).property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/cloud-infrastructure/pservers/pserver/test-pserver").next();
- } catch(Exception ex){
+ } catch (Exception ex) {
success = false;
} finally {
- if(success){
+ if (success) {
transaction.commit();
} else {
transaction.rollback();
@@ -157,7 +156,8 @@ public class AAIGremlinQueryTest {
String endpoint = "/aai/v11/query?format=console";
httpEntity = new HttpEntity(payload, headers);
- responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));
String result = JsonPath.read(responseEntity.getBody().toString(), "$.results[0].result");
@@ -184,7 +184,8 @@ public class AAIGremlinQueryTest {
String endpoint = "/aai/v11/query?format=console";
httpEntity = new HttpEntity(payload, headers);
- responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));
String result = JsonPath.read(responseEntity.getBody().toString(), "$.results[0].result");
@@ -202,32 +203,26 @@ public class AAIGremlinQueryTest {
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
httpEntity = new HttpEntity(payload, headers);
String endpoint = "/aai/v11/query?format=count";
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));
- assertThat(responseEntity.getBody().toString(), containsString("<results><result><pserver>1</pserver></result></results>"));
+ assertThat(responseEntity.getBody().toString(),
+ containsString("<results><result><pserver>1</pserver></result></results>"));
gremlinQueryMap.put("gremlin-query", "g.V().has('hostname', 'test-pserver')");
payload = PayloadUtil.getTemplatePayload("gremlin-query.json", gremlinQueryMap);
httpEntity = new HttpEntity(payload, headers);
- Format[] formats = new Format[]{
- Format.graphson,
- Format.pathed,
- Format.id,
- Format.resource,
- Format.simple,
- Format.resource_and_url,
- Format.console,
- Format.raw,
- Format.count
- };
+ Format[] formats = new Format[] {Format.graphson, Format.pathed, Format.id, Format.resource,
+ Format.simple, Format.resource_and_url, Format.console, Format.raw, Format.count};
- for(Format format : formats){
+ for (Format format : formats) {
endpoint = "/aai/v11/query?format=" + format.toString();
logger.debug("Current endpoint being executed {}", endpoint);
- responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));
String responseBody = responseEntity.getBody().toString();
@@ -236,6 +231,7 @@ public class AAIGremlinQueryTest {
assertThat(responseBody, is(not(containsString("<result><result>"))));
}
}
+
@Test
public void testPserverCountUsingDsl() throws Exception {
Map<String, String> dslQuerymap = new HashMap<>();
@@ -248,7 +244,8 @@ public class AAIGremlinQueryTest {
String endpoint = "/aai/v11/dsl?format=console";
httpEntity = new HttpEntity(payload, headers);
- responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));
String result = JsonPath.read(responseEntity.getBody().toString(), "$.results[0].result");
@@ -266,30 +263,24 @@ public class AAIGremlinQueryTest {
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
httpEntity = new HttpEntity(payload, headers);
String endpoint = "/aai/v11/dsl?format=count";
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));
- assertThat(responseEntity.getBody().toString(), containsString("<results><result><pserver>1</pserver></result></results>"));
+ assertThat(responseEntity.getBody().toString(),
+ containsString("<results><result><pserver>1</pserver></result></results>"));
httpEntity = new HttpEntity(payload, headers);
- Format[] formats = new Format[]{
- Format.graphson,
- Format.pathed,
- Format.id,
- Format.resource,
- Format.simple,
- Format.resource_and_url,
- Format.console,
- Format.raw,
- Format.count
- };
+ Format[] formats = new Format[] {Format.graphson, Format.pathed, Format.id, Format.resource,
+ Format.simple, Format.resource_and_url, Format.console, Format.raw, Format.count};
- for(Format format : formats){
+ for (Format format : formats) {
endpoint = "/aai/v11/dsl?format=" + format.toString();
logger.debug("Current endpoint being executed {}", endpoint);
- responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));
String responseBody = responseEntity.getBody().toString();
@@ -309,14 +300,12 @@ public class AAIGremlinQueryTest {
GraphTraversalSource g = transaction.traversal();
- g.V().has("source-of-truth", "JUNIT")
- .toList()
- .forEach(Vertex::remove);
+ g.V().has("source-of-truth", "JUNIT").toList().forEach(Vertex::remove);
- } catch(Exception ex){
+ } catch (Exception ex) {
success = false;
} finally {
- if(success){
+ if (success) {
transaction.commit();
} else {
transaction.rollback();
diff --git a/aai-traversal/src/test/java/org/onap/aai/AAISetup.java b/aai-traversal/src/test/java/org/onap/aai/AAISetup.java
index a13384a..e1cbe45 100644
--- a/aai-traversal/src/test/java/org/onap/aai/AAISetup.java
+++ b/aai-traversal/src/test/java/org/onap/aai/AAISetup.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -27,83 +27,74 @@ import java.util.Map;
import org.apache.commons.io.IOUtils;
import org.junit.BeforeClass;
+import org.junit.ClassRule;
+import org.junit.Rule;
import org.onap.aai.config.*;
import org.onap.aai.dbgraphmap.SearchGraph;
import org.onap.aai.edges.EdgeIngestor;
import org.onap.aai.introspection.LoaderFactory;
+import org.onap.aai.introspection.MoxyLoader;
import org.onap.aai.nodes.NodeIngestor;
import org.onap.aai.rest.db.HttpEntry;
import org.onap.aai.rest.dsl.DslQueryProcessor;
import org.onap.aai.rest.search.GremlinServerSingleton;
import org.onap.aai.serialization.db.EdgeSerializer;
import org.onap.aai.setup.AAIConfigTranslator;
+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.beans.factory.annotation.Value;
import org.springframework.test.context.ContextConfiguration;
-import org.onap.aai.introspection.MoxyLoader;
-import org.onap.aai.setup.SchemaLocationsBean;
-import org.junit.ClassRule;
-import org.junit.Rule;
import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.rules.SpringClassRule;
import org.springframework.test.context.junit4.rules.SpringMethodRule;
-@ContextConfiguration(classes = {
- ConfigConfiguration.class,
- AAIConfigTranslator.class,
- EdgeIngestor.class,
- EdgeSerializer.class,
- NodeIngestor.class,
- SpringContextAware.class,
- IntrospectionConfig.class ,
- RestBeanConfig.class,
- SearchConfiguration.class,
- DslConfiguration.class,
- XmlFormatTransformerConfiguration.class,
- GremlinServerSingleton.class
-})
-@TestPropertySource(properties = {
- "schema.uri.base.path = /aai",
- "schema.ingest.file = src/test/resources/application-test.properties"
-})
+@ContextConfiguration(
+ classes = {ConfigConfiguration.class, AAIConfigTranslator.class, EdgeIngestor.class,
+ EdgeSerializer.class, NodeIngestor.class, SpringContextAware.class,
+ IntrospectionConfig.class, RestBeanConfig.class, SearchConfiguration.class,
+ DslConfiguration.class, XmlFormatTransformerConfiguration.class,
+ GremlinServerSingleton.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
+ @Autowired
+ protected NodeIngestor nodeIngestor;
+
+ @Autowired
+ protected LoaderFactory loaderFactory;
+
+ @Autowired
+ protected Map<SchemaVersion, MoxyLoader> moxyLoaderInstance;
+
+ @Autowired
+ protected HttpEntry traversalHttpEntry;
+
+ @Autowired
+ protected HttpEntry traversalUriHttpEntry;
+
+ @Autowired
protected SearchGraph searchGraph;
-
- @Autowired
- protected EdgeSerializer edgeSer;
-
- @Autowired
- protected EdgeIngestor edgeIngestor;
- @Autowired
- protected DslQueryProcessor dslQueryProcessor;
+ @Autowired
+ protected EdgeSerializer edgeSer;
+
+ @Autowired
+ protected EdgeIngestor edgeIngestor;
+
+ @Autowired
+ protected DslQueryProcessor dslQueryProcessor;
- @Autowired
- protected SchemaVersions schemaVersions;
+ @Autowired
+ protected SchemaVersions schemaVersions;
- @Autowired
- protected GremlinServerSingleton gremlinServerSingleton;
+ @Autowired
+ protected GremlinServerSingleton gremlinServerSingleton;
- @Value("${schema.uri.base.path}")
- protected String basePath;
+ @Value("${schema.uri.base.path}")
+ protected String basePath;
@ClassRule
public static final SpringClassRule springClassRule = new SpringClassRule();
@@ -115,14 +106,12 @@ public abstract class AAISetup {
public static void setupBundleconfig() throws Exception {
System.setProperty("AJSC_HOME", "./");
System.setProperty("BUNDLECONFIG_DIR", "src/main/resources/");
-
+
}
-
+
public String getPayload(String filename) throws IOException {
- InputStream inputStream = getClass()
- .getClassLoader()
- .getResourceAsStream(filename);
+ InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filename);
String message = String.format("Unable to find the %s in src/test/resources", filename);
assertNotNull(message, inputStream);
@@ -131,11 +120,3 @@ public abstract class AAISetup {
return resource;
}
}
-
-
-
-
-
-
-
-
diff --git a/aai-traversal/src/test/java/org/onap/aai/HttpTestUtil.java b/aai-traversal/src/test/java/org/onap/aai/HttpTestUtil.java
index f12c8c3..23342f8 100644
--- a/aai-traversal/src/test/java/org/onap/aai/HttpTestUtil.java
+++ b/aai-traversal/src/test/java/org/onap/aai/HttpTestUtil.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,18 @@
*/
package org.onap.aai;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.doReturn;
+import static org.mockito.Mockito.when;
+
+import java.io.UnsupportedEncodingException;
+import java.net.URI;
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
+
+import javax.ws.rs.core.*;
+
import org.javatuples.Pair;
import org.mockito.Mockito;
import org.onap.aai.config.SpringContextAware;
@@ -37,17 +49,6 @@ import org.onap.aai.setup.SchemaVersions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-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 Logger logger = LoggerFactory.getLogger(HttpTestUtil.class);
@@ -67,14 +68,14 @@ public class HttpTestUtil extends RESTAPI {
private SchemaVersions schemaVersions;
- public void init(){
+ public void init() {
schemaVersions = (SchemaVersions) SpringContextAware.getBean("schemaVersions");
- httpHeaders = Mockito.mock(HttpHeaders.class);
- uriInfo = Mockito.mock(UriInfo.class);
+ httpHeaders = Mockito.mock(HttpHeaders.class);
+ uriInfo = Mockito.mock(UriInfo.class);
- headersMultiMap = new MultivaluedHashMap<>();
- queryParameters = Mockito.spy(new MultivaluedHashMap<>());
+ headersMultiMap = new MultivaluedHashMap<>();
+ queryParameters = Mockito.spy(new MultivaluedHashMap<>());
headersMultiMap.add("X-FromAppId", "JUNIT");
headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
@@ -100,7 +101,8 @@ public class HttpTestUtil extends RESTAPI {
when(httpHeaders.getMediaType()).thenReturn(APPLICATION_JSON);
}
- public Response doPut(String uri, String payload) throws UnsupportedEncodingException, AAIException {
+ public Response doPut(String uri, String payload)
+ throws UnsupportedEncodingException, AAIException {
this.init();
Response response = null;
@@ -112,26 +114,27 @@ public class HttpTestUtil extends RESTAPI {
uri = uri.replaceAll("/aai/", "");
logger.info("Starting the put request for the uri {} with payload {}", uri, payload);
- String [] arr = uri.split("/");
+ String[] arr = uri.split("/");
SchemaVersion version = null;
- if(arr.length > 1){
- if(arr[0].matches("^v\\d+")){
+ if (arr.length > 1) {
+ if (arr[0].matches("^v\\d+")) {
version = new SchemaVersion(arr[0]);
uri = uri.replaceAll("^v\\d+", "");
}
}
- if(version == null){
+ if (version == null) {
version = schemaVersions.getDefaultVersion();
}
Mockito.when(uriInfo.getPath()).thenReturn(uri);
- HttpEntry resourceHttpEntry = SpringContextAware.getBean("traversalHttpEntry", HttpEntry.class);
+ HttpEntry resourceHttpEntry =
+ SpringContextAware.getBean("traversalHttpEntry", HttpEntry.class);
resourceHttpEntry.setHttpEntryProperties(version);
- Loader loader = resourceHttpEntry.getLoader();
- dbEngine = resourceHttpEntry.getDbEngine();
+ Loader loader = resourceHttpEntry.getLoader();
+ dbEngine = resourceHttpEntry.getDbEngine();
URI uriObject = UriBuilder.fromPath(uri).build();
URIToObject uriToObject = new URIToObject(loader, uriObject);
@@ -139,50 +142,54 @@ public class HttpTestUtil extends RESTAPI {
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"));
+ 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"));
+ 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();
+ 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");
+ 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){
+ 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);
+ 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());
+ 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) {
+ if (response != null) {
logFailure(HttpMethod.PUT, response);
}
dbEngine.rollback();
@@ -204,33 +211,35 @@ public class HttpTestUtil extends RESTAPI {
uri = uri.replaceAll("/aai/", "");
logger.info("Starting the GET request for the uri {} with depth {}", uri, "all");
- String [] arr = uri.split("/");
+ String[] arr = uri.split("/");
SchemaVersion version = null;
- if(arr.length > 1){
- if(arr[0].matches("^v\\d+")){
+ if (arr.length > 1) {
+ if (arr[0].matches("^v\\d+")) {
version = new SchemaVersion(arr[0]);
uri = uri.replaceAll("^v\\d+", "");
}
}
- if(version == null){
+ if (version == null) {
version = schemaVersions.getDefaultVersion();
}
- HttpEntry resourceHttpEntry = SpringContextAware.getBean("traversalHttpEntry", HttpEntry.class);
+ HttpEntry resourceHttpEntry =
+ SpringContextAware.getBean("traversalHttpEntry", HttpEntry.class);
resourceHttpEntry.setHttpEntryProperties(version);
-
- Loader loader = resourceHttpEntry.getLoader();
- dbEngine = resourceHttpEntry.getDbEngine();
+
+ 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);
+ QueryParser uriQuery =
+ dbEngine.getQueryBuilder().createQueryFromURI(uriObject, queryParameters);
Mockito.when(uriInfo.getPath()).thenReturn(uri);
@@ -238,28 +247,32 @@ public class HttpTestUtil extends RESTAPI {
Introspector obj = loader.introspectorFromName(objType);
- DBRequest dbRequest =
- new DBRequest.Builder(HttpMethod.GET, uriObject, uriQuery, obj, httpHeaders, uriInfo, "JUNIT-TRANSACTION")
- .build();
+ 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");
+ 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);
+ response =
+ this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
success = false;
- } catch(Exception e){
+ } catch (Exception e) {
AAIException ex = new AAIException("AAI_4000", e);
- response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
+ 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());
+ 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);
}
@@ -274,7 +287,8 @@ public class HttpTestUtil extends RESTAPI {
return response;
}
- public Response doDelete(String uri, String resourceVersion) throws UnsupportedEncodingException, AAIException {
+ public Response doDelete(String uri, String resourceVersion)
+ throws UnsupportedEncodingException, AAIException {
this.init();
Response response = null;
@@ -284,43 +298,46 @@ public class HttpTestUtil extends RESTAPI {
try {
uri = uri.replaceAll("/aai/", "");
- logger.info("Starting the delete request for the uri {} with resource version {}", uri, resourceVersion);
+ logger.info("Starting the delete request for the uri {} with resource version {}", uri,
+ resourceVersion);
- String [] arr = uri.split("/");
+ String[] arr = uri.split("/");
SchemaVersion version = null;
- if(arr.length > 1){
- if(arr[0].matches("^v\\d+")){
+ if (arr.length > 1) {
+ if (arr[0].matches("^v\\d+")) {
version = new SchemaVersion(arr[0]);
- if(!uri.contains("relationship-list/relationship")){
+ if (!uri.contains("relationship-list/relationship")) {
uri = uri.replaceAll("^v\\d+", "");
}
}
}
- if(version == null){
+ if (version == null) {
version = schemaVersions.getDefaultVersion();
}
Mockito.when(uriInfo.getPath()).thenReturn(uri);
- HttpEntry resourceHttpEntry = SpringContextAware.getBean("traversalHttpEntry", HttpEntry.class);
+ HttpEntry resourceHttpEntry =
+ SpringContextAware.getBean("traversalHttpEntry", HttpEntry.class);
resourceHttpEntry.setHttpEntryProperties(version);
- Loader loader = resourceHttpEntry.getLoader();
- dbEngine = resourceHttpEntry.getDbEngine();
+ 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);
+ 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")){
+ if (uri.contains("/relationship-list/relationship")) {
obj = loader.introspectorFromName("relationship");
httpMethod = HttpMethod.DELETE_EDGE;
} else {
@@ -328,28 +345,32 @@ public class HttpTestUtil extends RESTAPI {
httpMethod = HttpMethod.DELETE;
}
- DBRequest dbRequest =
- new DBRequest.Builder(httpMethod, uriObject, uriQuery, obj, httpHeaders, uriInfo, "JUNIT-TRANSACTION")
- .build();
+ 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");
+ 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);
+ response =
+ this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, e);
success = false;
- } catch(Exception e){
+ } catch (Exception e) {
AAIException ex = new AAIException("AAI_4000", e);
- response = this.consumerExceptionResponseGenerator(httpHeaders, uriInfo, HttpMethod.PUT, ex);
+ 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());
+ 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);
}
@@ -364,8 +385,9 @@ public class HttpTestUtil extends RESTAPI {
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());
+ 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-traversal/src/test/java/org/onap/aai/PayloadUtil.java b/aai-traversal/src/test/java/org/onap/aai/PayloadUtil.java
index 8adc9d1..5a86d92 100644
--- a/aai-traversal/src/test/java/org/onap/aai/PayloadUtil.java
+++ b/aai-traversal/src/test/java/org/onap/aai/PayloadUtil.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,7 +19,7 @@
*/
package org.onap.aai;
-import org.apache.commons.io.IOUtils;
+import static org.junit.Assert.assertNotNull;
import java.io.IOException;
import java.io.InputStream;
@@ -28,7 +28,7 @@ import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
-import static org.junit.Assert.assertNotNull;
+import org.apache.commons.io.IOUtils;
public class PayloadUtil {
@@ -37,7 +37,8 @@ public class PayloadUtil {
public static String getExpectedPayload(String fileName) throws IOException {
- InputStream inputStream = PayloadUtil.class.getClassLoader().getResourceAsStream("payloads/expected/" + fileName);
+ InputStream inputStream =
+ PayloadUtil.class.getClassLoader().getResourceAsStream("payloads/expected/" + fileName);
String message = String.format("Unable to find the %s in src/test/resources", fileName);
assertNotNull(message, inputStream);
@@ -50,7 +51,8 @@ public class PayloadUtil {
public static String getResourcePayload(String fileName) throws IOException {
- InputStream inputStream = PayloadUtil.class.getClassLoader().getResourceAsStream("payloads/resource/" + fileName);
+ 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);
@@ -61,16 +63,18 @@ public class PayloadUtil {
return resource;
}
- public static String getTemplatePayload(String fileName, Map<String, String> templateValueMap) throws Exception {
+ public static String getTemplatePayload(String fileName, Map<String, String> templateValueMap)
+ throws Exception {
- InputStream inputStream = PayloadUtil.class.getClassLoader().getResourceAsStream("payloads/templates/" + fileName);
+ 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)){
+ if (cache.containsKey(fileName)) {
resource = cache.get(fileName);
} else {
resource = IOUtils.toString(inputStream);
@@ -81,26 +85,31 @@ public class PayloadUtil {
String resourceWithTemplateValues = resource;
- while(matcher.find()){
+ 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));
+ 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);
+ 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 getNamedQueryPayload(String fileName) throws IOException {
- InputStream inputStream = PayloadUtil.class.getClassLoader().getResourceAsStream("payloads/named-queries/" + fileName);
+ InputStream inputStream = PayloadUtil.class.getClassLoader()
+ .getResourceAsStream("payloads/named-queries/" + fileName);
- String message = String.format("Unable to find the %s in src/test/resources/payloads/named-queries", fileName);
+ String message = String
+ .format("Unable to find the %s in src/test/resources/payloads/named-queries", fileName);
assertNotNull(message, inputStream);
String resource = IOUtils.toString(inputStream);
diff --git a/aai-traversal/src/test/java/org/onap/aai/QueryParameterTest.java b/aai-traversal/src/test/java/org/onap/aai/QueryParameterTest.java
index faf0160..817ba28 100644
--- a/aai-traversal/src/test/java/org/onap/aai/QueryParameterTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/QueryParameterTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,16 +19,25 @@
*/
package org.onap.aai;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+
import com.att.eelf.configuration.EELFManager;
+
+import java.util.*;
+
+import javax.ws.rs.core.Response;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.aai.config.PropertyPasswordConfiguration;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.annotation.Import;
import org.springframework.http.*;
import org.springframework.test.context.ContextConfiguration;
@@ -36,15 +45,10 @@ import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
-import javax.ws.rs.core.Response;
-import java.util.*;
-
-import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertThat;
-
@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = TraversalApp.class)
+@SpringBootTest(
+ webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+ classes = TraversalApp.class)
@TestPropertySource(locations = "classpath:application-test.properties")
@ContextConfiguration(initializers = PropertyPasswordConfiguration.class)
@Import(TraversalTestConfiguration.class)
@@ -62,7 +66,6 @@ public class QueryParameterTest {
private String configurationUri2;
-
@Autowired
RestTemplate restTemplate;
@@ -96,14 +99,14 @@ public class QueryParameterTest {
httpTestUtil = new HttpTestUtil();
configurationId = "test-" + UUID.randomUUID().toString();
- configurationUri ="/aai/v13/network/configurations/configuration/" + configurationId;
+ configurationUri = "/aai/v13/network/configurations/configuration/" + configurationId;
Map<String, String> configurationMap = new HashMap<>();
configurationMap.put("configuration-id", configurationId);
String payload = PayloadUtil.getTemplatePayload("configuration.json", configurationMap);
httpTestUtil.doPut(configurationUri, payload);
configurationId2 = "test-" + UUID.randomUUID().toString();
- configurationUri2 ="/aai/v13/network/configurations/configuration/" + configurationId2;
+ configurationUri2 = "/aai/v13/network/configurations/configuration/" + configurationId2;
configurationMap.put("configuration-id", configurationId2);
payload = PayloadUtil.getTemplatePayload("configuration.json", configurationMap);
httpTestUtil.doPut(configurationUri2, payload);
@@ -112,7 +115,7 @@ public class QueryParameterTest {
serviceInstanceId = "test-service-instance1";
serviceInstanceName = "test service instance1";
- customerUri ="/aai/v13/business/network/customers/customer/" + customerId;
+ customerUri = "/aai/v13/business/network/customers/customer/" + customerId;
Map<String, String> customerMap = new HashMap<>();
customerMap.put("customer-id", customerId);
customerMap.put("service-instance-id", serviceInstanceId);
@@ -125,7 +128,7 @@ public class QueryParameterTest {
customerId2 = "test-" + UUID.randomUUID().toString();
serviceInstanceId2 = "test-service-instance2";
serviceInstanceName2 = "test service instance1";
- customerUri2 ="/aai/v13/business/customers/customer/" + customerId2;
+ customerUri2 = "/aai/v13/business/customers/customer/" + customerId2;
customerMap = new HashMap<>();
customerMap.put("customer-id", customerId2);
@@ -135,7 +138,7 @@ public class QueryParameterTest {
httpTestUtil.doPut(customerUri2, payload);
vnfId = "test-" + UUID.randomUUID().toString();
- vnfUri ="/aai/v13/network/generic-vnfs/generic-vnf/" + vnfId;
+ vnfUri = "/aai/v13/network/generic-vnfs/generic-vnf/" + vnfId;
Map<String, String> vnfMap = new HashMap<>();
vnfMap.put("vnf-id", vnfId);
vnfMap.put("configuration-id", configurationId);
@@ -145,7 +148,7 @@ public class QueryParameterTest {
httpTestUtil.doPut(vnfUri, payload);
vnfId2 = "test-" + UUID.randomUUID().toString();
- vnfUri2 ="/aai/v13/network/generic-vnfs/generic-vnf/" + vnfId2;
+ vnfUri2 = "/aai/v13/network/generic-vnfs/generic-vnf/" + vnfId2;
vnfMap = new HashMap<>();
vnfMap.put("vnf-id", vnfId2);
vnfMap.put("configuration-id", configurationId2);
@@ -180,7 +183,8 @@ public class QueryParameterTest {
String payload = PayloadUtil.getTemplatePayload("custom-query.json", customQueryMap);
httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
LOGGER.info("Response of custom query : {}", responseEntity.getBody().toString());
assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));
assertThat(responseEntity.getBody().toString(), containsString(customerUri2));
diff --git a/aai-traversal/src/test/java/org/onap/aai/SubgraphPruneTest.java b/aai-traversal/src/test/java/org/onap/aai/SubgraphPruneTest.java
index 42a4542..4aefa85 100644
--- a/aai-traversal/src/test/java/org/onap/aai/SubgraphPruneTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/SubgraphPruneTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,13 +19,20 @@
*/
package org.onap.aai;
+import static org.hamcrest.core.Is.is;
+import static org.junit.Assert.assertThat;
+
+import java.util.*;
+
+import javax.ws.rs.core.Response;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.onap.aai.config.PropertyPasswordConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.annotation.Import;
import org.springframework.http.*;
import org.springframework.test.context.ContextConfiguration;
@@ -33,20 +40,15 @@ import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
-import javax.ws.rs.core.Response;
-import java.util.*;
-
-import static org.hamcrest.core.Is.is;
-import static org.junit.Assert.assertThat;
-
@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = TraversalApp.class)
+@SpringBootTest(
+ webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+ classes = TraversalApp.class)
@TestPropertySource(locations = "classpath:application-test.properties")
@ContextConfiguration(initializers = PropertyPasswordConfiguration.class)
@Import(TraversalTestConfiguration.class)
public class SubgraphPruneTest {
-
private HttpTestUtil httpTestUtil;
private String pserverUri;
@@ -73,7 +75,7 @@ public class SubgraphPruneTest {
httpTestUtil = new HttpTestUtil();
hostname = "test-" + UUID.randomUUID().toString();
- pserverUri ="/aai/v11/cloud-infrastructure/pservers/pserver/" + hostname;
+ pserverUri = "/aai/v11/cloud-infrastructure/pservers/pserver/" + hostname;
Map<String, String> pserverMap = new HashMap<>();
pserverMap.put("hostname", hostname);
String payload = PayloadUtil.getTemplatePayload("pserver.json", pserverMap);
@@ -91,8 +93,10 @@ public class SubgraphPruneTest {
cloudRegionMap.put("vserver-name", "some-vserver-name-id1111");
cloudRegionMap.put("pserver-uri", pserverUri);
- String cloudRegionPayload = PayloadUtil.getTemplatePayload("cloud-region-with-vserver.json", cloudRegionMap);
- String cloudRegionUri = "/aai/v11/cloud-infrastructure/cloud-regions/cloud-region/some-owner-id1111/some-region-id1111";
+ String cloudRegionPayload =
+ PayloadUtil.getTemplatePayload("cloud-region-with-vserver.json", cloudRegionMap);
+ String cloudRegionUri =
+ "/aai/v11/cloud-infrastructure/cloud-regions/cloud-region/some-owner-id1111/some-region-id1111";
Response response = httpTestUtil.doPut(cloudRegionUri, cloudRegionPayload);
@@ -114,14 +118,16 @@ public class SubgraphPruneTest {
Map<String, String> gremlinQueryMap = new HashMap<>();
// Having the cap('x') here causes the subgraph to fail
- gremlinQueryMap.put("gremlin-query", "g.V().has('vserver-id', '" + vserverId + "').store('x').out().has('aai-node-type', 'pserver').store('x').cap('x').unfold()");
+ gremlinQueryMap.put("gremlin-query", "g.V().has('vserver-id', '" + vserverId
+ + "').store('x').out().has('aai-node-type', 'pserver').store('x').cap('x').unfold()");
String payload = PayloadUtil.getTemplatePayload("gremlin-query.json", gremlinQueryMap);
String endpoint = "/aai/v13/query?format=console&subgraph=prune";
httpEntity = new HttpEntity(payload, headers);
ResponseEntity responseEntity = null;
- responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
System.out.println(responseEntity.getBody().toString());
assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/TraversalTestConfiguration.java b/aai-traversal/src/test/java/org/onap/aai/TraversalTestConfiguration.java
index 516c6b9..8b94352 100644
--- a/aai-traversal/src/test/java/org/onap/aai/TraversalTestConfiguration.java
+++ b/aai-traversal/src/test/java/org/onap/aai/TraversalTestConfiguration.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,11 +19,19 @@
*/
package org.onap.aai;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import java.io.File;
+import java.io.FileInputStream;
+import java.io.IOException;
+import java.io.InputStream;
+import java.security.KeyStore;
+
+import javax.net.ssl.SSLContext;
+
import org.apache.http.client.HttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.ssl.SSLContextBuilder;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.TestConfiguration;
import org.springframework.boot.web.client.RestTemplateBuilder;
@@ -36,13 +44,6 @@ import org.springframework.util.ResourceUtils;
import org.springframework.web.client.ResponseErrorHandler;
import org.springframework.web.client.RestTemplate;
-import javax.net.ssl.SSLContext;
-import java.io.File;
-import java.io.FileInputStream;
-import java.io.IOException;
-import java.io.InputStream;
-import java.security.KeyStore;
-
@TestConfiguration
public class TraversalTestConfiguration {
@@ -60,31 +61,30 @@ public class TraversalTestConfiguration {
RestTemplate restTemplate = null;
- if(env.acceptsProfiles("one-way-ssl", "two-way-ssl")) {
- char[] trustStorePassword = env.getProperty("server.ssl.trust-store-password").toCharArray();
- char[] keyStorePassword = env.getProperty("server.ssl.key-store-password").toCharArray();
+ if (env.acceptsProfiles("one-way-ssl", "two-way-ssl")) {
+ char[] trustStorePassword =
+ env.getProperty("server.ssl.trust-store-password").toCharArray();
+ char[] keyStorePassword =
+ env.getProperty("server.ssl.key-store-password").toCharArray();
String keyStore = env.getProperty("server.ssl.key-store");
String trustStore = env.getProperty("server.ssl.trust-store");
SSLContextBuilder sslContextBuilder = SSLContextBuilder.create();
if (env.acceptsProfiles("two-way-ssl")) {
- sslContextBuilder = sslContextBuilder.loadKeyMaterial(loadPfx(keyStore, keyStorePassword), keyStorePassword);
+ sslContextBuilder = sslContextBuilder
+ .loadKeyMaterial(loadPfx(keyStore, keyStorePassword), keyStorePassword);
}
SSLContext sslContext = sslContextBuilder
- .loadTrustMaterial(ResourceUtils.getFile(trustStore), trustStorePassword)
- .build();
+ .loadTrustMaterial(ResourceUtils.getFile(trustStore), trustStorePassword).build();
- HttpClient client = HttpClients.custom()
- .setSSLContext(sslContext)
- .setSSLHostnameVerifier((s, sslSession) -> true)
- .build();
+ HttpClient client = HttpClients.custom().setSSLContext(sslContext)
+ .setSSLHostnameVerifier((s, sslSession) -> true).build();
restTemplate = builder
- .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(client))
- .build();
- }else {
+ .requestFactory(() -> new HttpComponentsClientHttpRequestFactory(client)).build();
+ } else {
restTemplate = builder.build();
}
@@ -100,7 +100,7 @@ public class TraversalTestConfiguration {
return true;
}
- if(clientHttpResponse.getRawStatusCode() % 100 == 5){
+ if (clientHttpResponse.getRawStatusCode() % 100 == 5) {
logger.debug("Call returned a error " + clientHttpResponse.getStatusText());
return true;
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/dbgraphgen/ModelBasedProcessingInvalidDataTest.java b/aai-traversal/src/test/java/org/onap/aai/dbgraphgen/ModelBasedProcessingInvalidDataTest.java
index e1515e3..842a6ca 100644
--- a/aai-traversal/src/test/java/org/onap/aai/dbgraphgen/ModelBasedProcessingInvalidDataTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/dbgraphgen/ModelBasedProcessingInvalidDataTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,8 +19,16 @@
*/
package org.onap.aai.dbgraphgen;
+import static org.junit.Assert.*;
+import static org.mockito.Matchers.any;
+import static org.mockito.Matchers.anyMapOf;
+import static org.mockito.Mockito.when;
+
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
+
+import java.util.*;
+
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.graphdb.types.system.BaseVertexLabel;
import org.janusgraph.graphdb.types.system.EmptyVertex;
@@ -40,13 +48,6 @@ import org.onap.aai.introspection.ModelType;
import org.onap.aai.serialization.db.DBSerializer;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-import java.util.*;
-
-import static org.junit.Assert.*;
-import static org.mockito.Matchers.any;
-import static org.mockito.Matchers.anyMapOf;
-import static org.mockito.Mockito.when;
-
@RunWith(MockitoJUnitRunner.class)
public class ModelBasedProcessingInvalidDataTest extends AAISetup {
@@ -60,7 +61,6 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
@Mock
private ModelBasedProcessing mockProcessor;
-
@Mock
private DbMethHelper dbMethHelper;
@@ -73,7 +73,8 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
@Before
public void init() {
MockitoAnnotations.initMocks(this);
- loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getDefaultVersion());
+ loader = loaderFactory.createLoaderForVersion(ModelType.MOXY,
+ schemaVersions.getDefaultVersion());
processor = new ModelBasedProcessing(loader, dbEngine, serializer);
dbMethHelper = new DbMethHelper(loader, dbEngine);
@@ -83,181 +84,161 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
@Test
public void getStartNodesAndModVersionIdsTest() throws AAIException {
-
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> startNodeFilterArrayOfHashes =
+ new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("test", new Object());
startNodeFilterArrayOfHashes.add(map);
Map<String, String> result = new HashMap<>();
Map<String, String> result1 = mockProcessor.getStartNodesAndModVersionIds("test", "test",
- "test", "test", "test",
- "test", startNodeFilterArrayOfHashes,
- "test");
+ "test", "test", "test", "test", startNodeFilterArrayOfHashes, "test");
assertNotNull(result);
}
-
@Test(expected = NullPointerException.class)
public void getStartNodesAndModVersionIdsTest2() throws AAIException {
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> startNodeFilterArrayOfHashes =
+ new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("test", new Object());
startNodeFilterArrayOfHashes.add(map);
- Map<String, String> result1 = processor.getStartNodesAndModVersionIds("test", "test",
- "", "test", "test",
- "test", startNodeFilterArrayOfHashes,
- "test");
+ Map<String, String> result1 = processor.getStartNodesAndModVersionIds("test", "test", "",
+ "test", "test", "test", startNodeFilterArrayOfHashes, "test");
assertNotNull(result1);
}
-
@Test(expected = NullPointerException.class)
public void getStartNodesAndModVersionIdsTest3() throws AAIException {
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> startNodeFilterArrayOfHashes =
+ new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("test", new Object());
startNodeFilterArrayOfHashes.add(map);
- Map<String, String> result1 = processor.getStartNodesAndModVersionIds("test", "test",
- "", "", "test",
- "test", startNodeFilterArrayOfHashes,
- "test");
+ Map<String, String> result1 = processor.getStartNodesAndModVersionIds("test", "test", "",
+ "", "test", "test", startNodeFilterArrayOfHashes, "test");
assertNotNull(result1);
}
-
@Test(expected = AAIException.class)
public void getStartNodesAndModVersionIdsTest4() throws AAIException {
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> startNodeFilterArrayOfHashes =
+ new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("test", new Object());
startNodeFilterArrayOfHashes.add(map);
- Map<String, String> result1 = processor.getStartNodesAndModVersionIds("test", "test",
- "", "", "",
- "test", startNodeFilterArrayOfHashes,
- "test");
+ Map<String, String> result1 = processor.getStartNodesAndModVersionIds("test", "test", "",
+ "", "", "test", startNodeFilterArrayOfHashes, "test");
assertNotNull(result1);
}
-
@Test(expected = AAIException.class)
public void getStartNodesAndModVersionIdsTest5() throws AAIException {
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> startNodeFilterArrayOfHashes =
+ new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("test", new Object());
startNodeFilterArrayOfHashes.add(map);
- Map<String, String> result1 = processor.getStartNodesAndModVersionIds("test", "test",
- "", "", "",
- "", startNodeFilterArrayOfHashes,
- "test");
+ Map<String, String> result1 = processor.getStartNodesAndModVersionIds("test", "test", "",
+ "", "", "", startNodeFilterArrayOfHashes, "test");
assertNotNull(result1);
}
-
@Test(expected = AAIException.class)
public void getStartNodesAndModVersionIdsNullTest() throws AAIException {
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> startNodeFilterArrayOfHashes =
+ new ArrayList<Map<String, Object>>();
Map<String, String> result = null;
- result = processor.getStartNodesAndModVersionIds("test", "test",
- "", "", "",
- "", startNodeFilterArrayOfHashes,
- "test");
+ result = processor.getStartNodesAndModVersionIds("test", "test", "", "", "", "",
+ startNodeFilterArrayOfHashes, "test");
assertNotNull(result);
}
-
@Test(expected = NullPointerException.class)
public void getStartNodesAndModVersionIdsNullTest1() throws AAIException {
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> startNodeFilterArrayOfHashes =
+ new ArrayList<Map<String, Object>>();
Map<String, String> result = null;
- result = processor.getStartNodesAndModVersionIds("test", "test",
- "Test", "", "",
- "", startNodeFilterArrayOfHashes,
- "test");
+ result = processor.getStartNodesAndModVersionIds("test", "test", "Test", "", "", "",
+ startNodeFilterArrayOfHashes, "test");
assertNotNull(result);
}
@Test(expected = NullPointerException.class)
public void getStartNodesAndModVersionIdsNullTest2() throws AAIException {
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> startNodeFilterArrayOfHashes =
+ new ArrayList<Map<String, Object>>();
Map<String, String> result = null;
- result = processor.getStartNodesAndModVersionIds("test", "test",
- "", "test", "",
- "", startNodeFilterArrayOfHashes,
- "test");
+ result = processor.getStartNodesAndModVersionIds("test", "test", "", "test", "", "",
+ startNodeFilterArrayOfHashes, "test");
assertNotNull(result);
}
-
@Test(expected = NullPointerException.class)
public void getStartNodesAndModVersionIdsNullTest3() throws AAIException {
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> startNodeFilterArrayOfHashes =
+ new ArrayList<Map<String, Object>>();
Map<String, String> result = null;
- result = processor.getStartNodesAndModVersionIds("test", "test",
- "", "", "test",
- "", startNodeFilterArrayOfHashes,
- "test");
+ result = processor.getStartNodesAndModVersionIds("test", "test", "", "", "test", "",
+ startNodeFilterArrayOfHashes, "test");
assertNotNull(result);
}
@Test(expected = NullPointerException.class)
public void getModelVerTopWidgetTypeTest() throws AAIException {
Vertex vertex = new EmptyVertex();
- //Mockito.when(mockProcessor.getModelVerTopWidgetType(Mockito.any(Vertex.class), Mockito.any(String.class))).thenReturn("Sucess");
+ // Mockito.when(mockProcessor.getModelVerTopWidgetType(Mockito.any(Vertex.class),
+ // Mockito.any(String.class))).thenReturn("Sucess");
String result = processor.getModelVerTopWidgetType(vertex, "test");
- assertEquals("result has -local tacked on the end as it should", "Sucess", result
- );
+ assertEquals("result has -local tacked on the end as it should", "Sucess", result);
}
@Test(expected = NullPointerException.class)
public void getModelVerTopWidgetType() throws AAIException {
- /*Mockito.when(mockProcessor.getModelVerTopWidgetType(Mockito.any(String.class),
- Mockito.any(String.class), Mockito.any(String.class),
- Mockito.any(String.class), Mockito.any(String.class))
- ).thenReturn("Sucess");*/
+ /*
+ * Mockito.when(mockProcessor.getModelVerTopWidgetType(Mockito.any(String.class),
+ * Mockito.any(String.class), Mockito.any(String.class),
+ * Mockito.any(String.class), Mockito.any(String.class))
+ * ).thenReturn("Sucess");
+ */
String result = processor.getModelVerTopWidgetType("test", "test", "test", "Test", "test");
- assertEquals("result has -local tacked on the end as it should", "Sucess", result
- );
+ assertEquals("result has -local tacked on the end as it should", "Sucess", result);
}
@Test(expected = AAIException.class)
public void queryByModel() throws AAIException {
- /*Mockito.when(mockProcessor.getModelVerTopWidgetType(Mockito.any(String.class),
- Mockito.any(String.class), Mockito.any(String.class),
- Mockito.any(String.class), Mockito.any(String.class))
- ).thenReturn("Sucess");*/
- List<ResultSet> result = processor.queryByModel("test", "test",
- "test", "test", "test",
- "generic-vnf", null,
- "test");
+ /*
+ * Mockito.when(mockProcessor.getModelVerTopWidgetType(Mockito.any(String.class),
+ * Mockito.any(String.class), Mockito.any(String.class),
+ * Mockito.any(String.class), Mockito.any(String.class))
+ * ).thenReturn("Sucess");
+ */
+ List<ResultSet> result = processor.queryByModel("test", "test", "test", "test", "test",
+ "generic-vnf", null, "test");
assertEquals("result has -local tacked on the end as it should", 0, result.size());
-
}
-
@Test(expected = NullPointerException.class)
public void queryByModel_Timed() throws AAIException {
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> startNodeFilterArrayOfHashes =
+ new ArrayList<Map<String, Object>>();
Map<String, Object> map = new HashMap<String, Object>();
map.put("test", new Object());
startNodeFilterArrayOfHashes.add(map);
- List<ResultSet> result = processor.queryByModel_Timed("test", "test",
- "test", "test", "test",
- "test", startNodeFilterArrayOfHashes,
- "test");
+ List<ResultSet> result = processor.queryByModel_Timed("test", "test", "test", "test",
+ "test", "test", startNodeFilterArrayOfHashes, "test");
assertEquals("result has -local tacked on the end as it should", 0, result.size());
-
}
@Mock
@@ -267,17 +248,14 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
public void runDeleteByModel() throws AAIException {
Map<String, String> resultMock = new HashMap<String, String>();
- // when(mockProcessor.getNodeUsingUniqueId(any(String.class),any(String.class),any(String.class),any(String.class),any(String.class))).thenReturn(vertex);
- when(mockProcessor.runDeleteByModel(any(String.class),
- any(String.class), any(String.class),
- any(String.class), anyMapOf(String.class, Object.class), any(String.class), any(String.class))
- ).thenReturn(resultMock);
- Map<String, String> result = processor.runDeleteByModel("test", "test",
- "test", "test", startNodeFilterHash,
- "test",
- "test");
- assertEquals("result has -local tacked on the end as it should", result.size(), resultMock.size());
-
+ // when(mockProcessor.getNodeUsingUniqueId(any(String.class),any(String.class),any(String.class),any(String.class),any(String.class))).thenReturn(vertex);
+ when(mockProcessor.runDeleteByModel(any(String.class), any(String.class), any(String.class),
+ any(String.class), anyMapOf(String.class, Object.class), any(String.class),
+ any(String.class))).thenReturn(resultMock);
+ Map<String, String> result = processor.runDeleteByModel("test", "test", "test", "test",
+ startNodeFilterHash, "test", "test");
+ assertEquals("result has -local tacked on the end as it should", result.size(),
+ resultMock.size());
}
@@ -287,11 +265,8 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
public void runDeleteByModelWithNullParams() throws AAIException {
Map<String, String> resultMock = new HashMap<String, String>();
-
- Map<String, String> result = processor.runDeleteByModel("test", "test",
- null, null, null,
- "test",
- "test");
+ Map<String, String> result =
+ processor.runDeleteByModel("test", "test", null, null, null, "test", "test");
assertNotNull(result);
@@ -300,22 +275,17 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
@Test(expected = NullPointerException.class)
public void runDeleteByModelWithNullParams1() throws AAIException {
- Map<String, String> result1 = processor.runDeleteByModel("test", "test",
- null, "unknown", null,
- "test",
- "test");
+ Map<String, String> result1 =
+ processor.runDeleteByModel("test", "test", null, "unknown", null, "test", "test");
assertNotNull(result1);
}
-
@Test(expected = NullPointerException.class)
public void runDeleteByModelWithNullParams2() throws AAIException {
- Map<String, String> result1 = processor.runDeleteByModel("test", "test",
- null, "unknown", null,
- "test",
- "test");
+ Map<String, String> result1 =
+ processor.runDeleteByModel("test", "test", null, "unknown", null, "test", "test");
assertNotNull(result1);
}
@@ -325,9 +295,11 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
String transId = "test";
String fromAppId = "test";
String namedQueryUuid = "test";
- ArrayList<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<Map<String, Object>>();
+ ArrayList<Map<String, Object>> startNodeFilterArrayOfHashes =
+ new ArrayList<Map<String, Object>>();
String apiVer = "test";
- List<ResultSet> result = processor.queryByNamedQuery(transId, fromAppId, namedQueryUuid, startNodeFilterArrayOfHashes, apiVer);
+ List<ResultSet> result = processor.queryByNamedQuery(transId, fromAppId, namedQueryUuid,
+ startNodeFilterArrayOfHashes, apiVer);
assertNotNull(result);
}
@@ -337,10 +309,12 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
String fromAppId = "test";
String namedQueryUuid = "test";
String secondaryFilterCutPoint = "test";
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<Map<String, Object>>();
+ List<Map<String, Object>> startNodeFilterArrayOfHashes =
+ new ArrayList<Map<String, Object>>();
String apiVer = "test";
Map<String, Object> secondaryFilterHash = new HashMap<String, Object>();
- List<ResultSet> result = processor.queryByNamedQuery(transId, fromAppId, namedQueryUuid, startNodeFilterArrayOfHashes, apiVer, secondaryFilterCutPoint, secondaryFilterHash);
+ List<ResultSet> result = processor.queryByNamedQuery(transId, fromAppId, namedQueryUuid,
+ startNodeFilterArrayOfHashes, apiVer, secondaryFilterCutPoint, secondaryFilterHash);
assertNotNull(result);
}
@@ -352,22 +326,17 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
resultSet.setVert(null);
Map<String, String> result = processor.deleteAsNeededFromResultSet("test", "test",
- resultSet, "test", "test",
- "test",
- resultMock);
+ resultSet, "test", "test", "test", resultMock);
assertEquals(result.size(), 0);
resultSet.setVert(vert);
Map<String, String> result1 = processor.deleteAsNeededFromResultSet("test", "test",
- resultSet, "test", "test",
- "test",
- resultMock);
+ resultSet, "test", "test", "test", resultMock);
assertEquals(result.size(), 0);
-
}
@Test(expected = NullPointerException.class)
@@ -414,7 +383,7 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
rsList.add(rs1);
rs.setSubResultSet(rsList);
Map<String, Object> map = new HashMap<String, Object>();
- //map.put("test.filter",new Object());
+ // map.put("test.filter",new Object());
boolean result = processor.satisfiesFilters(rs, map);
assertEquals(result, false);
@@ -452,12 +421,11 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
public void collectInstanceDataTest() throws AAIException {
BaseVertexLabel bs = new BaseVertexLabel("test");
- //bs.setId(80);
+ // bs.setId(80);
EmptyVertex ev = new EmptyVertex();
- //ev.setId(50l);
+ // ev.setId(50l);
Vertex thisLevelElemVtx = ev;
-
Multimap<String, String> thisMap = ArrayListMultimap.create();
List<String> vidsTraversed = new ArrayList<String>();
// only applies when collecting data using the default model for delete
@@ -466,22 +434,23 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
namedQueryElementHash.put("test", "test");
Map<String, String> delKeyHash = new HashMap<String, String>();
- ResultSet rs = processor.collectInstanceData("test", "test", thisLevelElemVtx, "test", validNextStepMap, vidsTraversed, 1, delKeyHash, namedQueryElementHash, "test");
+ ResultSet rs = processor.collectInstanceData("test", "test", thisLevelElemVtx, "test",
+ validNextStepMap, vidsTraversed, 1, delKeyHash, namedQueryElementHash, "test");
}
@Test(expected = NullPointerException.class)
- public void genTopoMap4ModelVerTest() throws
- AAIException {
+ public void genTopoMap4ModelVerTest() throws AAIException {
Vertex vertext = new EmptyVertex();
- Multimap<String, String> map = processor.genTopoMap4ModelVer("test", "test", vertext, "test");
+ Multimap<String, String> map =
+ processor.genTopoMap4ModelVer("test", "test", vertext, "test");
assertNotEquals(map, null);
}
@Test(expected = AAIException.class)
- public void genTopoMap4ModelVerTestNull() throws
- AAIException {
+ public void genTopoMap4ModelVerTestNull() throws AAIException {
Vertex vertext = null;
- Multimap<String, String> map = processor.genTopoMap4ModelVer("test", "test", vertext, "test");
+ Multimap<String, String> map =
+ processor.genTopoMap4ModelVer("test", "test", vertext, "test");
assertNotEquals(map, null);
}
@@ -495,7 +464,7 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
@Test(expected = AAIException.class)
public void getModConstraintHashTest() throws AAIException {
Vertex modelElementVtx = new EmptyVertex();
- //modelElementVtx.property(AAIProperties.NODE_TYPE,"Model");
+ // modelElementVtx.property(AAIProperties.NODE_TYPE,"Model");
Vertex modelElementVtx1 = new EmptyVertex();
Map<String, Vertex> currentHash = new HashMap<String, Vertex>();
currentHash.put("constraint", modelElementVtx1);
@@ -506,7 +475,7 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
@Test(expected = AAIException.class)
public void getModConstraintHashTestNull() throws AAIException {
Vertex modelElementVtx = null;
- //modelElementVtx.property(AAIProperties.NODE_TYPE,"Model");
+ // modelElementVtx.property(AAIProperties.NODE_TYPE,"Model");
Vertex modelElementVtx1 = null;
Map<String, Vertex> currentHash = new HashMap<String, Vertex>();
currentHash.put("constraint", modelElementVtx1);
@@ -517,7 +486,7 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
@Test(expected = NullPointerException.class)
public void getTopElementForSvcOrResModelVerTest() throws AAIException {
Vertex modelElementVtx = new EmptyVertex();
- //modelElementVtx.property(AAIProperties.NODE_TYPE,"Model");
+ // modelElementVtx.property(AAIProperties.NODE_TYPE,"Model");
Vertex modelElementVtx1 = new EmptyVertex();
Map<String, Vertex> currentHash = new HashMap<String, Vertex>();
currentHash.put("constraint", modelElementVtx1);
@@ -535,7 +504,8 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
namedQueryElementVertex.properties("property-collect-list", "");
- Map<String, Object> result = processor.getNamedQueryPropOverRide(transId, fromAppId, namedQueryElementVertex, instanceVertex, apiVer);
+ Map<String, Object> result = processor.getNamedQueryPropOverRide(transId, fromAppId,
+ namedQueryElementVertex, instanceVertex, apiVer);
assertNotEquals(result, null);
}
@@ -549,7 +519,8 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
namedQueryElementVertex.properties("property-collect-list", "");
- Map<String, Object> result = processor.getNamedQueryPropOverRide(transId, fromAppId, namedQueryElementVertex, instanceVertex, apiVer);
+ Map<String, Object> result = processor.getNamedQueryPropOverRide(transId, fromAppId,
+ namedQueryElementVertex, instanceVertex, apiVer);
assertNotEquals(result, null);
}
@@ -563,7 +534,8 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
namedQueryElementVertex.properties("property-collect-list", "");
- boolean result = processor.namedQueryConstraintSaysStop(transId, fromAppId, namedQueryElementVertex, instanceVertex, apiVer);
+ boolean result = processor.namedQueryConstraintSaysStop(transId, fromAppId,
+ namedQueryElementVertex, instanceVertex, apiVer);
assertTrue(result);
}
@@ -577,7 +549,8 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
namedQueryElementVertex.properties("property-collect-list", "");
- boolean result = processor.namedQueryConstraintSaysStop(transId, fromAppId, namedQueryElementVertex, instanceVertex, apiVer);
+ boolean result = processor.namedQueryConstraintSaysStop(transId, fromAppId,
+ namedQueryElementVertex, instanceVertex, apiVer);
assertTrue(result);
}
@@ -589,8 +562,8 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
Vertex instanceVertex = null;
String apiVer = "test";
-
- boolean result = processor.namedQueryConstraintSaysStop(transId, fromAppId, namedQueryElementVertex, instanceVertex, apiVer);
+ boolean result = processor.namedQueryConstraintSaysStop(transId, fromAppId,
+ namedQueryElementVertex, instanceVertex, apiVer);
assertTrue(result);
}
@@ -606,7 +579,8 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
namedQueryElementVertex.properties("property-collect-list", "");
- Map<String, Object> result = processor.getNamedQueryExtraDataLookup(transId, fromAppId, namedQueryElementVertex, instanceVertex, apiVer);
+ Map<String, Object> result = processor.getNamedQueryExtraDataLookup(transId, fromAppId,
+ namedQueryElementVertex, instanceVertex, apiVer);
assertTrue(result.size() > 0);
}
@@ -622,8 +596,7 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
int levelCounter = 1;
Map<String, String> result = processor.collectNQElementHash(transId, fromAppId,
- thisLevelElemVtx, incomingTrail, currentHash,
- vidsTraversed, levelCounter);
+ thisLevelElemVtx, incomingTrail, currentHash, vidsTraversed, levelCounter);
assertNotEquals(result, null);
}
@@ -642,8 +615,8 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
String overRideModelVersionId = "test";
Map<String, String> result = processor.collectDeleteKeyHash(transId, fromAppId,
- thisLevelElemVtx, incomingTrail, currentHash,
- vidsTraversed, levelCounter, modConstraintHash, overRideModelId, overRideModelVersionId);
+ thisLevelElemVtx, incomingTrail, currentHash, vidsTraversed, levelCounter,
+ modConstraintHash, overRideModelId, overRideModelVersionId);
assertNotEquals(result, null);
}
@@ -680,9 +653,9 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
List<String> vidsTraversed = new ArrayList<String>();
int levelCounter = 1;
- Multimap<String, String> result = processor.collectTopology4ModelVer(transId, fromAppId,
- thisLevelElemVtx, incomingTrail, thisMap, vidsTraversed, levelCounter, currentHash
- , "test", "test");
+ Multimap<String, String> result =
+ processor.collectTopology4ModelVer(transId, fromAppId, thisLevelElemVtx, incomingTrail,
+ thisMap, vidsTraversed, levelCounter, currentHash, "test", "test");
assertNotEquals(result, null);
}
@@ -700,7 +673,8 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
String incomingTrail = "test";
Multimap<String, String> currentMap = ArrayListMultimap.create();
- Multimap<String, String> result = processor.collectTopology4LinkagePoint(transId, fromAppId, linkagePointStrVal, incomingTrail, currentMap);
+ Multimap<String, String> result = processor.collectTopology4LinkagePoint(transId, fromAppId,
+ linkagePointStrVal, incomingTrail, currentMap);
assertNotEquals(result, null);
}
@@ -719,7 +693,8 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
String fromAppId = "test";
Vertex queryVertex = new EmptyVertex();
String namedQueryUuid = "E44533334343";
- Multimap<String, String> result = processor.genTopoMap4NamedQ(transId, fromAppId, queryVertex, namedQueryUuid);
+ Multimap<String, String> result =
+ processor.genTopoMap4NamedQ(transId, fromAppId, queryVertex, namedQueryUuid);
assertNotEquals(result, null);
}
@@ -735,7 +710,7 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
int levelCounter = 1;
Multimap<String, String> result = processor.collectTopology4NamedQ(transId, fromAppId,
- thisLevelElemVtx, incomingTrail, thisMap, vidsTraversed, levelCounter);
+ thisLevelElemVtx, incomingTrail, thisMap, vidsTraversed, levelCounter);
assertNotEquals(result, null);
}
@@ -785,7 +760,6 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
boolean vertex = processor.nodeTypeSupportsPersona(incomingTrail);
assertFalse(vertex);
-
incomingTrail = "test";
boolean vertex1 = processor.nodeTypeSupportsPersona(incomingTrail);
assertTrue(vertex1);
@@ -797,11 +771,11 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
String transID = "test";
Vertex thisLevelElemVtx = new EmptyVertex();
String incomingTrail = "test";
- String vertex1 = processor.getNqElementWidgetType(appId, transID, thisLevelElemVtx, incomingTrail);
+ String vertex1 =
+ processor.getNqElementWidgetType(appId, transID, thisLevelElemVtx, incomingTrail);
assertNotEquals(vertex1, null);
}
-
@Test(expected = NullPointerException.class)
public void getModElementWidgetType() throws AAIException {
String appId = "test";
@@ -819,11 +793,11 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
String nodeType = "generic-vnf";
String idPropertyName = "test";
String uniqueIdVal = "test";
- Vertex vertex1 = processor.getNodeUsingUniqueId(transID, appId, nodeType, idPropertyName, uniqueIdVal);
+ Vertex vertex1 =
+ processor.getNodeUsingUniqueId(transID, appId, nodeType, idPropertyName, uniqueIdVal);
assertNotEquals(vertex1, null);
}
-
@Test(expected = AAIException.class)
public void getNodeUsingUniqueIdNull() throws AAIException {
String appId = "test";
@@ -832,12 +806,12 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
String idPropertyName = "test";
String uniqueIdVal = "";
Vertex vertex1 = null;
- vertex1 = processor.getNodeUsingUniqueId(transID, appId, nodeType, idPropertyName, uniqueIdVal);
+ vertex1 =
+ processor.getNodeUsingUniqueId(transID, appId, nodeType, idPropertyName, uniqueIdVal);
assertNotEquals(vertex1, null);
}
-
@Test(expected = AAIException.class)
public void getNodeUsingUniqueIdNull1() throws AAIException {
String appId = "test";
@@ -846,13 +820,12 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
String idPropertyName = "";
String uniqueIdVal = "test";
Vertex vertex1 = null;
- vertex1 = processor.getNodeUsingUniqueId(transID, appId, nodeType, idPropertyName, uniqueIdVal);
+ vertex1 =
+ processor.getNodeUsingUniqueId(transID, appId, nodeType, idPropertyName, uniqueIdVal);
assertNotEquals(vertex1, null);
-
}
-
@Test(expected = AAIException.class)
public void getNodeUsingUniqueIdNull2() throws AAIException {
String appId = "test";
@@ -861,10 +834,10 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
String idPropertyName = "test";
String uniqueIdVal = "test";
Vertex vertex1 = null;
- vertex1 = processor.getNodeUsingUniqueId(transID, appId, nodeType, idPropertyName, uniqueIdVal);
+ vertex1 =
+ processor.getNodeUsingUniqueId(transID, appId, nodeType, idPropertyName, uniqueIdVal);
assertNotEquals(vertex1, null);
-
}
@Test(expected = NullPointerException.class)
@@ -877,7 +850,6 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
assertNotEquals(result, null);
}
-
@Test(expected = AAIException.class)
public void getModelVersUsingNameNull() throws AAIException {
String appId = "test";
@@ -888,7 +860,6 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
assertNotEquals(result, null);
}
-
@Test(expected = NullPointerException.class)
public void getModVersUsingModelInvId() throws AAIException {
String appId = "test";
@@ -959,9 +930,6 @@ public class ModelBasedProcessingInvalidDataTest extends AAISetup {
String modelName = "test";
processor.validateModel(transID, appId, modelName, modelVersionId);
-
}
-
}
-
diff --git a/aai-traversal/src/test/java/org/onap/aai/dbgraphgen/ModelBasedProcessingTest.java b/aai-traversal/src/test/java/org/onap/aai/dbgraphgen/ModelBasedProcessingTest.java
index 80f6d34..ab1ea0a 100644
--- a/aai-traversal/src/test/java/org/onap/aai/dbgraphgen/ModelBasedProcessingTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/dbgraphgen/ModelBasedProcessingTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -21,6 +21,12 @@ package org.onap.aai.dbgraphgen;
import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Multimap;
+
+import java.util.ArrayList;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
@@ -42,12 +48,7 @@ import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.setup.SchemaVersion;
-import java.util.ArrayList;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-public class ModelBasedProcessingTest extends AAISetup{
+public class ModelBasedProcessingTest extends AAISetup {
private SchemaVersion version;
private static final ModelType introspectorFactoryType = ModelType.MOXY;
@@ -57,828 +58,917 @@ public class ModelBasedProcessingTest extends AAISetup{
private static final String FROM_APP_ID = "JUNIT";
private static final String API_VERSION = "1.0";
private static final String AAI_NODE_TYPE = "aai-node-type";
-
+
private static final String MODEL_VESION_NODE_VALUE = "model-ver";
private static final String MODEL_VERSION_ID_KEY = "model-version-id";
private static final String MODEL_VERSION_ID_VALUE = "model-version-id-1";
-
+
private static final String MODEL_INVARIANT_ID_NODE_VALUE = "model-invariant-id-local";
private static final String MODEL_INVARIANT_ID_KEY = "model-invariant-id-local";
private static final String MODEL_INVARIANT_ID_VALUE = "model-invariant-id-1";
-
+
private static final String MODEL_NAME_NODE_VALUE = "model-name";
private static final String MODEL_NAME_ID_KEY = "model-name";
private static final String MODEL_NAME_ID_VALUE = "generic-vnf";
-
-
- private static TransactionalGraphEngine dbEngine;
- private static TransactionalGraphEngine.Admin admin;
- DBSerializer serializer;
- private static Loader loader;
-
- ModelBasedProcessing modelBasedProcessor;
-
- GraphTraversalSource source;
-
- Graph graph;
-
- Vertex model;
- Vertex modelVersion;
- Vertex modelElement;
- Vertex constrainedElementSet;
- Vertex namedQueryElement;
- Vertex linkagePoints;
- Vertex namedQuery;
-
- @BeforeClass
- public static void configure() throws Exception {
- System.setProperty("AJSC_HOME", ".");
- System.setProperty("BUNDLECONFIG_DIR", "src/main/resources");
- }
-
- @Before
- public void init() throws AAIException {
- MockitoAnnotations.initMocks(this);
- version = schemaVersions.getDefaultVersion();
- loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- TransactionalGraphEngine newDbEngine = new JanusGraphDBEngine(queryStyle, loader);
- dbEngine = Mockito.spy(newDbEngine);
- serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, "JUNIT");
- admin = Mockito.spy(dbEngine.asAdmin());
- modelBasedProcessor = new ModelBasedProcessing(loader, dbEngine, serializer);
- graph = TinkerGraph.open();
- source = createGraph();
- }
-
- private GraphTraversalSource createGraph() throws AAIException {
- model = graph.addVertex(T.label, "model", T.id, "0", AAI_NODE_TYPE, "model", "model-invariant-id", "model-invariant-id-1", "model-type", "widget");
- modelVersion = graph.addVertex(T.label, MODEL_VESION_NODE_VALUE, T.id, "1", AAI_NODE_TYPE, MODEL_VESION_NODE_VALUE, MODEL_VERSION_ID_KEY,
- MODEL_VERSION_ID_VALUE,MODEL_NAME_ID_KEY, MODEL_NAME_ID_VALUE, "model-version", "model-version-1");
- graph.addVertex(T.label, MODEL_INVARIANT_ID_NODE_VALUE, T.id, "2", MODEL_INVARIANT_ID_KEY, MODEL_INVARIANT_ID_VALUE, "model-version-id-local", MODEL_VERSION_ID_VALUE);
- namedQuery = graph.addVertex(T.label, "named-query", T.id, "3","aai-node-type", "named-query", "named-query-uuid", "named-query-uuid-1");
- graph.addVertex(T.label, MODEL_NAME_NODE_VALUE, T.id, "4", AAI_NODE_TYPE, MODEL_NAME_NODE_VALUE, MODEL_NAME_ID_KEY, MODEL_NAME_ID_VALUE);
- modelElement = graph.addVertex(T.label, "model-element", T.id, "5", AAI_NODE_TYPE, "model-element");
- Vertex modelConstraint = graph.addVertex(T.label, "model-constraint", T.id, "6", AAI_NODE_TYPE, "model-constraint","constrained-element-set-uuid-2-replace","cesu2r-1");
- constrainedElementSet = graph.addVertex(T.label, "constrained-element-set", T.id, "7", AAI_NODE_TYPE, "constrained-element-set");
- Vertex elementChoiceSet = graph.addVertex(T.label, "element-choice-set", T.id, "8", AAI_NODE_TYPE, "element-choice-set");
- namedQueryElement = graph.addVertex(T.label, "named-query-element", T.id, "9","aai-node-type", "named-query-element",
- "property-limit-desc", "show-all", "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
- "property-collect-list", "property-collect-list-1");
- linkagePoints = graph.addVertex(T.label, "linkage-points", T.id, "10", AAI_NODE_TYPE, "linkage-points", "linkage-points", getArrayListAsString(),
- "new-data-del-flag", "F");
-
- GraphTraversalSource g = graph.traversal();
- edgeSer.addTreeEdge(g, model, modelVersion);
- edgeSer.addTreeEdge(g, modelElement, modelConstraint);
- edgeSer.addTreeEdge(g, constrainedElementSet, modelConstraint);
- edgeSer.addTreeEdge(g, modelVersion, modelElement);
- edgeSer.addTreeEdge(g, modelElement, constrainedElementSet);
- edgeSer.addTreeEdge(g, constrainedElementSet, elementChoiceSet);
- edgeSer.addTreeEdge(g, modelElement, elementChoiceSet);
- edgeSer.addTreeEdge(g, namedQuery, namedQueryElement);
- edgeSer.addTreeEdge(g, namedQueryElement, namedQueryElement);
- edgeSer.addEdge(g, modelVersion, modelElement);
- edgeSer.addEdge(g, model, namedQueryElement);
- return g;
- }
-
- @Test(expected=AAIException.class)
- public void testGetStartNodesAndModVersionIds_NullId_ExpectException() throws AAIException {
- List<Map<String,Object>> startNodeFilterArrayOfHashes=new ArrayList<>();
- String passedModelVerId = null;
- String passedModelInvId = null;
- String passedModelName = null;
- modelBasedProcessor.getStartNodesAndModVersionIds("9999","postmen",passedModelVerId,passedModelInvId,
- passedModelName,"generic-vnf",startNodeFilterArrayOfHashes,"");
- }
-
- @Test
- public void testGetStartNodesAndModVersionIds_ModelVersion() throws AAIException {
-
- List<Map<String,Object>> startNodeFilterArrayOfHashes=new ArrayList<>();
- String passedModelInvId = null;
- String passedModelName = null;
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID, MODEL_VERSION_ID_VALUE, passedModelInvId, passedModelName,
- AAI_NODE_TYPE, startNodeFilterArrayOfHashes, API_VERSION);
- }
-
- @Test
- public void testGetStartNodesAndModVersionIds_ModelInId() throws AAIException {
- List<Map<String,Object>> startNodeFilterArrayOfHashes=new ArrayList<>();
- String passedModelVersion = null;
- String passedModelName = null;
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID,passedModelVersion,MODEL_INVARIANT_ID_VALUE, passedModelName,
- AAI_NODE_TYPE, startNodeFilterArrayOfHashes, API_VERSION);
- }
-
- @Test
- public void testGetStartNodesAndModVersionIds_ModelName() throws AAIException {
- List<Map<String,Object>> startNodeFilterArrayOfHashes=new ArrayList<>();
- String passedModelVersion = null;
- String passedModelInvId = null;
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID,passedModelVersion,passedModelInvId, MODEL_NAME_ID_VALUE,
- AAI_NODE_TYPE, startNodeFilterArrayOfHashes, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testGetStartNodesAndModVersionIds_NonEmptyHashMap_ModelVersion() throws AAIException {
- Map<String, Object> map = new HashMap<>();
- map.put("model-ver.model-name", "model-name");
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
- startNodeFilterArrayOfHashes.add(map);
- String passedModelInvId = null;
- String passedModelName = null;
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID, MODEL_VERSION_ID_VALUE, passedModelInvId, passedModelName,
- MODEL_NAME_ID_VALUE, startNodeFilterArrayOfHashes, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testGetStartNodesAndModVersionIds_NonEmptyHashMap_ModelInvId() throws AAIException {
- Map<String, Object> map = new HashMap<>();
- map.put("model-ver.model-name", "model-name");
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
- startNodeFilterArrayOfHashes.add(map);
- String passedModelVersion = null;
- String passedModelName = null;
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID,passedModelVersion,MODEL_INVARIANT_ID_VALUE, passedModelName,
- MODEL_NAME_ID_VALUE, startNodeFilterArrayOfHashes, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testGetStartNodesAndModVersionIds_NonEmptyHashMap_ModelName() throws AAIException {
- Map<String, Object> map = new HashMap<>();
- map.put("model-ver.model-name", "model-name");
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
- startNodeFilterArrayOfHashes.add(map);
- String passedModelVersion = null;
- String passedModelInvId = null;
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID,passedModelVersion,passedModelInvId, MODEL_NAME_ID_VALUE,
- MODEL_NAME_ID_VALUE, startNodeFilterArrayOfHashes, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testQueryByModel() throws AAIException {
- List<Map<String,Object>> startNodeFilterArrayOfHashes=new ArrayList<>();
- String passedModelInvId = null;
- String passedModelName = null;
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.queryByModel(TRANSACTION_ID, FROM_APP_ID, MODEL_VERSION_ID_VALUE, passedModelInvId, passedModelName,
- AAI_NODE_TYPE, startNodeFilterArrayOfHashes, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testQueryByModel_Timed() throws AAIException {
- List<Map<String,Object>> startNodeFilterArrayOfHashes=new ArrayList<>();
- String passedModelVersion = null;
- String passedModelName = null;
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.queryByModel_Timed(TRANSACTION_ID, FROM_APP_ID,passedModelVersion,MODEL_INVARIANT_ID_VALUE, passedModelName,
- MODEL_NAME_ID_VALUE, startNodeFilterArrayOfHashes, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testgetModelTypeFromModelVer_NullVertexArg() throws AAIException {
- Vertex nullVertex = null;
- modelBasedProcessor.getModelVerTopWidgetType(nullVertex, "");
- }
-
- @Test
- public void testValidateNamedQuery_FoundQuery() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
-
- modelBasedProcessor.validateNamedQuery("9999", "JUNIT", "named-query-uuid-1", "1.0");
- }
-
- @Test(expected=AAIException.class)
- public void testValidateNamedQuery_NotFoundQuery() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
-
- modelBasedProcessor.validateNamedQuery("9999", "JUNIT", "named-query-uuid", "1.0");
- }
-
- @Test(expected=AAIException.class)
- public void testGetNodeUsingUniqueId_NullUniqueId() throws AAIException {
- modelBasedProcessor.getNodeUsingUniqueId("9999", "postmen","generic-vnf","vnf-id","");
- modelBasedProcessor.getNodeUsingUniqueId("9999", "postmen","generic-vnf","vnf-id",null);
- }
-
- @Test(expected=AAIException.class)
- public void testGetNodeUsingUniqueId_NullPropertyName() throws AAIException {
- modelBasedProcessor.getNodeUsingUniqueId("9999", "postmen","generic-vnf","","vnf-id-1");
- modelBasedProcessor.getNodeUsingUniqueId("9999", "postmen","generic-vnf",null,"vnf-id-1");
- }
-
- @Test(expected=AAIException.class)
- public void testGetNodeUsingUniqueId_NullNodeType() throws AAIException {
- modelBasedProcessor.getNodeUsingUniqueId("9999", "postmen","","vnf-id","vnf-id-1");
- modelBasedProcessor.getNodeUsingUniqueId("9999", "postmen",null,"vnf-id","vnf-id-1");
- }
-
- @Test(expected=AAIException.class)
- public void testValidateModel() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.validateModel("9999", "JUNIT", MODEL_VERSION_ID_VALUE, "1.0");
- }
-
- @Test
- public void testShowResultSet_NullVertex() {
- ResultSet rs = getResultSet();
- rs.setVert(null);
- modelBasedProcessor.showResultSet(rs, 1);
- }
-
- @Test
- public void testShowResultSet_NonEmptyOverrideHash() {
- ResultSet rs = getResultSet();
- modelBasedProcessor.showResultSet(rs, 2);
- }
-
- @Test
- public void testShowResultSet_EmptyOverrideHash() {
- ResultSet rs = getResultSet();
- rs.setPropertyOverRideHash(new HashMap<String, Object>());
- modelBasedProcessor.showResultSet(rs, 2);
- }
-
- private ResultSet getResultSet() {
- ResultSet rs = new ResultSet();
- rs.setVert(model);
- rs.setLocationInModelSubGraph("2");
- Map<String,Object> overrideHash = new HashMap<String, Object>();
- rs.setPropertyOverRideHash(overrideHash);
- overrideHash.put("key1", "value1");
- overrideHash.put("key2", "value2");
- overrideHash.put("key3", "value3");
- overrideHash.put("key4", "value4");
-
- Map<String,Object> extraHash = new HashMap<String, Object>();
- rs.setExtraPropertyHash(extraHash);
- extraHash.put("key1", "value1");
- extraHash.put("key2", "value2");
- extraHash.put("key3", "value3");
- extraHash.put("key4", "value4");
-
- return rs;
- }
-
- @Test
- public void testPruneResultSet_NotCutPointType() throws AAIException {
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
-
- ResultSet rs = getResultSet();
- List<ResultSet> subResultSet = new ArrayList<>();
- subResultSet.add(getResultSet());
- rs.setSubResultSet(subResultSet);
- modelBasedProcessor.pruneResultSet(rs, "mdl", new HashMap<>());
- }
-
- @Test
- public void testPruneResultSet_CutPointType() throws AAIException {
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
-
- ResultSet rs = getResultSet();
- Map<String, Object> startNodeFilterHash = new HashMap<>();
- startNodeFilterHash.put("model.model_type","widget");
- startNodeFilterHash.put("named_query.named-query-uuid","named-query-uuid-1");
- modelBasedProcessor.pruneResultSet(rs, "model", startNodeFilterHash);
- }
-
- @Test
- public void testCollapseForDoNotOutput_FlagTrue() throws AAIException {
-
- ResultSet rs = getResultSet();
- List<ResultSet> subResultSet = new ArrayList<>();
- subResultSet.add(getResultSet());
- rs.setSubResultSet(subResultSet);
- rs.setDoNotOutputFlag("true");
- modelBasedProcessor.collapseForDoNotOutput(rs);
- }
-
- @Test
- public void testCollapseForDoNotOutput_FlagFalse() throws AAIException {
-
- ResultSet rs = getResultSet();
- List<ResultSet> subResultSet = new ArrayList<>();
- subResultSet.add(getResultSet());
- rs.setSubResultSet(subResultSet);
- rs.setDoNotOutputFlag("false");
- modelBasedProcessor.collapseForDoNotOutput(rs);
- }
-
- @Test
- public void testMakeSureItsAnArrayList() {
- String listString = getArrayListAsString();
- modelBasedProcessor.makeSureItsAnArrayList(listString);
- }
-
- private String getArrayListAsString() {
- List<String> strList = new ArrayList<>();
- strList.add("1");
- strList.add("2");
- strList.add("3");
- return strList.toString();
- }
-
- @Test
- public void testGetModConstraintHash() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.getModConstraintHash(modelElement, new HashMap<>());
- }
-
- @Test(expected=AAIException.class)
- public void testGenTopoMap4ModelVer_WidgetType() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.genTopoMap4ModelVer(TRANSACTION_ID, FROM_APP_ID, modelVersion, MODEL_VERSION_ID_VALUE);
- }
-
- @Test(expected=AAIException.class)
- public void testGenTopoMap4ModelVer_ServiceType() throws AAIException {
-
- Graph serviceGraph = TinkerGraph.open();
- Vertex modelV = serviceGraph.addVertex(T.label, "model", T.id, "20", AAI_NODE_TYPE, "model", "model-invariant-id", "model-invariant-id-1", "model-type", "service");
- Vertex modelVerV = serviceGraph.addVertex(T.label, MODEL_VESION_NODE_VALUE, T.id, "21", AAI_NODE_TYPE, MODEL_VESION_NODE_VALUE,
- MODEL_VERSION_ID_KEY, MODEL_VERSION_ID_VALUE,MODEL_NAME_ID_KEY, MODEL_NAME_ID_VALUE, "model-version", "model-version-1");
- Vertex modelElementV = graph.addVertex(T.label, "model-element", T.id, "22", AAI_NODE_TYPE, "model-element");
- GraphTraversalSource gts = serviceGraph.traversal();
-
- //EdgeRules rules4Service = EdgeRules.getInstance();
- edgeSer.addTreeEdge(gts, modelV, modelVerV);
- edgeSer.addTreeEdge(gts, modelElementV, modelVerV);
- edgeSer.addEdge(gts, modelElementV, modelVerV);
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
- modelBasedProcessor.genTopoMap4ModelVer(TRANSACTION_ID, FROM_APP_ID, modelVerV, MODEL_VERSION_ID_VALUE);
- }
-
- @Test(expected=AAIException.class)
- public void testCollectTopology4ModelVer() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
-
- Multimap<String, String> initialEmptyMap = ArrayListMultimap.create();
- List<String> vidsTraversed = new ArrayList<>();
- modelBasedProcessor.collectTopology4ModelVer(TRANSACTION_ID, FROM_APP_ID, modelElement, "", initialEmptyMap, vidsTraversed,
- 0, null, MODEL_INVARIANT_ID_VALUE, MODEL_VERSION_ID_VALUE);
- }
-
- @Test(expected=AAIException.class)
- public void testGetNextStepElementsFromSet_NullVertex() throws AAIException {
- modelBasedProcessor.getNextStepElementsFromSet(null);
- }
-
- @Test
- public void testRundeleteAsNeededFromResultSet() throws AAIException {
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
-
- ResultSet rs = getResultSet();
- rs.setNewDataDelFlag("T");
- modelBasedProcessor.deleteAsNeededFromResultSet(TRANSACTION_ID, FROM_APP_ID, rs,
- "", API_VERSION, API_VERSION, new HashMap<>());
- }
-
- @Test(expected=AAIException.class)
- public void testQueryByNamedQuery() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.queryByNamedQuery(TRANSACTION_ID, FROM_APP_ID, "named-query-uuid-1", new ArrayList<>(), API_VERSION);
- }
-
- @Test
- public void testCollectInstanceData() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- Multimap<String, String> validNextStepMap = ArrayListMultimap.create();
- validNextStepMap.put("named-query-element-uuid-1", "named-query-element-uuid-1");
- List<String> vidsTraversed=new ArrayList<>();
- vidsTraversed.add("named-query-element-uuid-1");
- Map<String,String> namedQueryElementHash = new HashMap<>();
- namedQueryElementHash.put("named-query-element-uuid-1", "named-query-element-uuid-1");
- modelBasedProcessor.collectInstanceData(TRANSACTION_ID, FROM_APP_ID, modelElement, "named-query-element-uuid-1",
- validNextStepMap, vidsTraversed, 0, new HashMap<>(), namedQueryElementHash, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testNamedQueryConstraintSaysStop_NullNamedQueryVertex() throws AAIException {
- modelBasedProcessor.namedQueryConstraintSaysStop(TRANSACTION_ID, FROM_APP_ID, null, model, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testNamedQueryConstraintSaysStop_NullInstanceVertex() throws AAIException {
- modelBasedProcessor.namedQueryConstraintSaysStop(TRANSACTION_ID, FROM_APP_ID, model, null, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testNamedQueryConstraintSaysStop_NullContraintType() throws AAIException {
-
- Graph serviceGraph = TinkerGraph.open();
- Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "30","aai-node-type", "named-query-element",
- "property-limit-desc", "show-all", "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
- "property-collect-list", "property-collect-list-1");
- Vertex propertyContraintV = graph.addVertex(T.label, "property-constraint", T.id, "31", AAI_NODE_TYPE, "property-constraint");
- Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "32", AAI_NODE_TYPE, "instance-vertex", "property-name", "property-name");
- GraphTraversalSource gts = serviceGraph.traversal();
-
- edgeSer.addTreeEdge(gts, namedQueryElementV, propertyContraintV);
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
- modelBasedProcessor.namedQueryConstraintSaysStop(TRANSACTION_ID, FROM_APP_ID, namedQueryElementV, instanceVertexV, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testNamedQueryConstraintSaysStop_NullPropertyName() throws AAIException {
-
- Graph serviceGraph = TinkerGraph.open();
- Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "33","aai-node-type", "named-query-element",
- "property-limit-desc", "show-all", "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
- "property-collect-list", "property-collect-list-1");
- Vertex propertyContraintV = graph.addVertex(T.label, "property-constraint", T.id, "34", AAI_NODE_TYPE, "property-constraint", "constraint-type", "EQUALS");
- Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "35", AAI_NODE_TYPE, "instance-vertex", "property-name", "property-name");
- GraphTraversalSource gts = serviceGraph.traversal();
-
- //EdgeRules rules4Service = EdgeRules.getInstance();
- edgeSer.addTreeEdge(gts, namedQueryElementV, propertyContraintV);
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
- modelBasedProcessor.namedQueryConstraintSaysStop(TRANSACTION_ID, FROM_APP_ID, namedQueryElementV, instanceVertexV, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testNamedQueryConstraintSaysStop_NullPropertyValue() throws AAIException {
-
- Graph serviceGraph = TinkerGraph.open();
- Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "36","aai-node-type", "named-query-element",
- "property-limit-desc", "show-all", "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
- "property-collect-list", "property-collect-list-1");
- Vertex propertyContraintV = graph.addVertex(T.label, "property-constraint", T.id, "37", AAI_NODE_TYPE, "property-constraint",
- "constraint-type", "EQUALS", "property-name", "property-name");
- Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "38", AAI_NODE_TYPE, "instance-vertex", "property-name", "property-name");
- GraphTraversalSource gts = serviceGraph.traversal();
-
- edgeSer.addTreeEdge(gts, namedQueryElementV, propertyContraintV);
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
- modelBasedProcessor.namedQueryConstraintSaysStop(TRANSACTION_ID, FROM_APP_ID, namedQueryElementV, instanceVertexV, API_VERSION);
- }
-
- @Test
- public void testNamedQueryConstraintSaysStop_ConstraintTypeEquals() throws AAIException {
-
- Graph serviceGraph = TinkerGraph.open();
- Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "39","aai-node-type", "named-query-element",
- "property-limit-desc", "show-all", "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
- "property-collect-list", "property-collect-list-1");
- Vertex propertyContraintV = graph.addVertex(T.label, "property-constraint", T.id, "40", AAI_NODE_TYPE, "property-constraint",
- "constraint-type", "EQUALS", "property-name", "property-name", "property-value", "property-value");
- Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "41", AAI_NODE_TYPE, "instance-vertex", "property-name", "property-name");
- GraphTraversalSource gts = serviceGraph.traversal();
-
- edgeSer.addTreeEdge(gts, namedQueryElementV, propertyContraintV);
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
- modelBasedProcessor.namedQueryConstraintSaysStop(TRANSACTION_ID, FROM_APP_ID, namedQueryElementV, instanceVertexV, API_VERSION);
- }
-
- @Test
- public void testNamedQueryConstraintSaysStop_ConstraintTypeNotEquals() throws AAIException {
-
- Graph serviceGraph = TinkerGraph.open();
- Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "42","aai-node-type", "named-query-element",
- "property-limit-desc", "show-all", "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
- "property-collect-list", "property-collect-list-1");
- Vertex propertyContraintV = graph.addVertex(T.label, "property-constraint", T.id, "43", AAI_NODE_TYPE, "property-constraint",
- "constraint-type", "NOT-EQUALS", "property-name", "property-name", "property-value", "property-value");
- Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "44", AAI_NODE_TYPE, "instance-vertex", "property-name", "property-name");
- GraphTraversalSource gts = serviceGraph.traversal();
-
- edgeSer.addTreeEdge(gts, namedQueryElementV, propertyContraintV);
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
- modelBasedProcessor.namedQueryConstraintSaysStop(TRANSACTION_ID, FROM_APP_ID, namedQueryElementV, instanceVertexV, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testGetNamedQueryExtraDataLookup_TargetNodeTypeNull() throws AAIException {
-
- Graph serviceGraph = TinkerGraph.open();
- Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "45","aai-node-type", "named-query-element",
- "property-limit-desc", "show-all", "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
- "property-collect-list", "property-collect-list-1");
- Vertex relatedLookUpV = graph.addVertex(T.label, "related-lookup", T.id, "46", AAI_NODE_TYPE, "related-lookup",
- "source-node-property", "source-node-property", "source-node-type", "generic-vnf");
- Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "47", AAI_NODE_TYPE, "instance-vertex", "property-name", "property-name");
- GraphTraversalSource gts = serviceGraph.traversal();
- edgeSer.addTreeEdge(gts, namedQueryElementV, relatedLookUpV);
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
- modelBasedProcessor.getNamedQueryExtraDataLookup(TRANSACTION_ID, FROM_APP_ID, namedQueryElementV, instanceVertexV, API_VERSION);
- }
-
- @Test
- public void testGetNamedQueryExtraDataLookup_InvalidSourceProperty() throws AAIException {
-
- Graph serviceGraph = TinkerGraph.open();
- Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "51","aai-node-type", "named-query-element",
- "property-limit-desc", "show-all", "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
- "property-collect-list", "property-collect-list-1");
- Vertex relatedLookUpV = graph.addVertex(T.label, "related-lookup", T.id, "52", AAI_NODE_TYPE, "related-lookup",
- "source-node-property", "source-node-property", "source-node-type", "generic-vnf", "target-node-type", "generic-vnf",
- "target-node-property", "generic-vnf", "property-collect-list", "property-collect-list");
- Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "53", AAI_NODE_TYPE, "instance-vertex", "property-name", "property-name");
- GraphTraversalSource gts = serviceGraph.traversal();
- edgeSer.addTreeEdge(gts, namedQueryElementV, relatedLookUpV);
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
- modelBasedProcessor.getNamedQueryExtraDataLookup(TRANSACTION_ID, FROM_APP_ID, namedQueryElementV, instanceVertexV, API_VERSION);
- }
-
- @Test(expected=IllegalArgumentException.class)
- public void testGetNamedQueryExtraDataLookup_ValidSourceProperty() throws AAIException {
-
- Graph serviceGraph = TinkerGraph.open();
- Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "54","aai-node-type", "named-query-element",
- "property-limit-desc", "show-all", "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
- "property-collect-list", "property-collect-list-1");
- Vertex relatedLookUpV = graph.addVertex(T.label, "related-lookup", T.id, "55", AAI_NODE_TYPE, "related-lookup",
- "source-node-property", "source-node-property", "source-node-type", "generic-vnf", "target-node-type", "generic-vnf", "target-node-property", "generic-vnf");
- Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "56", AAI_NODE_TYPE, "instance-vertex", "source-node-property", "source-node-property");
- GraphTraversalSource gts = serviceGraph.traversal();
- edgeSer.addTreeEdge(gts, namedQueryElementV, relatedLookUpV);
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
- modelBasedProcessor.getNamedQueryExtraDataLookup(TRANSACTION_ID, FROM_APP_ID, namedQueryElementV, instanceVertexV, API_VERSION);
- }
-
- @Test
- public void testCollectNQElementHash() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.collectNQElementHash(TRANSACTION_ID, FROM_APP_ID, namedQueryElement, "", new HashMap<>(), new ArrayList<>(), 0);
- }
-
- @Test
- public void testCollectDeleteKeyHash() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.collectDeleteKeyHash(TRANSACTION_ID, FROM_APP_ID, linkagePoints, "", new HashMap<>(), new ArrayList<>(),
- 0, new HashMap<>(), "model-version-1", "model-version-id-local");
- }
-
- @Test(expected=AAIException.class)
- public void testCheck4EdgeRule_InvalidNodeA() throws AAIException {
- modelBasedProcessor.check4EdgeRule("model-version1", "model-ver");
- }
-
- @Test(expected=AAIException.class)
- public void testCheck4EdgeRule_InvalidNodeB() throws AAIException {
- modelBasedProcessor.check4EdgeRule("model-ver", "model-version1");
- }
-
- @Test(expected=AAIException.class)
- public void testCheck4EdgeRule_InvalidEdge() throws AAIException {
- modelBasedProcessor.check4EdgeRule("model-ver", "named-query");
- }
-
- @Test
- public void testCollectTopology4LinkagePoint() throws AAIException {
- String linkagePointStrVal = new String("model-ver|model");
- String incomingTrail = new String("model|model-ver");
- Multimap<String, String> currentMap = ArrayListMultimap.create();
- modelBasedProcessor.collectTopology4LinkagePoint(TRANSACTION_ID, FROM_APP_ID, linkagePointStrVal, incomingTrail, currentMap);
- }
-
- @Test
- public void testGenTopoMap4NamedQ() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.genTopoMap4NamedQ(TRANSACTION_ID, FROM_APP_ID, namedQuery, "named-query-uuid-1");
- }
-
- @Test
- public void testGetModelThatNqElementRepresents() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.getModelThatNqElementRepresents(namedQueryElement, "");
- }
-
- @Test
- public void testGetModelVerThatElementRepresents() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.getModelVerThatElementRepresents(modelElement, "");
- }
-
- @Test
- public void testGetModelTypeFromModel() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.getModelTypeFromModel(model, "");
- }
-
- @Test
- public void testGetModelVerTopWidgetType() throws AAIException {
- Graph serviceGraph = TinkerGraph.open();
- Vertex modelV = serviceGraph.addVertex(T.label, "model", T.id, "57", AAI_NODE_TYPE, "model", "model-invariant-id", "model-invariant-id-1", "model-type", "service");
- Vertex modelVerV = serviceGraph.addVertex(T.label, MODEL_VESION_NODE_VALUE, T.id, "58", AAI_NODE_TYPE, MODEL_VESION_NODE_VALUE,
- MODEL_VERSION_ID_KEY, MODEL_VERSION_ID_VALUE,MODEL_NAME_ID_KEY, MODEL_NAME_ID_VALUE, "model-version", "model-version-1");
- Vertex modelElementV = graph.addVertex(T.label, "model-element", T.id, "59", AAI_NODE_TYPE, "model-element");
- GraphTraversalSource gts = serviceGraph.traversal();
-
- edgeSer.addTreeEdge(gts, modelV, modelVerV);
- edgeSer.addTreeEdge(gts, modelElementV, modelVerV);
- edgeSer.addEdge(gts, modelElementV, modelVerV);
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
- modelBasedProcessor.getModelVerTopWidgetType(modelVerV, "");
- }
-
- @Test
- public void testGetModelElementStepName() throws AAIException {
- Graph serviceGraph = TinkerGraph.open();
- Vertex modelV = serviceGraph.addVertex(T.label, "model", T.id, "60", AAI_NODE_TYPE, "model", "model-invariant-id", "model-invariant-id-1", "model-type", "service");
- Vertex modelVerV = serviceGraph.addVertex(T.label, MODEL_VESION_NODE_VALUE, T.id, "61", AAI_NODE_TYPE, MODEL_VESION_NODE_VALUE,
- MODEL_VERSION_ID_KEY, MODEL_VERSION_ID_VALUE,MODEL_NAME_ID_KEY, MODEL_NAME_ID_VALUE, "model-version", "model-version-1");
- Vertex modelElementV = graph.addVertex(T.label, "model-element", T.id, "62", AAI_NODE_TYPE, "model-element");
- GraphTraversalSource gts = serviceGraph.traversal();
-
- edgeSer.addTreeEdge(gts, modelV, modelVerV);
- edgeSer.addTreeEdge(gts, modelElementV, modelVerV);
- edgeSer.addEdge(gts, modelElementV, modelVerV);
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
- modelBasedProcessor.getModelElementStepName(modelElementV, "");
- }
-
- @Test(expected=IllegalArgumentException.class)
- public void testRunDeleteByModel() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- Map<String, Object> map = new HashMap<>();
- map.put("generic-vnf.d","relationshipdata");
-
- modelBasedProcessor.runDeleteByModel(TRANSACTION_ID, FROM_APP_ID, MODEL_VERSION_ID_VALUE, "model-ver", map, API_VERSION, API_VERSION);
- }
-
- @Test
- public void testSecondConstructor() {
- ModelBasedProcessing mdp = new ModelBasedProcessing();
- }
-
- @Test(expected=AAIIdentityMapParseException.class)
- public void testQueryByNamedQuery_NonEmptyMap() throws AAIException {
- Map<String, Object> map = new HashMap<>();
- map.put("model-ver.model-name", "model-name");
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
- startNodeFilterArrayOfHashes.add(map);
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
-
- modelBasedProcessor.queryByNamedQuery(TRANSACTION_ID, FROM_APP_ID, "named-query-uuid-1", startNodeFilterArrayOfHashes, API_VERSION, null, null);
-
- }
-
- @Test(expected=AAIIdentityMapParseException.class)
- public void testRunDeleteByModel_Service() throws AAIException {
- Graph serviceGraph = TinkerGraph.open();
- Vertex modelV = serviceGraph.addVertex(T.label, "model", T.id, "63", AAI_NODE_TYPE, "model", "model-invariant-id", "model-invariant-id-1", "model-type", "service");
- Vertex modelVerV = serviceGraph.addVertex(T.label, MODEL_VESION_NODE_VALUE, T.id, "64", AAI_NODE_TYPE, MODEL_VESION_NODE_VALUE,
- MODEL_VERSION_ID_KEY, MODEL_VERSION_ID_VALUE,MODEL_NAME_ID_KEY, MODEL_NAME_ID_VALUE, "model-version", "model-version-1");
- Vertex modelElementV = graph.addVertex(T.label, "model-element", T.id, "65", AAI_NODE_TYPE, "model-element");
- GraphTraversalSource gts = serviceGraph.traversal();
-
- edgeSer.addTreeEdge(gts, modelV, modelVerV);
- edgeSer.addTreeEdge(gts, modelElementV, modelVerV);
- edgeSer.addEdge(gts, modelElementV, modelVerV);
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
-
- Map<String, Object> map = new HashMap<>();
- map.put("generic-vnf.d","relationshipdata");
-
- modelBasedProcessor.runDeleteByModel(TRANSACTION_ID, FROM_APP_ID, MODEL_VERSION_ID_VALUE, "model-ver", map, API_VERSION, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testGetStartNodesAndModVersionIds_NonEmptyHashMap_AllEmpty() throws AAIException {
- Map<String, Object> map = new HashMap<>();
- map.put("model-ver.model-name", "model-name");
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
- startNodeFilterArrayOfHashes.add(map);
- String passedModelInvId = null;
- String passedModelName = null;
- String passedModelVerId = null;
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID, passedModelVerId, passedModelInvId, passedModelName,
- "", startNodeFilterArrayOfHashes, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testGetStartNodesAndModVersionIds_NonEmptyHashMap_ModelTypeNonNull() throws AAIException {
- Map<String, Object> map = new HashMap<>();
- map.put("model-ver.model-name", "model-name");
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
- startNodeFilterArrayOfHashes.add(map);
- String passedModelInvId = null;
- String passedModelName = null;
- String passedModelVerId = null;
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID, passedModelVerId, passedModelInvId, passedModelName,
- MODEL_NAME_ID_VALUE, startNodeFilterArrayOfHashes, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testQueryByModel_Timed_NonEmptyHash() throws AAIException {
- Map<String, Object> map = new HashMap<>();
- map.put("model-ver.model-name", "model-name");
- List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
- startNodeFilterArrayOfHashes.add(map);
- String passedModelVersion = null;
- String passedModelName = null;
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- modelBasedProcessor.queryByModel_Timed(TRANSACTION_ID, FROM_APP_ID,passedModelVersion,MODEL_INVARIANT_ID_VALUE, passedModelName,
- MODEL_NAME_ID_VALUE, startNodeFilterArrayOfHashes, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testRunDeleteByModel_NullVersionAndNode() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- Map<String, Object> map = new HashMap<>();
- map.put("generic-vnf.d","relationshipdata");
-
- modelBasedProcessor.runDeleteByModel(TRANSACTION_ID, FROM_APP_ID, "", "", map, API_VERSION, API_VERSION);
- }
-
- @Test(expected=AAIException.class)
- public void testRunDeleteByModel_NullVersion() throws AAIException {
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
- Map<String, Object> map = new HashMap<>();
- map.put("generic-vnf.d","relationshipdata");
-
- modelBasedProcessor.runDeleteByModel(TRANSACTION_ID, FROM_APP_ID, "", "model-ver", map, API_VERSION, API_VERSION);
- }
-
- @Test
- public void testGenTopoMap4ModelVer_WidgetType_Map() throws AAIException {
-
- Graph serviceGraph = TinkerGraph.open();
- Vertex modelV = serviceGraph.addVertex(T.label, "model", T.id, "66", AAI_NODE_TYPE, "model", "model-invariant-id", "model-invariant-id-1", "model-type", "widget");
- Vertex modelVerV = serviceGraph.addVertex(T.label, MODEL_VESION_NODE_VALUE, T.id, "67", AAI_NODE_TYPE, MODEL_VESION_NODE_VALUE,
- MODEL_VERSION_ID_KEY, MODEL_VERSION_ID_VALUE,MODEL_NAME_ID_KEY, MODEL_NAME_ID_VALUE, "model-version", "model-version-1");
- GraphTraversalSource gts = serviceGraph.traversal();
-
- edgeSer.addTreeEdge(gts, modelV, modelVerV);
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
-
- Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
- Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
- modelBasedProcessor.genTopoMap4ModelVer(TRANSACTION_ID, FROM_APP_ID, modelVerV, MODEL_VERSION_ID_VALUE);
- }
-
+
+ private static TransactionalGraphEngine dbEngine;
+ private static TransactionalGraphEngine.Admin admin;
+ DBSerializer serializer;
+ private static Loader loader;
+
+ ModelBasedProcessing modelBasedProcessor;
+
+ GraphTraversalSource source;
+
+ Graph graph;
+
+ Vertex model;
+ Vertex modelVersion;
+ Vertex modelElement;
+ Vertex constrainedElementSet;
+ Vertex namedQueryElement;
+ Vertex linkagePoints;
+ Vertex namedQuery;
+
+ @BeforeClass
+ public static void configure() throws Exception {
+ System.setProperty("AJSC_HOME", ".");
+ System.setProperty("BUNDLECONFIG_DIR", "src/main/resources");
+ }
+
+ @Before
+ public void init() throws AAIException {
+ MockitoAnnotations.initMocks(this);
+ version = schemaVersions.getDefaultVersion();
+ loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
+ TransactionalGraphEngine newDbEngine = new JanusGraphDBEngine(queryStyle, loader);
+ dbEngine = Mockito.spy(newDbEngine);
+ serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, "JUNIT");
+ admin = Mockito.spy(dbEngine.asAdmin());
+ modelBasedProcessor = new ModelBasedProcessing(loader, dbEngine, serializer);
+ graph = TinkerGraph.open();
+ source = createGraph();
+ }
+
+ private GraphTraversalSource createGraph() throws AAIException {
+ model = graph.addVertex(T.label, "model", T.id, "0", AAI_NODE_TYPE, "model",
+ "model-invariant-id", "model-invariant-id-1", "model-type", "widget");
+ modelVersion = graph.addVertex(T.label, MODEL_VESION_NODE_VALUE, T.id, "1", AAI_NODE_TYPE,
+ MODEL_VESION_NODE_VALUE, MODEL_VERSION_ID_KEY, MODEL_VERSION_ID_VALUE,
+ MODEL_NAME_ID_KEY, MODEL_NAME_ID_VALUE, "model-version", "model-version-1");
+ graph.addVertex(T.label, MODEL_INVARIANT_ID_NODE_VALUE, T.id, "2", MODEL_INVARIANT_ID_KEY,
+ MODEL_INVARIANT_ID_VALUE, "model-version-id-local", MODEL_VERSION_ID_VALUE);
+ namedQuery = graph.addVertex(T.label, "named-query", T.id, "3", "aai-node-type",
+ "named-query", "named-query-uuid", "named-query-uuid-1");
+ graph.addVertex(T.label, MODEL_NAME_NODE_VALUE, T.id, "4", AAI_NODE_TYPE,
+ MODEL_NAME_NODE_VALUE, MODEL_NAME_ID_KEY, MODEL_NAME_ID_VALUE);
+ modelElement =
+ graph.addVertex(T.label, "model-element", T.id, "5", AAI_NODE_TYPE, "model-element");
+ Vertex modelConstraint =
+ graph.addVertex(T.label, "model-constraint", T.id, "6", AAI_NODE_TYPE,
+ "model-constraint", "constrained-element-set-uuid-2-replace", "cesu2r-1");
+ constrainedElementSet = graph.addVertex(T.label, "constrained-element-set", T.id, "7",
+ AAI_NODE_TYPE, "constrained-element-set");
+ Vertex elementChoiceSet = graph.addVertex(T.label, "element-choice-set", T.id, "8",
+ AAI_NODE_TYPE, "element-choice-set");
+ namedQueryElement = graph.addVertex(T.label, "named-query-element", T.id, "9",
+ "aai-node-type", "named-query-element", "property-limit-desc", "show-all",
+ "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
+ "property-collect-list", "property-collect-list-1");
+ linkagePoints = graph.addVertex(T.label, "linkage-points", T.id, "10", AAI_NODE_TYPE,
+ "linkage-points", "linkage-points", getArrayListAsString(), "new-data-del-flag", "F");
+
+ GraphTraversalSource g = graph.traversal();
+ edgeSer.addTreeEdge(g, model, modelVersion);
+ edgeSer.addTreeEdge(g, modelElement, modelConstraint);
+ edgeSer.addTreeEdge(g, constrainedElementSet, modelConstraint);
+ edgeSer.addTreeEdge(g, modelVersion, modelElement);
+ edgeSer.addTreeEdge(g, modelElement, constrainedElementSet);
+ edgeSer.addTreeEdge(g, constrainedElementSet, elementChoiceSet);
+ edgeSer.addTreeEdge(g, modelElement, elementChoiceSet);
+ edgeSer.addTreeEdge(g, namedQuery, namedQueryElement);
+ edgeSer.addTreeEdge(g, namedQueryElement, namedQueryElement);
+ edgeSer.addEdge(g, modelVersion, modelElement);
+ edgeSer.addEdge(g, model, namedQueryElement);
+ return g;
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGetStartNodesAndModVersionIds_NullId_ExpectException() throws AAIException {
+ List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
+ String passedModelVerId = null;
+ String passedModelInvId = null;
+ String passedModelName = null;
+ modelBasedProcessor.getStartNodesAndModVersionIds("9999", "postmen", passedModelVerId,
+ passedModelInvId, passedModelName, "generic-vnf", startNodeFilterArrayOfHashes, "");
+ }
+
+ @Test
+ public void testGetStartNodesAndModVersionIds_ModelVersion() throws AAIException {
+
+ List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
+ String passedModelInvId = null;
+ String passedModelName = null;
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID,
+ MODEL_VERSION_ID_VALUE, passedModelInvId, passedModelName, AAI_NODE_TYPE,
+ startNodeFilterArrayOfHashes, API_VERSION);
+ }
+
+ @Test
+ public void testGetStartNodesAndModVersionIds_ModelInId() throws AAIException {
+ List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
+ String passedModelVersion = null;
+ String passedModelName = null;
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID,
+ passedModelVersion, MODEL_INVARIANT_ID_VALUE, passedModelName, AAI_NODE_TYPE,
+ startNodeFilterArrayOfHashes, API_VERSION);
+ }
+
+ @Test
+ public void testGetStartNodesAndModVersionIds_ModelName() throws AAIException {
+ List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
+ String passedModelVersion = null;
+ String passedModelInvId = null;
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID,
+ passedModelVersion, passedModelInvId, MODEL_NAME_ID_VALUE, AAI_NODE_TYPE,
+ startNodeFilterArrayOfHashes, API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGetStartNodesAndModVersionIds_NonEmptyHashMap_ModelVersion()
+ throws AAIException {
+ Map<String, Object> map = new HashMap<>();
+ map.put("model-ver.model-name", "model-name");
+ List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
+ startNodeFilterArrayOfHashes.add(map);
+ String passedModelInvId = null;
+ String passedModelName = null;
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID,
+ MODEL_VERSION_ID_VALUE, passedModelInvId, passedModelName, MODEL_NAME_ID_VALUE,
+ startNodeFilterArrayOfHashes, API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGetStartNodesAndModVersionIds_NonEmptyHashMap_ModelInvId() throws AAIException {
+ Map<String, Object> map = new HashMap<>();
+ map.put("model-ver.model-name", "model-name");
+ List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
+ startNodeFilterArrayOfHashes.add(map);
+ String passedModelVersion = null;
+ String passedModelName = null;
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID,
+ passedModelVersion, MODEL_INVARIANT_ID_VALUE, passedModelName, MODEL_NAME_ID_VALUE,
+ startNodeFilterArrayOfHashes, API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGetStartNodesAndModVersionIds_NonEmptyHashMap_ModelName() throws AAIException {
+ Map<String, Object> map = new HashMap<>();
+ map.put("model-ver.model-name", "model-name");
+ List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
+ startNodeFilterArrayOfHashes.add(map);
+ String passedModelVersion = null;
+ String passedModelInvId = null;
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID,
+ passedModelVersion, passedModelInvId, MODEL_NAME_ID_VALUE, MODEL_NAME_ID_VALUE,
+ startNodeFilterArrayOfHashes, API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testQueryByModel() throws AAIException {
+ List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
+ String passedModelInvId = null;
+ String passedModelName = null;
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.queryByModel(TRANSACTION_ID, FROM_APP_ID, MODEL_VERSION_ID_VALUE,
+ passedModelInvId, passedModelName, AAI_NODE_TYPE, startNodeFilterArrayOfHashes,
+ API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testQueryByModel_Timed() throws AAIException {
+ List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
+ String passedModelVersion = null;
+ String passedModelName = null;
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.queryByModel_Timed(TRANSACTION_ID, FROM_APP_ID, passedModelVersion,
+ MODEL_INVARIANT_ID_VALUE, passedModelName, MODEL_NAME_ID_VALUE,
+ startNodeFilterArrayOfHashes, API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testgetModelTypeFromModelVer_NullVertexArg() throws AAIException {
+ Vertex nullVertex = null;
+ modelBasedProcessor.getModelVerTopWidgetType(nullVertex, "");
+ }
+
+ @Test
+ public void testValidateNamedQuery_FoundQuery() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+
+ modelBasedProcessor.validateNamedQuery("9999", "JUNIT", "named-query-uuid-1", "1.0");
+ }
+
+ @Test(expected = AAIException.class)
+ public void testValidateNamedQuery_NotFoundQuery() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+
+ modelBasedProcessor.validateNamedQuery("9999", "JUNIT", "named-query-uuid", "1.0");
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGetNodeUsingUniqueId_NullUniqueId() throws AAIException {
+ modelBasedProcessor.getNodeUsingUniqueId("9999", "postmen", "generic-vnf", "vnf-id", "");
+ modelBasedProcessor.getNodeUsingUniqueId("9999", "postmen", "generic-vnf", "vnf-id", null);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGetNodeUsingUniqueId_NullPropertyName() throws AAIException {
+ modelBasedProcessor.getNodeUsingUniqueId("9999", "postmen", "generic-vnf", "", "vnf-id-1");
+ modelBasedProcessor.getNodeUsingUniqueId("9999", "postmen", "generic-vnf", null,
+ "vnf-id-1");
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGetNodeUsingUniqueId_NullNodeType() throws AAIException {
+ modelBasedProcessor.getNodeUsingUniqueId("9999", "postmen", "", "vnf-id", "vnf-id-1");
+ modelBasedProcessor.getNodeUsingUniqueId("9999", "postmen", null, "vnf-id", "vnf-id-1");
+ }
+
+ @Test(expected = AAIException.class)
+ public void testValidateModel() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.validateModel("9999", "JUNIT", MODEL_VERSION_ID_VALUE, "1.0");
+ }
+
+ @Test
+ public void testShowResultSet_NullVertex() {
+ ResultSet rs = getResultSet();
+ rs.setVert(null);
+ modelBasedProcessor.showResultSet(rs, 1);
+ }
+
+ @Test
+ public void testShowResultSet_NonEmptyOverrideHash() {
+ ResultSet rs = getResultSet();
+ modelBasedProcessor.showResultSet(rs, 2);
+ }
+
+ @Test
+ public void testShowResultSet_EmptyOverrideHash() {
+ ResultSet rs = getResultSet();
+ rs.setPropertyOverRideHash(new HashMap<String, Object>());
+ modelBasedProcessor.showResultSet(rs, 2);
+ }
+
+ private ResultSet getResultSet() {
+ ResultSet rs = new ResultSet();
+ rs.setVert(model);
+ rs.setLocationInModelSubGraph("2");
+ Map<String, Object> overrideHash = new HashMap<String, Object>();
+ rs.setPropertyOverRideHash(overrideHash);
+ overrideHash.put("key1", "value1");
+ overrideHash.put("key2", "value2");
+ overrideHash.put("key3", "value3");
+ overrideHash.put("key4", "value4");
+
+ Map<String, Object> extraHash = new HashMap<String, Object>();
+ rs.setExtraPropertyHash(extraHash);
+ extraHash.put("key1", "value1");
+ extraHash.put("key2", "value2");
+ extraHash.put("key3", "value3");
+ extraHash.put("key4", "value4");
+
+ return rs;
+ }
+
+ @Test
+ public void testPruneResultSet_NotCutPointType() throws AAIException {
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+
+ ResultSet rs = getResultSet();
+ List<ResultSet> subResultSet = new ArrayList<>();
+ subResultSet.add(getResultSet());
+ rs.setSubResultSet(subResultSet);
+ modelBasedProcessor.pruneResultSet(rs, "mdl", new HashMap<>());
+ }
+
+ @Test
+ public void testPruneResultSet_CutPointType() throws AAIException {
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+
+ ResultSet rs = getResultSet();
+ Map<String, Object> startNodeFilterHash = new HashMap<>();
+ startNodeFilterHash.put("model.model_type", "widget");
+ startNodeFilterHash.put("named_query.named-query-uuid", "named-query-uuid-1");
+ modelBasedProcessor.pruneResultSet(rs, "model", startNodeFilterHash);
+ }
+
+ @Test
+ public void testCollapseForDoNotOutput_FlagTrue() throws AAIException {
+
+ ResultSet rs = getResultSet();
+ List<ResultSet> subResultSet = new ArrayList<>();
+ subResultSet.add(getResultSet());
+ rs.setSubResultSet(subResultSet);
+ rs.setDoNotOutputFlag("true");
+ modelBasedProcessor.collapseForDoNotOutput(rs);
+ }
+
+ @Test
+ public void testCollapseForDoNotOutput_FlagFalse() throws AAIException {
+
+ ResultSet rs = getResultSet();
+ List<ResultSet> subResultSet = new ArrayList<>();
+ subResultSet.add(getResultSet());
+ rs.setSubResultSet(subResultSet);
+ rs.setDoNotOutputFlag("false");
+ modelBasedProcessor.collapseForDoNotOutput(rs);
+ }
+
+ @Test
+ public void testMakeSureItsAnArrayList() {
+ String listString = getArrayListAsString();
+ modelBasedProcessor.makeSureItsAnArrayList(listString);
+ }
+
+ private String getArrayListAsString() {
+ List<String> strList = new ArrayList<>();
+ strList.add("1");
+ strList.add("2");
+ strList.add("3");
+ return strList.toString();
+ }
+
+ @Test
+ public void testGetModConstraintHash() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.getModConstraintHash(modelElement, new HashMap<>());
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGenTopoMap4ModelVer_WidgetType() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.genTopoMap4ModelVer(TRANSACTION_ID, FROM_APP_ID, modelVersion,
+ MODEL_VERSION_ID_VALUE);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGenTopoMap4ModelVer_ServiceType() throws AAIException {
+
+ Graph serviceGraph = TinkerGraph.open();
+ Vertex modelV = serviceGraph.addVertex(T.label, "model", T.id, "20", AAI_NODE_TYPE, "model",
+ "model-invariant-id", "model-invariant-id-1", "model-type", "service");
+ Vertex modelVerV = serviceGraph.addVertex(T.label, MODEL_VESION_NODE_VALUE, T.id, "21",
+ AAI_NODE_TYPE, MODEL_VESION_NODE_VALUE, MODEL_VERSION_ID_KEY, MODEL_VERSION_ID_VALUE,
+ MODEL_NAME_ID_KEY, MODEL_NAME_ID_VALUE, "model-version", "model-version-1");
+ Vertex modelElementV =
+ graph.addVertex(T.label, "model-element", T.id, "22", AAI_NODE_TYPE, "model-element");
+ GraphTraversalSource gts = serviceGraph.traversal();
+
+ // EdgeRules rules4Service = EdgeRules.getInstance();
+ edgeSer.addTreeEdge(gts, modelV, modelVerV);
+ edgeSer.addTreeEdge(gts, modelElementV, modelVerV);
+ edgeSer.addEdge(gts, modelElementV, modelVerV);
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
+ modelBasedProcessor.genTopoMap4ModelVer(TRANSACTION_ID, FROM_APP_ID, modelVerV,
+ MODEL_VERSION_ID_VALUE);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testCollectTopology4ModelVer() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+
+ Multimap<String, String> initialEmptyMap = ArrayListMultimap.create();
+ List<String> vidsTraversed = new ArrayList<>();
+ modelBasedProcessor.collectTopology4ModelVer(TRANSACTION_ID, FROM_APP_ID, modelElement, "",
+ initialEmptyMap, vidsTraversed, 0, null, MODEL_INVARIANT_ID_VALUE,
+ MODEL_VERSION_ID_VALUE);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGetNextStepElementsFromSet_NullVertex() throws AAIException {
+ modelBasedProcessor.getNextStepElementsFromSet(null);
+ }
+
+ @Test
+ public void testRundeleteAsNeededFromResultSet() throws AAIException {
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+
+ ResultSet rs = getResultSet();
+ rs.setNewDataDelFlag("T");
+ modelBasedProcessor.deleteAsNeededFromResultSet(TRANSACTION_ID, FROM_APP_ID, rs, "",
+ API_VERSION, API_VERSION, new HashMap<>());
+ }
+
+ @Test(expected = AAIException.class)
+ public void testQueryByNamedQuery() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.queryByNamedQuery(TRANSACTION_ID, FROM_APP_ID, "named-query-uuid-1",
+ new ArrayList<>(), API_VERSION);
+ }
+
+ @Test
+ public void testCollectInstanceData() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ Multimap<String, String> validNextStepMap = ArrayListMultimap.create();
+ validNextStepMap.put("named-query-element-uuid-1", "named-query-element-uuid-1");
+ List<String> vidsTraversed = new ArrayList<>();
+ vidsTraversed.add("named-query-element-uuid-1");
+ Map<String, String> namedQueryElementHash = new HashMap<>();
+ namedQueryElementHash.put("named-query-element-uuid-1", "named-query-element-uuid-1");
+ modelBasedProcessor.collectInstanceData(TRANSACTION_ID, FROM_APP_ID, modelElement,
+ "named-query-element-uuid-1", validNextStepMap, vidsTraversed, 0, new HashMap<>(),
+ namedQueryElementHash, API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testNamedQueryConstraintSaysStop_NullNamedQueryVertex() throws AAIException {
+ modelBasedProcessor.namedQueryConstraintSaysStop(TRANSACTION_ID, FROM_APP_ID, null, model,
+ API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testNamedQueryConstraintSaysStop_NullInstanceVertex() throws AAIException {
+ modelBasedProcessor.namedQueryConstraintSaysStop(TRANSACTION_ID, FROM_APP_ID, model, null,
+ API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testNamedQueryConstraintSaysStop_NullContraintType() throws AAIException {
+
+ Graph serviceGraph = TinkerGraph.open();
+ Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "30",
+ "aai-node-type", "named-query-element", "property-limit-desc", "show-all",
+ "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
+ "property-collect-list", "property-collect-list-1");
+ Vertex propertyContraintV = graph.addVertex(T.label, "property-constraint", T.id, "31",
+ AAI_NODE_TYPE, "property-constraint");
+ Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "32",
+ AAI_NODE_TYPE, "instance-vertex", "property-name", "property-name");
+ GraphTraversalSource gts = serviceGraph.traversal();
+
+ edgeSer.addTreeEdge(gts, namedQueryElementV, propertyContraintV);
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
+ modelBasedProcessor.namedQueryConstraintSaysStop(TRANSACTION_ID, FROM_APP_ID,
+ namedQueryElementV, instanceVertexV, API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testNamedQueryConstraintSaysStop_NullPropertyName() throws AAIException {
+
+ Graph serviceGraph = TinkerGraph.open();
+ Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "33",
+ "aai-node-type", "named-query-element", "property-limit-desc", "show-all",
+ "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
+ "property-collect-list", "property-collect-list-1");
+ Vertex propertyContraintV = graph.addVertex(T.label, "property-constraint", T.id, "34",
+ AAI_NODE_TYPE, "property-constraint", "constraint-type", "EQUALS");
+ Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "35",
+ AAI_NODE_TYPE, "instance-vertex", "property-name", "property-name");
+ GraphTraversalSource gts = serviceGraph.traversal();
+
+ // EdgeRules rules4Service = EdgeRules.getInstance();
+ edgeSer.addTreeEdge(gts, namedQueryElementV, propertyContraintV);
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
+ modelBasedProcessor.namedQueryConstraintSaysStop(TRANSACTION_ID, FROM_APP_ID,
+ namedQueryElementV, instanceVertexV, API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testNamedQueryConstraintSaysStop_NullPropertyValue() throws AAIException {
+
+ Graph serviceGraph = TinkerGraph.open();
+ Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "36",
+ "aai-node-type", "named-query-element", "property-limit-desc", "show-all",
+ "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
+ "property-collect-list", "property-collect-list-1");
+ Vertex propertyContraintV = graph.addVertex(T.label, "property-constraint", T.id, "37",
+ AAI_NODE_TYPE, "property-constraint", "constraint-type", "EQUALS", "property-name",
+ "property-name");
+ Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "38",
+ AAI_NODE_TYPE, "instance-vertex", "property-name", "property-name");
+ GraphTraversalSource gts = serviceGraph.traversal();
+
+ edgeSer.addTreeEdge(gts, namedQueryElementV, propertyContraintV);
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
+ modelBasedProcessor.namedQueryConstraintSaysStop(TRANSACTION_ID, FROM_APP_ID,
+ namedQueryElementV, instanceVertexV, API_VERSION);
+ }
+
+ @Test
+ public void testNamedQueryConstraintSaysStop_ConstraintTypeEquals() throws AAIException {
+
+ Graph serviceGraph = TinkerGraph.open();
+ Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "39",
+ "aai-node-type", "named-query-element", "property-limit-desc", "show-all",
+ "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
+ "property-collect-list", "property-collect-list-1");
+ Vertex propertyContraintV = graph.addVertex(T.label, "property-constraint", T.id, "40",
+ AAI_NODE_TYPE, "property-constraint", "constraint-type", "EQUALS", "property-name",
+ "property-name", "property-value", "property-value");
+ Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "41",
+ AAI_NODE_TYPE, "instance-vertex", "property-name", "property-name");
+ GraphTraversalSource gts = serviceGraph.traversal();
+
+ edgeSer.addTreeEdge(gts, namedQueryElementV, propertyContraintV);
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
+ modelBasedProcessor.namedQueryConstraintSaysStop(TRANSACTION_ID, FROM_APP_ID,
+ namedQueryElementV, instanceVertexV, API_VERSION);
+ }
+
+ @Test
+ public void testNamedQueryConstraintSaysStop_ConstraintTypeNotEquals() throws AAIException {
+
+ Graph serviceGraph = TinkerGraph.open();
+ Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "42",
+ "aai-node-type", "named-query-element", "property-limit-desc", "show-all",
+ "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
+ "property-collect-list", "property-collect-list-1");
+ Vertex propertyContraintV = graph.addVertex(T.label, "property-constraint", T.id, "43",
+ AAI_NODE_TYPE, "property-constraint", "constraint-type", "NOT-EQUALS", "property-name",
+ "property-name", "property-value", "property-value");
+ Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "44",
+ AAI_NODE_TYPE, "instance-vertex", "property-name", "property-name");
+ GraphTraversalSource gts = serviceGraph.traversal();
+
+ edgeSer.addTreeEdge(gts, namedQueryElementV, propertyContraintV);
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
+ modelBasedProcessor.namedQueryConstraintSaysStop(TRANSACTION_ID, FROM_APP_ID,
+ namedQueryElementV, instanceVertexV, API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGetNamedQueryExtraDataLookup_TargetNodeTypeNull() throws AAIException {
+
+ Graph serviceGraph = TinkerGraph.open();
+ Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "45",
+ "aai-node-type", "named-query-element", "property-limit-desc", "show-all",
+ "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
+ "property-collect-list", "property-collect-list-1");
+ Vertex relatedLookUpV =
+ graph.addVertex(T.label, "related-lookup", T.id, "46", AAI_NODE_TYPE, "related-lookup",
+ "source-node-property", "source-node-property", "source-node-type", "generic-vnf");
+ Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "47",
+ AAI_NODE_TYPE, "instance-vertex", "property-name", "property-name");
+ GraphTraversalSource gts = serviceGraph.traversal();
+ edgeSer.addTreeEdge(gts, namedQueryElementV, relatedLookUpV);
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
+ modelBasedProcessor.getNamedQueryExtraDataLookup(TRANSACTION_ID, FROM_APP_ID,
+ namedQueryElementV, instanceVertexV, API_VERSION);
+ }
+
+ @Test
+ public void testGetNamedQueryExtraDataLookup_InvalidSourceProperty() throws AAIException {
+
+ Graph serviceGraph = TinkerGraph.open();
+ Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "51",
+ "aai-node-type", "named-query-element", "property-limit-desc", "show-all",
+ "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
+ "property-collect-list", "property-collect-list-1");
+ Vertex relatedLookUpV =
+ graph.addVertex(T.label, "related-lookup", T.id, "52", AAI_NODE_TYPE, "related-lookup",
+ "source-node-property", "source-node-property", "source-node-type", "generic-vnf",
+ "target-node-type", "generic-vnf", "target-node-property", "generic-vnf",
+ "property-collect-list", "property-collect-list");
+ Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "53",
+ AAI_NODE_TYPE, "instance-vertex", "property-name", "property-name");
+ GraphTraversalSource gts = serviceGraph.traversal();
+ edgeSer.addTreeEdge(gts, namedQueryElementV, relatedLookUpV);
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
+ modelBasedProcessor.getNamedQueryExtraDataLookup(TRANSACTION_ID, FROM_APP_ID,
+ namedQueryElementV, instanceVertexV, API_VERSION);
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testGetNamedQueryExtraDataLookup_ValidSourceProperty() throws AAIException {
+
+ Graph serviceGraph = TinkerGraph.open();
+ Vertex namedQueryElementV = graph.addVertex(T.label, "named-query-element", T.id, "54",
+ "aai-node-type", "named-query-element", "property-limit-desc", "show-all",
+ "do-not-output", "true", "named-query-element-uuid", "named-query-element-uuid-1",
+ "property-collect-list", "property-collect-list-1");
+ Vertex relatedLookUpV =
+ graph.addVertex(T.label, "related-lookup", T.id, "55", AAI_NODE_TYPE, "related-lookup",
+ "source-node-property", "source-node-property", "source-node-type", "generic-vnf",
+ "target-node-type", "generic-vnf", "target-node-property", "generic-vnf");
+ Vertex instanceVertexV = graph.addVertex(T.label, "instance-vertex", T.id, "56",
+ AAI_NODE_TYPE, "instance-vertex", "source-node-property", "source-node-property");
+ GraphTraversalSource gts = serviceGraph.traversal();
+ edgeSer.addTreeEdge(gts, namedQueryElementV, relatedLookUpV);
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
+ modelBasedProcessor.getNamedQueryExtraDataLookup(TRANSACTION_ID, FROM_APP_ID,
+ namedQueryElementV, instanceVertexV, API_VERSION);
+ }
+
+ @Test
+ public void testCollectNQElementHash() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.collectNQElementHash(TRANSACTION_ID, FROM_APP_ID, namedQueryElement, "",
+ new HashMap<>(), new ArrayList<>(), 0);
+ }
+
+ @Test
+ public void testCollectDeleteKeyHash() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.collectDeleteKeyHash(TRANSACTION_ID, FROM_APP_ID, linkagePoints, "",
+ new HashMap<>(), new ArrayList<>(), 0, new HashMap<>(), "model-version-1",
+ "model-version-id-local");
+ }
+
+ @Test(expected = AAIException.class)
+ public void testCheck4EdgeRule_InvalidNodeA() throws AAIException {
+ modelBasedProcessor.check4EdgeRule("model-version1", "model-ver");
+ }
+
+ @Test(expected = AAIException.class)
+ public void testCheck4EdgeRule_InvalidNodeB() throws AAIException {
+ modelBasedProcessor.check4EdgeRule("model-ver", "model-version1");
+ }
+
+ @Test(expected = AAIException.class)
+ public void testCheck4EdgeRule_InvalidEdge() throws AAIException {
+ modelBasedProcessor.check4EdgeRule("model-ver", "named-query");
+ }
+
+ @Test
+ public void testCollectTopology4LinkagePoint() throws AAIException {
+ String linkagePointStrVal = new String("model-ver|model");
+ String incomingTrail = new String("model|model-ver");
+ Multimap<String, String> currentMap = ArrayListMultimap.create();
+ modelBasedProcessor.collectTopology4LinkagePoint(TRANSACTION_ID, FROM_APP_ID,
+ linkagePointStrVal, incomingTrail, currentMap);
+ }
+
+ @Test
+ public void testGenTopoMap4NamedQ() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.genTopoMap4NamedQ(TRANSACTION_ID, FROM_APP_ID, namedQuery,
+ "named-query-uuid-1");
+ }
+
+ @Test
+ public void testGetModelThatNqElementRepresents() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.getModelThatNqElementRepresents(namedQueryElement, "");
+ }
+
+ @Test
+ public void testGetModelVerThatElementRepresents() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.getModelVerThatElementRepresents(modelElement, "");
+ }
+
+ @Test
+ public void testGetModelTypeFromModel() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.getModelTypeFromModel(model, "");
+ }
+
+ @Test
+ public void testGetModelVerTopWidgetType() throws AAIException {
+ Graph serviceGraph = TinkerGraph.open();
+ Vertex modelV = serviceGraph.addVertex(T.label, "model", T.id, "57", AAI_NODE_TYPE, "model",
+ "model-invariant-id", "model-invariant-id-1", "model-type", "service");
+ Vertex modelVerV = serviceGraph.addVertex(T.label, MODEL_VESION_NODE_VALUE, T.id, "58",
+ AAI_NODE_TYPE, MODEL_VESION_NODE_VALUE, MODEL_VERSION_ID_KEY, MODEL_VERSION_ID_VALUE,
+ MODEL_NAME_ID_KEY, MODEL_NAME_ID_VALUE, "model-version", "model-version-1");
+ Vertex modelElementV =
+ graph.addVertex(T.label, "model-element", T.id, "59", AAI_NODE_TYPE, "model-element");
+ GraphTraversalSource gts = serviceGraph.traversal();
+
+ edgeSer.addTreeEdge(gts, modelV, modelVerV);
+ edgeSer.addTreeEdge(gts, modelElementV, modelVerV);
+ edgeSer.addEdge(gts, modelElementV, modelVerV);
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
+ modelBasedProcessor.getModelVerTopWidgetType(modelVerV, "");
+ }
+
+ @Test
+ public void testGetModelElementStepName() throws AAIException {
+ Graph serviceGraph = TinkerGraph.open();
+ Vertex modelV = serviceGraph.addVertex(T.label, "model", T.id, "60", AAI_NODE_TYPE, "model",
+ "model-invariant-id", "model-invariant-id-1", "model-type", "service");
+ Vertex modelVerV = serviceGraph.addVertex(T.label, MODEL_VESION_NODE_VALUE, T.id, "61",
+ AAI_NODE_TYPE, MODEL_VESION_NODE_VALUE, MODEL_VERSION_ID_KEY, MODEL_VERSION_ID_VALUE,
+ MODEL_NAME_ID_KEY, MODEL_NAME_ID_VALUE, "model-version", "model-version-1");
+ Vertex modelElementV =
+ graph.addVertex(T.label, "model-element", T.id, "62", AAI_NODE_TYPE, "model-element");
+ GraphTraversalSource gts = serviceGraph.traversal();
+
+ edgeSer.addTreeEdge(gts, modelV, modelVerV);
+ edgeSer.addTreeEdge(gts, modelElementV, modelVerV);
+ edgeSer.addEdge(gts, modelElementV, modelVerV);
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
+ modelBasedProcessor.getModelElementStepName(modelElementV, "");
+ }
+
+ @Test(expected = IllegalArgumentException.class)
+ public void testRunDeleteByModel() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ Map<String, Object> map = new HashMap<>();
+ map.put("generic-vnf.d", "relationshipdata");
+
+ modelBasedProcessor.runDeleteByModel(TRANSACTION_ID, FROM_APP_ID, MODEL_VERSION_ID_VALUE,
+ "model-ver", map, API_VERSION, API_VERSION);
+ }
+
+ @Test
+ public void testSecondConstructor() {
+ ModelBasedProcessing mdp = new ModelBasedProcessing();
+ }
+
+ @Test(expected = AAIIdentityMapParseException.class)
+ public void testQueryByNamedQuery_NonEmptyMap() throws AAIException {
+ Map<String, Object> map = new HashMap<>();
+ map.put("model-ver.model-name", "model-name");
+ List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
+ startNodeFilterArrayOfHashes.add(map);
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+
+ modelBasedProcessor.queryByNamedQuery(TRANSACTION_ID, FROM_APP_ID, "named-query-uuid-1",
+ startNodeFilterArrayOfHashes, API_VERSION, null, null);
+
+ }
+
+ @Test(expected = AAIIdentityMapParseException.class)
+ public void testRunDeleteByModel_Service() throws AAIException {
+ Graph serviceGraph = TinkerGraph.open();
+ Vertex modelV = serviceGraph.addVertex(T.label, "model", T.id, "63", AAI_NODE_TYPE, "model",
+ "model-invariant-id", "model-invariant-id-1", "model-type", "service");
+ Vertex modelVerV = serviceGraph.addVertex(T.label, MODEL_VESION_NODE_VALUE, T.id, "64",
+ AAI_NODE_TYPE, MODEL_VESION_NODE_VALUE, MODEL_VERSION_ID_KEY, MODEL_VERSION_ID_VALUE,
+ MODEL_NAME_ID_KEY, MODEL_NAME_ID_VALUE, "model-version", "model-version-1");
+ Vertex modelElementV =
+ graph.addVertex(T.label, "model-element", T.id, "65", AAI_NODE_TYPE, "model-element");
+ GraphTraversalSource gts = serviceGraph.traversal();
+
+ edgeSer.addTreeEdge(gts, modelV, modelVerV);
+ edgeSer.addTreeEdge(gts, modelElementV, modelVerV);
+ edgeSer.addEdge(gts, modelElementV, modelVerV);
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
+
+ Map<String, Object> map = new HashMap<>();
+ map.put("generic-vnf.d", "relationshipdata");
+
+ modelBasedProcessor.runDeleteByModel(TRANSACTION_ID, FROM_APP_ID, MODEL_VERSION_ID_VALUE,
+ "model-ver", map, API_VERSION, API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGetStartNodesAndModVersionIds_NonEmptyHashMap_AllEmpty() throws AAIException {
+ Map<String, Object> map = new HashMap<>();
+ map.put("model-ver.model-name", "model-name");
+ List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
+ startNodeFilterArrayOfHashes.add(map);
+ String passedModelInvId = null;
+ String passedModelName = null;
+ String passedModelVerId = null;
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID,
+ passedModelVerId, passedModelInvId, passedModelName, "", startNodeFilterArrayOfHashes,
+ API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testGetStartNodesAndModVersionIds_NonEmptyHashMap_ModelTypeNonNull()
+ throws AAIException {
+ Map<String, Object> map = new HashMap<>();
+ map.put("model-ver.model-name", "model-name");
+ List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
+ startNodeFilterArrayOfHashes.add(map);
+ String passedModelInvId = null;
+ String passedModelName = null;
+ String passedModelVerId = null;
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.getStartNodesAndModVersionIds(TRANSACTION_ID, FROM_APP_ID,
+ passedModelVerId, passedModelInvId, passedModelName, MODEL_NAME_ID_VALUE,
+ startNodeFilterArrayOfHashes, API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testQueryByModel_Timed_NonEmptyHash() throws AAIException {
+ Map<String, Object> map = new HashMap<>();
+ map.put("model-ver.model-name", "model-name");
+ List<Map<String, Object>> startNodeFilterArrayOfHashes = new ArrayList<>();
+ startNodeFilterArrayOfHashes.add(map);
+ String passedModelVersion = null;
+ String passedModelName = null;
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ modelBasedProcessor.queryByModel_Timed(TRANSACTION_ID, FROM_APP_ID, passedModelVersion,
+ MODEL_INVARIANT_ID_VALUE, passedModelName, MODEL_NAME_ID_VALUE,
+ startNodeFilterArrayOfHashes, API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testRunDeleteByModel_NullVersionAndNode() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ Map<String, Object> map = new HashMap<>();
+ map.put("generic-vnf.d", "relationshipdata");
+
+ modelBasedProcessor.runDeleteByModel(TRANSACTION_ID, FROM_APP_ID, "", "", map, API_VERSION,
+ API_VERSION);
+ }
+
+ @Test(expected = AAIException.class)
+ public void testRunDeleteByModel_NullVersion() throws AAIException {
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(source);
+ Map<String, Object> map = new HashMap<>();
+ map.put("generic-vnf.d", "relationshipdata");
+
+ modelBasedProcessor.runDeleteByModel(TRANSACTION_ID, FROM_APP_ID, "", "model-ver", map,
+ API_VERSION, API_VERSION);
+ }
+
+ @Test
+ public void testGenTopoMap4ModelVer_WidgetType_Map() throws AAIException {
+
+ Graph serviceGraph = TinkerGraph.open();
+ Vertex modelV = serviceGraph.addVertex(T.label, "model", T.id, "66", AAI_NODE_TYPE, "model",
+ "model-invariant-id", "model-invariant-id-1", "model-type", "widget");
+ Vertex modelVerV = serviceGraph.addVertex(T.label, MODEL_VESION_NODE_VALUE, T.id, "67",
+ AAI_NODE_TYPE, MODEL_VESION_NODE_VALUE, MODEL_VERSION_ID_KEY, MODEL_VERSION_ID_VALUE,
+ MODEL_NAME_ID_KEY, MODEL_NAME_ID_VALUE, "model-version", "model-version-1");
+ GraphTraversalSource gts = serviceGraph.traversal();
+
+ edgeSer.addTreeEdge(gts, modelV, modelVerV);
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
+
+ Mockito.when(dbEngine.asAdmin()).thenReturn(admin);
+ Mockito.when(admin.getReadOnlyTraversalSource()).thenReturn(gts);
+ modelBasedProcessor.genTopoMap4ModelVer(TRANSACTION_ID, FROM_APP_ID, modelVerV,
+ MODEL_VERSION_ID_VALUE);
+ }
+
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/dbgraphmap/SearchGraphEdgeRuleTest.java b/aai-traversal/src/test/java/org/onap/aai/dbgraphmap/SearchGraphEdgeRuleTest.java
index 7148ca3..30323d2 100644
--- a/aai-traversal/src/test/java/org/onap/aai/dbgraphmap/SearchGraphEdgeRuleTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/dbgraphmap/SearchGraphEdgeRuleTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,34 +30,34 @@ import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.exceptions.AAIException;
import org.springframework.beans.factory.annotation.Autowired;
+public class SearchGraphEdgeRuleTest extends AAISetup {
+ @Rule
+ public ExpectedException expectedEx = ExpectedException.none();
-public class SearchGraphEdgeRuleTest extends AAISetup{
- @Rule
- public ExpectedException expectedEx = ExpectedException.none();
-
-
- @Test
- public void getEdgeLabelTest() throws AAIException, EdgeRuleNotFoundException {
- String[] label = searchGraph.getEdgeLabel("customer", "service-subscription");
-
- assertEquals("org.onap.relationships.inventory.BelongsTo", label[0]);
- }
-
- @Test
- public void getEdgeLabelThrowsExceptionWhenNoRuleExists() throws Exception {
- String nodeTypeA = "complex";
- String nodeTypeB = "service";
- expectedEx.expect(org.onap.aai.edges.exceptions.EdgeRuleNotFoundException.class);
- expectedEx.expectMessage("No rules found for EdgeRuleQuery with filter params node type: complex, node type: service, type: any, isPrivate");
- searchGraph.getEdgeLabel(nodeTypeA, nodeTypeB);
- }
-
- @Test
- public void getEdgeLabelThrowsExceptionWhenNodeTypesDoNotExist() throws Exception {
- String nodeTypeA = "A";
- String nodeTypeB = "B";
- expectedEx.expect(org.onap.aai.edges.exceptions.EdgeRuleNotFoundException.class);
- expectedEx.expectMessage("No rules found for EdgeRuleQuery with filter params node type: A, node type: B, type: any, isPrivate");
- searchGraph.getEdgeLabel(nodeTypeA, nodeTypeB);
- }
+ @Test
+ public void getEdgeLabelTest() throws AAIException, EdgeRuleNotFoundException {
+ String[] label = searchGraph.getEdgeLabel("customer", "service-subscription");
+
+ assertEquals("org.onap.relationships.inventory.BelongsTo", label[0]);
+ }
+
+ @Test
+ public void getEdgeLabelThrowsExceptionWhenNoRuleExists() throws Exception {
+ String nodeTypeA = "complex";
+ String nodeTypeB = "service";
+ expectedEx.expect(org.onap.aai.edges.exceptions.EdgeRuleNotFoundException.class);
+ expectedEx.expectMessage(
+ "No rules found for EdgeRuleQuery with filter params node type: complex, node type: service, type: any, isPrivate");
+ searchGraph.getEdgeLabel(nodeTypeA, nodeTypeB);
+ }
+
+ @Test
+ public void getEdgeLabelThrowsExceptionWhenNodeTypesDoNotExist() throws Exception {
+ String nodeTypeA = "A";
+ String nodeTypeB = "B";
+ expectedEx.expect(org.onap.aai.edges.exceptions.EdgeRuleNotFoundException.class);
+ expectedEx.expectMessage(
+ "No rules found for EdgeRuleQuery with filter params node type: A, node type: B, type: any, isPrivate");
+ searchGraph.getEdgeLabel(nodeTypeA, nodeTypeB);
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/dbgraphmap/SearchGraphNamedQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/dbgraphmap/SearchGraphNamedQueryTest.java
index 7839496..73896a0 100644
--- a/aai-traversal/src/test/java/org/onap/aai/dbgraphmap/SearchGraphNamedQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/dbgraphmap/SearchGraphNamedQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,8 +19,25 @@
*/
package org.onap.aai.dbgraphmap;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+
+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.util.*;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.*;
+
import org.junit.Before;
import org.junit.Test;
import org.mockito.Mockito;
@@ -31,22 +48,7 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.rest.util.AAIExtensionMap;
import org.onap.aai.util.AAIConstants;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.*;
-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.util.*;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class SearchGraphNamedQueryTest extends AAISetup{
+public class SearchGraphNamedQueryTest extends AAISetup {
protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
@@ -68,80 +70,83 @@ public class SearchGraphNamedQueryTest extends AAISetup{
private List<MediaType> outputMediaTypes;
private static boolean ranOnce = false;
-
+
private HttpTestUtil httpTestUtil;
-
- private String getJsonValue(String json, String key ) {
+ private String getJsonValue(String json, String key) {
JsonObject jsonObj = new JsonParser().parse(json).getAsJsonObject();
String strValue = "";
- if ( jsonObj.isJsonObject()) {
- strValue = jsonObj.get(key).getAsString();
+ if (jsonObj.isJsonObject()) {
+ strValue = jsonObj.get(key).getAsString();
}
- return strValue;
+ return strValue;
}
-
+
private void addWidgets() {
- String widgetPath = "." + AAIConstants.AAI_FILESEP + "src/main/resources" + AAIConstants.AAI_FILESEP + "etc" +
- AAIConstants.AAI_FILESEP + "scriptdata"+ AAIConstants.AAI_FILESEP + "widget-model-json";
-
+ String widgetPath = "." + AAIConstants.AAI_FILESEP + "src/main/resources"
+ + AAIConstants.AAI_FILESEP + "etc" + AAIConstants.AAI_FILESEP + "scriptdata"
+ + AAIConstants.AAI_FILESEP + "widget-model-json";
+
File dir = new File(widgetPath);
File[] files = dir.listFiles();
assert files != null;
- for ( File file : files) {
- try {
- Path path = Paths.get(widgetPath + AAIConstants.AAI_FILESEP + file.getName());
- String widgetPayload = new String(Files.readAllBytes(path));
- String modelInvariantId = getJsonValue(widgetPayload, "model-invariant-id");
- String widgetUri = "/aai/v12/service-design-and-creation/models/model/" + modelInvariantId;
- Response response = httpTestUtil.doPut(widgetUri, widgetPayload);
- assertEquals("Expected the named-query to be created", 201, response.getStatus());
- } catch ( AAIException | IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
+ for (File file : files) {
+ try {
+ Path path = Paths.get(widgetPath + AAIConstants.AAI_FILESEP + file.getName());
+ String widgetPayload = new String(Files.readAllBytes(path));
+ String modelInvariantId = getJsonValue(widgetPayload, "model-invariant-id");
+ String widgetUri =
+ "/aai/v12/service-design-and-creation/models/model/" + modelInvariantId;
+ Response response = httpTestUtil.doPut(widgetUri, widgetPayload);
+ assertEquals("Expected the named-query to be created", 201, response.getStatus());
+ } catch (AAIException | IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
}
-
+
private void addNamedQueries() {
- String namedQueryPath = "." + AAIConstants.AAI_FILESEP + "src/main/resources" + AAIConstants.AAI_FILESEP + "etc" +
- AAIConstants.AAI_FILESEP + "scriptdata"+ AAIConstants.AAI_FILESEP + "named-query-json";
-
+ String namedQueryPath = "." + AAIConstants.AAI_FILESEP + "src/main/resources"
+ + AAIConstants.AAI_FILESEP + "etc" + AAIConstants.AAI_FILESEP + "scriptdata"
+ + AAIConstants.AAI_FILESEP + "named-query-json";
+
File dir = new File(namedQueryPath);
File[] files = dir.listFiles();
assert files != null;
- for ( File file : files) {
- try {
- Path path = Paths.get(namedQueryPath + AAIConstants.AAI_FILESEP + file.getName());
- String namedQueryPayload = new String(Files.readAllBytes(path));
- String namedQueryUuid = getJsonValue(namedQueryPayload, "named-query-uuid");
- String namedQueryUri = "/aai/v12/service-design-and-creation/named-queries/named-query/" + namedQueryUuid;
-
- Response response = httpTestUtil.doPut(namedQueryUri, namedQueryPayload);
- assertEquals("Expected the named-query to be created", 201, response.getStatus());
- } catch ( AAIException | IOException e) {
- // TODO Auto-generated catch block
- e.printStackTrace();
- }
-
- }
+ for (File file : files) {
+ try {
+ Path path = Paths.get(namedQueryPath + AAIConstants.AAI_FILESEP + file.getName());
+ String namedQueryPayload = new String(Files.readAllBytes(path));
+ String namedQueryUuid = getJsonValue(namedQueryPayload, "named-query-uuid");
+ String namedQueryUri =
+ "/aai/v12/service-design-and-creation/named-queries/named-query/"
+ + namedQueryUuid;
+
+ Response response = httpTestUtil.doPut(namedQueryUri, namedQueryPayload);
+ assertEquals("Expected the named-query to be created", 201, response.getStatus());
+ } catch (AAIException | IOException e) {
+ // TODO Auto-generated catch block
+ e.printStackTrace();
+ }
+
+ }
}
-
- private String addVersionToUri(String uri ) {
- return "/aai/" + schemaVersions.getDefaultVersion() + "/" + uri;
+
+ private String addVersionToUri(String uri) {
+ return "/aai/" + schemaVersions.getDefaultVersion() + "/" + uri;
}
@Before
- public void setup(){
-
- httpTestUtil = new HttpTestUtil();
+ public void setup() {
-
- httpHeaders = mock(HttpHeaders.class);
+ httpTestUtil = new HttpTestUtil();
- headersMultiMap = new MultivaluedHashMap<>();
- queryParameters = Mockito.spy(new MultivaluedHashMap<>());
+ httpHeaders = mock(HttpHeaders.class);
+
+ headersMultiMap = new MultivaluedHashMap<>();
+ queryParameters = Mockito.spy(new MultivaluedHashMap<>());
headersMultiMap.add("X-FromAppId", "JUNIT");
headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
@@ -157,231 +162,250 @@ public class SearchGraphNamedQueryTest extends AAISetup{
when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
- when(httpHeaders.getRequestHeader("X-FromAppId")).thenReturn(Collections.singletonList("JUNIT"));
- when(httpHeaders.getRequestHeader("X-TransactionId")).thenReturn(Collections.singletonList("JUNIT"));
+ when(httpHeaders.getRequestHeader("X-FromAppId"))
+ .thenReturn(Collections.singletonList("JUNIT"));
+ when(httpHeaders.getRequestHeader("X-TransactionId"))
+ .thenReturn(Collections.singletonList("JUNIT"));
when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);
-
- // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be very unreasonable
+ // 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);
- if ( !ranOnce ) {
- ranOnce = true;
- addWidgets();
- addNamedQueries();
- }
+ if (!ranOnce) {
+ ranOnce = true;
+ addWidgets();
+ addNamedQueries();
+ }
}
-
@Test
public void getDHVLogicalLinkByCircuitId_1_0_Test() throws Exception {
- AAIExtensionMap aaiExtMap = new AAIExtensionMap();
- aaiExtMap.setHttpHeaders(httpHeaders);
- String queryParameters = PayloadUtil.getNamedQueryPayload("query-payload.DHVLogicalLinkByCircuitId-1.0.json");
- String putPayload = PayloadUtil.getNamedQueryPayload("logical-link.DHVLogicalLinkByCircuitId-1.0.json");
-
+ AAIExtensionMap aaiExtMap = new AAIExtensionMap();
+ aaiExtMap.setHttpHeaders(httpHeaders);
+ String queryParameters =
+ PayloadUtil.getNamedQueryPayload("query-payload.DHVLogicalLinkByCircuitId-1.0.json");
+ String putPayload =
+ PayloadUtil.getNamedQueryPayload("logical-link.DHVLogicalLinkByCircuitId-1.0.json");
+
String linkName = getJsonValue(putPayload, "link-name");
String putUri = addVersionToUri("network/logical-links/logical-link/" + linkName);
- Response response = httpTestUtil.doPut(putUri, putPayload);
+ Response response = httpTestUtil.doPut(putUri, putPayload);
assertEquals("Expected the logical-link to be created", 201, response.getStatus());
-
+
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getContentType()).thenReturn("application/json");
-
- aaiExtMap.setUri("/search/named-query");
- aaiExtMap.setApiVersion(schemaVersions.getDefaultVersion().toString());
- aaiExtMap.setServletRequest(request);
-
-
- response = searchGraph.runNamedQuery("JUNIT", "JUNIT", queryParameters, aaiExtMap);
+
+ aaiExtMap.setUri("/search/named-query");
+ aaiExtMap.setApiVersion(schemaVersions.getDefaultVersion().toString());
+ aaiExtMap.setServletRequest(request);
+
+ response = searchGraph.runNamedQuery("JUNIT", "JUNIT", queryParameters, aaiExtMap);
System.out.println("response was\n" + response.getEntity().toString());
assertEquals("Expected success from query", 200, response.getStatus());
boolean hasLinkName = response.getEntity().toString().indexOf(linkName) > 0;
- assertTrue("Response contains linkName", hasLinkName );
+ assertTrue("Response contains linkName", hasLinkName);
}
@Test
public void getSvcSubscriberModelInfo_1_0_Test() throws Exception {
- AAIExtensionMap aaiExtMap = new AAIExtensionMap();
- aaiExtMap.setHttpHeaders(httpHeaders);
- String queryParameters = PayloadUtil.getNamedQueryPayload("query-payload.SvcSubscriberModelInfo-1.0.json");
-
- String putPayload = PayloadUtil.getNamedQueryPayload("model.SvcSubscriberModelInfo-1.0.json");
+ AAIExtensionMap aaiExtMap = new AAIExtensionMap();
+ aaiExtMap.setHttpHeaders(httpHeaders);
+ String queryParameters =
+ PayloadUtil.getNamedQueryPayload("query-payload.SvcSubscriberModelInfo-1.0.json");
+
+ String putPayload =
+ PayloadUtil.getNamedQueryPayload("model.SvcSubscriberModelInfo-1.0.json");
String modelInvariantId = getJsonValue(putPayload, "model-invariant-id");
- String putUri = addVersionToUri("service-design-and-creation/models/model/" + modelInvariantId);
- Response response = httpTestUtil.doPut(putUri, putPayload);
+ String putUri =
+ addVersionToUri("service-design-and-creation/models/model/" + modelInvariantId);
+ Response response = httpTestUtil.doPut(putUri, putPayload);
assertEquals("Expected the model to be created", 201, response.getStatus());
-
+
putPayload = PayloadUtil.getNamedQueryPayload("customer.SvcSubscriberModelInfo-1.0.json");
String globalCustomerId = getJsonValue(putPayload, "global-customer-id");
putUri = addVersionToUri("business/customers/customer/" + globalCustomerId);
- response = httpTestUtil.doPut(putUri, putPayload);
+ response = httpTestUtil.doPut(putUri, putPayload);
assertEquals("Expected the customer to be created", 201, response.getStatus());
-
+
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getContentType()).thenReturn("application/json");
-
- aaiExtMap.setUri("/search/named-query");
- aaiExtMap.setApiVersion(schemaVersions.getDefaultVersion().toString());
- aaiExtMap.setServletRequest(request);
-
-
- response = searchGraph.runNamedQuery("JUNIT", "JUNIT", queryParameters, aaiExtMap);
+
+ aaiExtMap.setUri("/search/named-query");
+ aaiExtMap.setApiVersion(schemaVersions.getDefaultVersion().toString());
+ aaiExtMap.setServletRequest(request);
+
+ response = searchGraph.runNamedQuery("JUNIT", "JUNIT", queryParameters, aaiExtMap);
assertEquals("Expected success from query", 200, response.getStatus());
boolean hasModelName = response.getEntity().toString().indexOf("junit-model-name") > 0;
- assertTrue("Response contains modelName from model-ver", hasModelName );
+ assertTrue("Response contains modelName from model-ver", hasModelName);
}
-
+
@Test
public void getClosedLoopNamedQuery_1_0_Test() throws Exception {
- AAIExtensionMap aaiExtMap = new AAIExtensionMap();
- aaiExtMap.setHttpHeaders(httpHeaders);
- String queryParameters = PayloadUtil.getNamedQueryPayload("query-payload.closed-loop-named-query-1.0.json");
-
- String putPayload = PayloadUtil.getNamedQueryPayload("model.closed-loop-named-query-1.0.json");
+ AAIExtensionMap aaiExtMap = new AAIExtensionMap();
+ aaiExtMap.setHttpHeaders(httpHeaders);
+ String queryParameters =
+ PayloadUtil.getNamedQueryPayload("query-payload.closed-loop-named-query-1.0.json");
+
+ String putPayload =
+ PayloadUtil.getNamedQueryPayload("model.closed-loop-named-query-1.0.json");
String modelInvariantId = getJsonValue(putPayload, "model-invariant-id");
- String putUri = addVersionToUri("service-design-and-creation/models/model/" + modelInvariantId);
- Response response = httpTestUtil.doPut(putUri, putPayload);
- assertEquals("Expected the model to be created", 201, response.getStatus());
-
- putPayload = PayloadUtil.getNamedQueryPayload("cloud-region.closed-loop-named-query-1.0.json");
+ String putUri =
+ addVersionToUri("service-design-and-creation/models/model/" + modelInvariantId);
+ Response response = httpTestUtil.doPut(putUri, putPayload);
+ assertEquals("Expected the model to be created", 201, response.getStatus());
+
+ putPayload =
+ PayloadUtil.getNamedQueryPayload("cloud-region.closed-loop-named-query-1.0.json");
String cloudOwner = getJsonValue(putPayload, "cloud-owner");
String cloudRegionId = getJsonValue(putPayload, "cloud-region-id");
- putUri = addVersionToUri("cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner + "/" + cloudRegionId);
- response = httpTestUtil.doPut(putUri, putPayload);
+ putUri = addVersionToUri(
+ "cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner + "/" + cloudRegionId);
+ response = httpTestUtil.doPut(putUri, putPayload);
assertEquals("Expected the cloud-region to be created", 201, response.getStatus());
-
- putPayload = PayloadUtil.getNamedQueryPayload("cloud-region2.closed-loop-named-query-1.0.json");
+
+ putPayload =
+ PayloadUtil.getNamedQueryPayload("cloud-region2.closed-loop-named-query-1.0.json");
String cloudOwner2 = getJsonValue(putPayload, "cloud-owner");
String cloudRegionId2 = getJsonValue(putPayload, "cloud-region-id");
- putUri = addVersionToUri("cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner2 + "/" + cloudRegionId2);
- response = httpTestUtil.doPut(putUri, putPayload);
- assertEquals("Expected the cloud-region2 to be created", 201, response.getStatus());
-
+ putUri = addVersionToUri("cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner2
+ + "/" + cloudRegionId2);
+ response = httpTestUtil.doPut(putUri, putPayload);
+ assertEquals("Expected the cloud-region2 to be created", 201, response.getStatus());
+
putPayload = PayloadUtil.getNamedQueryPayload("tenant.closed-loop-named-query-1.0.json");
String tenantId = getJsonValue(putPayload, "tenant-id");
- putUri = addVersionToUri("cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner + "/" + cloudRegionId
- + "/tenants/tenant/" + tenantId);
- response = httpTestUtil.doPut(putUri, putPayload);
- assertEquals("Expected the tenant to be created", 201, response.getStatus());
+ putUri = addVersionToUri("cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner
+ + "/" + cloudRegionId + "/tenants/tenant/" + tenantId);
+ response = httpTestUtil.doPut(putUri, putPayload);
+ assertEquals("Expected the tenant to be created", 201, response.getStatus());
putPayload = PayloadUtil.getNamedQueryPayload("tenant2.closed-loop-named-query-1.0.json");
String tenantId2 = getJsonValue(putPayload, "tenant-id");
- putUri = addVersionToUri("cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner2 + "/" + cloudRegionId2
- + "/tenants/tenant/" + tenantId2);
- response = httpTestUtil.doPut(putUri, putPayload);
+ putUri = addVersionToUri("cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner2
+ + "/" + cloudRegionId2 + "/tenants/tenant/" + tenantId2);
+ response = httpTestUtil.doPut(putUri, putPayload);
assertEquals("Expected the tenant2 to be created", 201, response.getStatus());
-
+
putPayload = PayloadUtil.getNamedQueryPayload("vserver.closed-loop-named-query-1.0.json");
String vserverId = getJsonValue(putPayload, "vserver-id");
- putUri = addVersionToUri("cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner + "/" + cloudRegionId
- + "/tenants/tenant/" + tenantId + "/vservers/vserver/" + vserverId);
- response = httpTestUtil.doPut(putUri, putPayload);
- assertEquals("Expected the vserver to be created", 201, response.getStatus());
+ putUri =
+ addVersionToUri("cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner + "/"
+ + cloudRegionId + "/tenants/tenant/" + tenantId + "/vservers/vserver/" + vserverId);
+ response = httpTestUtil.doPut(putUri, putPayload);
+ assertEquals("Expected the vserver to be created", 201, response.getStatus());
putPayload = PayloadUtil.getNamedQueryPayload("vserver2.closed-loop-named-query-1.0.json");
String vserverId2 = getJsonValue(putPayload, "vserver-id");
- putUri = addVersionToUri("cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner2 + "/" + cloudRegionId2
- + "/tenants/tenant/" + tenantId2 + "/vservers/vserver/" + vserverId2);
- response = httpTestUtil.doPut(putUri, putPayload);
+ putUri = addVersionToUri(
+ "cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner2 + "/" + cloudRegionId2
+ + "/tenants/tenant/" + tenantId2 + "/vservers/vserver/" + vserverId2);
+ response = httpTestUtil.doPut(putUri, putPayload);
assertEquals("Expected the vserver2 to be created", 201, response.getStatus());
-
+
putPayload = PayloadUtil.getNamedQueryPayload("customer.closed-loop-named-query-1.0.json");
String globalCustomerId = getJsonValue(putPayload, "global-customer-id");
putUri = addVersionToUri("business/customers/customer/" + globalCustomerId);
- response = httpTestUtil.doPut(putUri, putPayload);
+ response = httpTestUtil.doPut(putUri, putPayload);
assertEquals("Expected the customer to be created", 201, response.getStatus());
- putPayload = PayloadUtil.getNamedQueryPayload("generic-vnf.closed-loop-named-query-1.0.json");
+ putPayload =
+ PayloadUtil.getNamedQueryPayload("generic-vnf.closed-loop-named-query-1.0.json");
String vnfId = getJsonValue(putPayload, "vnf-id");
putUri = addVersionToUri("network/generic-vnfs/generic-vnf/" + vnfId);
- response = httpTestUtil.doPut(putUri, putPayload);
+ response = httpTestUtil.doPut(putUri, putPayload);
assertEquals("Expected the generic-vnf to be created", 201, response.getStatus());
-
+
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getContentType()).thenReturn("application/json");
-
- aaiExtMap.setUri("/search/named-query");
- aaiExtMap.setApiVersion(schemaVersions.getDefaultVersion().toString());
- aaiExtMap.setServletRequest(request);
-
-
- response = searchGraph.runNamedQuery("JUNIT", "JUNIT", queryParameters, aaiExtMap);
+
+ aaiExtMap.setUri("/search/named-query");
+ aaiExtMap.setApiVersion(schemaVersions.getDefaultVersion().toString());
+ aaiExtMap.setServletRequest(request);
+
+ response = searchGraph.runNamedQuery("JUNIT", "JUNIT", queryParameters, aaiExtMap);
assertEquals("Expected success from query", 200, response.getStatus());
- boolean hasModelName = response.getEntity().toString().indexOf("example-model-name-val-closed-loop") > 0;
- assertTrue("Response contains modelName from model-ver", hasModelName );
+ boolean hasModelName =
+ response.getEntity().toString().indexOf("example-model-name-val-closed-loop") > 0;
+ assertTrue("Response contains modelName from model-ver", hasModelName);
}
-
+
@Test
public void getComponentList_1_2_Test() throws Exception {
- AAIExtensionMap aaiExtMap = new AAIExtensionMap();
- aaiExtMap.setHttpHeaders(httpHeaders);
- String queryParameters = PayloadUtil.getNamedQueryPayload("query-payload.ComponentList-1.2.json");
-
- String putPayload = PayloadUtil.getNamedQueryPayload("model.ComponentList-1.2.json");
+ AAIExtensionMap aaiExtMap = new AAIExtensionMap();
+ aaiExtMap.setHttpHeaders(httpHeaders);
+ String queryParameters =
+ PayloadUtil.getNamedQueryPayload("query-payload.ComponentList-1.2.json");
+
+ String putPayload = PayloadUtil.getNamedQueryPayload("model.ComponentList-1.2.json");
String modelInvariantId = getJsonValue(putPayload, "model-invariant-id");
- String putUri = addVersionToUri("service-design-and-creation/models/model/" + modelInvariantId);
- Response response = httpTestUtil.doPut(putUri, putPayload);
+ String putUri =
+ addVersionToUri("service-design-and-creation/models/model/" + modelInvariantId);
+ Response response = httpTestUtil.doPut(putUri, putPayload);
assertEquals("Expected the model to be created", 201, response.getStatus());
-
+
putPayload = PayloadUtil.getNamedQueryPayload("customer.ComponentList-1.2.json");
String globalCustomerId = getJsonValue(putPayload, "global-customer-id");
putUri = addVersionToUri("business/customers/customer/" + globalCustomerId);
- response = httpTestUtil.doPut(putUri, putPayload);
+ response = httpTestUtil.doPut(putUri, putPayload);
assertEquals("Expected the customer to be created", 201, response.getStatus());
-
+
putPayload = PayloadUtil.getNamedQueryPayload("generic-vnf.ComponentList-1.2.json");
String vnfId = getJsonValue(putPayload, "vnf-id");
putUri = addVersionToUri("network/generic-vnfs/generic-vnf/" + vnfId);
- response = httpTestUtil.doPut(putUri, putPayload);
- assertEquals("Expected the generic-vnf to be created", 201, response.getStatus());
+ response = httpTestUtil.doPut(putUri, putPayload);
+ assertEquals("Expected the generic-vnf to be created", 201, response.getStatus());
putPayload = PayloadUtil.getNamedQueryPayload("vf-module.ComponentList-1.2.json");
String vfModuleId = getJsonValue(putPayload, "vf-module-id");
- putUri = addVersionToUri("network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId);
- response = httpTestUtil.doPut(putUri, putPayload);
+ putUri = addVersionToUri(
+ "network/generic-vnfs/generic-vnf/" + vnfId + "/vf-modules/vf-module/" + vfModuleId);
+ response = httpTestUtil.doPut(putUri, putPayload);
assertEquals("Expected the vf-module to be created", 201, response.getStatus());
-
+
putPayload = PayloadUtil.getNamedQueryPayload("cloud-region.ComponentList-1.2.json");
String cloudOwner = getJsonValue(putPayload, "cloud-owner");
String cloudRegionId = getJsonValue(putPayload, "cloud-region-id");
- putUri = addVersionToUri("cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner + "/" + cloudRegionId);
- response = httpTestUtil.doPut(putUri, putPayload);
+ putUri = addVersionToUri(
+ "cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner + "/" + cloudRegionId);
+ response = httpTestUtil.doPut(putUri, putPayload);
assertEquals("Expected the cloud-region to be created", 201, response.getStatus());
-
+
putPayload = PayloadUtil.getNamedQueryPayload("tenant.ComponentList-1.2.json");
String tenantId = getJsonValue(putPayload, "tenant-id");
- putUri = addVersionToUri("cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner + "/" + cloudRegionId
- + "/tenants/tenant/" + tenantId);
- response = httpTestUtil.doPut(putUri, putPayload);
- assertEquals("Expected the tenant to be created", 201, response.getStatus());
-
+ putUri = addVersionToUri("cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner
+ + "/" + cloudRegionId + "/tenants/tenant/" + tenantId);
+ response = httpTestUtil.doPut(putUri, putPayload);
+ assertEquals("Expected the tenant to be created", 201, response.getStatus());
+
putPayload = PayloadUtil.getNamedQueryPayload("vserver.ComponentList-1.2.json");
String vserverId = getJsonValue(putPayload, "vserver-id");
- putUri = addVersionToUri("cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner + "/" + cloudRegionId
- + "/tenants/tenant/" + tenantId + "/vservers/vserver/" + vserverId);
- response = httpTestUtil.doPut(putUri, putPayload);
- assertEquals("Expected the vserver to be created", 201, response.getStatus());
-
+ putUri =
+ addVersionToUri("cloud-infrastructure/cloud-regions/cloud-region/" + cloudOwner + "/"
+ + cloudRegionId + "/tenants/tenant/" + tenantId + "/vservers/vserver/" + vserverId);
+ response = httpTestUtil.doPut(putUri, putPayload);
+ assertEquals("Expected the vserver to be created", 201, response.getStatus());
+
HttpServletRequest request = Mockito.mock(HttpServletRequest.class);
Mockito.when(request.getContentType()).thenReturn("application/json");
-
- aaiExtMap.setUri("/search/named-query");
- aaiExtMap.setApiVersion(schemaVersions.getDefaultVersion().toString());
- aaiExtMap.setServletRequest(request);
-
-
- response = searchGraph.runNamedQuery("JUNIT", "JUNIT", queryParameters, aaiExtMap);
+
+ aaiExtMap.setUri("/search/named-query");
+ aaiExtMap.setApiVersion(schemaVersions.getDefaultVersion().toString());
+ aaiExtMap.setServletRequest(request);
+
+ response = searchGraph.runNamedQuery("JUNIT", "JUNIT", queryParameters, aaiExtMap);
assertEquals("Expected success from query", 200, response.getStatus());
- boolean hasModelName = response.getEntity().toString().indexOf("example-model-name-val-component-list") > 0;
- assertTrue("Response contains modelName from model-ver", hasModelName );
- }
-} \ No newline at end of file
+ boolean hasModelName =
+ response.getEntity().toString().indexOf("example-model-name-val-component-list") > 0;
+ assertTrue("Response contains modelName from model-ver", hasModelName);
+ }
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/dbgraphmap/SearchGraphTest.java b/aai-traversal/src/test/java/org/onap/aai/dbgraphmap/SearchGraphTest.java
index 2b4ec18..c46af87 100644
--- a/aai-traversal/src/test/java/org/onap/aai/dbgraphmap/SearchGraphTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/dbgraphmap/SearchGraphTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,17 @@
*/
package org.onap.aai.dbgraphmap;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.net.URI;
+import java.util.*;
+import java.util.stream.Stream;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.*;
+
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.eclipse.persistence.dynamic.DynamicEntity;
import org.janusgraph.graphdb.types.system.EmptyVertex;
@@ -42,19 +53,7 @@ import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.util.GenericQueryBuilder;
import org.onap.aai.util.NodesQueryBuilder;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.*;
-import java.net.URI;
-import java.util.*;
-import java.util.stream.Stream;
-
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class SearchGraphTest extends AAISetup{
-
-
+public class SearchGraphTest extends AAISetup {
protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
@@ -109,16 +108,18 @@ public class SearchGraphTest extends AAISetup{
when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
- when(httpHeaders.getRequestHeader("X-FromAppId")).thenReturn(Collections.singletonList("JUNIT"));
- when(httpHeaders.getRequestHeader("X-TransactionId")).thenReturn(Collections.singletonList("JUNIT"));
+ when(httpHeaders.getRequestHeader("X-FromAppId"))
+ .thenReturn(Collections.singletonList("JUNIT"));
+ when(httpHeaders.getRequestHeader("X-TransactionId"))
+ .thenReturn(Collections.singletonList("JUNIT"));
when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);
-
when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters);
- // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be very unreasonable
+ // 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);
@@ -127,21 +128,25 @@ public class SearchGraphTest extends AAISetup{
}
@Test(expected = AAIException.class)
- public void runNodesQuery() throws AAIException{
- DBSerializer serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, "JUNIT");
+ public void runNodesQuery() throws AAIException {
+ DBSerializer serializer =
+ new DBSerializer(version, dbEngine, introspectorFactoryType, "JUNIT");
UrlBuilder urlBuilder = new UrlBuilder(version, serializer, schemaVersions, basePath);
- searchGraph.runNodesQuery(
- new NodesQueryBuilder().setHeaders(httpHeaders).setTargetNodeType("").setEdgeFilterParams(null)
- .setFilterParams(null).setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
+ searchGraph.runNodesQuery(new NodesQueryBuilder().setHeaders(httpHeaders)
+ .setTargetNodeType("").setEdgeFilterParams(null).setFilterParams(null)
+ .setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
}
+
@Test(expected = AAIException.class)
- public void runNodesQueryNull() throws AAIException{
- DBSerializer serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, "JUNIT");
+ public void runNodesQueryNull() throws AAIException {
+ DBSerializer serializer =
+ new DBSerializer(version, dbEngine, introspectorFactoryType, "JUNIT");
UrlBuilder urlBuilder = new UrlBuilder(version, serializer, schemaVersions, basePath);
- searchGraph.runNodesQuery(
- new NodesQueryBuilder().setHeaders(httpHeaders).setTargetNodeType("nnn").setEdgeFilterParams(null)
- .setFilterParams(null).setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
+ searchGraph.runNodesQuery(new NodesQueryBuilder().setHeaders(httpHeaders)
+ .setTargetNodeType("nnn").setEdgeFilterParams(null).setFilterParams(null)
+ .setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
}
+
@Test(expected = AAIException.class)
public void testRunGenericQueryFailWhenInvalidRelationshipList() throws AAIException {
@@ -151,15 +156,16 @@ public class SearchGraphTest extends AAISetup{
List<String> includeStrings = new ArrayList<>();
includeStrings.add("cloud-region");
- DBSerializer serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, "JUNIT");
+ DBSerializer serializer =
+ new DBSerializer(version, dbEngine, introspectorFactoryType, "JUNIT");
UrlBuilder urlBuilder = new UrlBuilder(version, serializer, schemaVersions, basePath);
- Response response = searchGraph.runGenericQuery(new GenericQueryBuilder().setHeaders(httpHeaders)
- .setStartNodeType("service-instance").setStartNodeKeyParams(keys).setIncludeNodeTypes(includeStrings)
- .setDepth(1).setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
+ Response response = searchGraph.runGenericQuery(
+ new GenericQueryBuilder().setHeaders(httpHeaders).setStartNodeType("service-instance")
+ .setStartNodeKeyParams(keys).setIncludeNodeTypes(includeStrings).setDepth(1)
+ .setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
System.out.println(response);
}
-
@Test(expected = AAIException.class)
public void testRunGenericQueryFailWhenInvalidRelationshipList1() throws AAIException {
@@ -169,10 +175,12 @@ public class SearchGraphTest extends AAISetup{
List<String> includeStrings = new ArrayList<>();
includeStrings.add("cloud-region");
- DBSerializer serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, "JUNIT");
+ DBSerializer serializer =
+ new DBSerializer(version, dbEngine, introspectorFactoryType, "JUNIT");
UrlBuilder urlBuilder = new UrlBuilder(version, serializer, schemaVersions, basePath);
- Response response = searchGraph.runGenericQuery(new GenericQueryBuilder().setHeaders(httpHeaders)
- .setStartNodeType(null).setStartNodeKeyParams(keys).setIncludeNodeTypes(includeStrings).setDepth(1)
+ Response response = searchGraph.runGenericQuery(
+ new GenericQueryBuilder().setHeaders(httpHeaders).setStartNodeType(null)
+ .setStartNodeKeyParams(keys).setIncludeNodeTypes(includeStrings).setDepth(1)
.setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
System.out.println(response);
}
@@ -183,10 +191,12 @@ public class SearchGraphTest extends AAISetup{
List<String> includeStrings = new ArrayList<>();
includeStrings.add("cloud-region");
- DBSerializer serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, "JUNIT");
+ DBSerializer serializer =
+ new DBSerializer(version, dbEngine, introspectorFactoryType, "JUNIT");
UrlBuilder urlBuilder = new UrlBuilder(version, serializer, schemaVersions, basePath);
- Response response = searchGraph.runGenericQuery(new GenericQueryBuilder().setHeaders(httpHeaders)
- .setStartNodeType("").setStartNodeKeyParams(null).setIncludeNodeTypes(includeStrings).setDepth(1)
+ Response response = searchGraph
+ .runGenericQuery(new GenericQueryBuilder().setHeaders(httpHeaders).setStartNodeType("")
+ .setStartNodeKeyParams(null).setIncludeNodeTypes(includeStrings).setDepth(1)
.setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
System.out.println(response);
}
@@ -197,11 +207,13 @@ public class SearchGraphTest extends AAISetup{
List<String> keys = new ArrayList<>();
keys.add("cloud-region.cloud-owner:test-aic");
- DBSerializer serializer = new DBSerializer(version, dbEngine, introspectorFactoryType, "JUNIT");
+ DBSerializer serializer =
+ new DBSerializer(version, dbEngine, introspectorFactoryType, "JUNIT");
UrlBuilder urlBuilder = new UrlBuilder(version, serializer, schemaVersions, basePath);
- Response response = searchGraph.runGenericQuery(new GenericQueryBuilder().setHeaders(httpHeaders)
- .setStartNodeType("").setStartNodeKeyParams(keys).setIncludeNodeTypes(null).setDepth(1)
- .setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
+ Response response =
+ searchGraph.runGenericQuery(new GenericQueryBuilder().setHeaders(httpHeaders)
+ .setStartNodeType("").setStartNodeKeyParams(keys).setIncludeNodeTypes(null)
+ .setDepth(1).setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
System.out.println(response);
}
@@ -209,113 +221,121 @@ public class SearchGraphTest extends AAISetup{
public void createSearchResults1() throws Exception {
List<Vertex> keys = new ArrayList<>();
- Vertex vertex=new EmptyVertex();
+ Vertex vertex = new EmptyVertex();
keys.add(vertex);
- UrlBuilder urlBuilder=mock(UrlBuilder.class);
- when(urlBuilder.pathed(vertex)).thenReturn("cloud-region");
- Stream<Vertex> stream=mock(Stream.class);
+ UrlBuilder urlBuilder = mock(UrlBuilder.class);
+ when(urlBuilder.pathed(vertex)).thenReturn("cloud-region");
+ Stream<Vertex> stream = mock(Stream.class);
when(stream.isParallel()).thenReturn(true);
- RelationshipToURI relationshipToURI=mock(RelationshipToURI.class);
- URI uri =new URI("");
+ RelationshipToURI relationshipToURI = mock(RelationshipToURI.class);
+ URI uri = new URI("");
when(relationshipToURI.getUri()).thenReturn(uri);
Introspector response = searchGraph.createSearchResults(loader, urlBuilder, keys);
System.out.println(response);
}
+
@Test(expected = AAIException.class)
- public void executeModelOperationTest() throws Exception{
- Vertex vertex=new EmptyVertex();
+ public void executeModelOperationTest() throws Exception {
+ Vertex vertex = new EmptyVertex();
vertex.property("model-name");
- AAIExtensionMap map=mock(AAIExtensionMap.class);
- HttpServletRequest servletRequest=mock(HttpServletRequest.class);
+ AAIExtensionMap map = mock(AAIExtensionMap.class);
+ HttpServletRequest servletRequest = mock(HttpServletRequest.class);
when(map.getHttpServletRequest()).thenReturn(servletRequest);
when(servletRequest.getContentType()).thenReturn("application/json");
- DynamicEntity modelAndNamedQuerySearch=mock(DynamicEntity.class);
+ DynamicEntity modelAndNamedQuerySearch = mock(DynamicEntity.class);
when(modelAndNamedQuerySearch.isSet("topNodeType")).thenReturn(true);
- searchGraph.executeModelOperation("","","",true,
- map);
+ searchGraph.executeModelOperation("", "", "", true, map);
}
@Test(expected = AAIException.class)
- public void executeModelOperationXMLTest() throws Exception{
- Vertex vertex=new EmptyVertex();
+ public void executeModelOperationXMLTest() throws Exception {
+ Vertex vertex = new EmptyVertex();
vertex.property("model-name");
- AAIExtensionMap map=mock(AAIExtensionMap.class);
- HttpServletRequest servletRequest=mock(HttpServletRequest.class);
+ AAIExtensionMap map = mock(AAIExtensionMap.class);
+ HttpServletRequest servletRequest = mock(HttpServletRequest.class);
when(map.getHttpServletRequest()).thenReturn(servletRequest);
when(servletRequest.getContentType()).thenReturn("application/xml");
- DynamicEntity modelAndNamedQuerySearch=mock(DynamicEntity.class);
+ DynamicEntity modelAndNamedQuerySearch = mock(DynamicEntity.class);
when(modelAndNamedQuerySearch.isSet("queryParameters")).thenReturn(true);
- searchGraph.executeModelOperation("","","",true,
- map);
+ searchGraph.executeModelOperation("", "", "", true, map);
}
+
@Test
- public void runNodesQueryTest() throws AAIException{
- UrlBuilder urlBuilder=mock(UrlBuilder.class);
- List<String> filter=new ArrayList<>();
+ public void runNodesQueryTest() throws AAIException {
+ UrlBuilder urlBuilder = mock(UrlBuilder.class);
+ List<String> filter = new ArrayList<>();
filter.add("model:EQUALS:DOES-NOT-EXIST:AAI");
- List<String> edgeFilter=new ArrayList<>();
+ List<String> edgeFilter = new ArrayList<>();
edgeFilter.add("model:DOES-NOT-EXIST:DOES-NOT-EXIST:AAI");
- Response response= searchGraph.runNodesQuery(new NodesQueryBuilder().setHeaders(httpHeaders).setTargetNodeType("model-ver").setEdgeFilterParams(edgeFilter)
- .setFilterParams(filter).setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
+ Response response = searchGraph.runNodesQuery(
+ new NodesQueryBuilder().setHeaders(httpHeaders).setTargetNodeType("model-ver")
+ .setEdgeFilterParams(edgeFilter).setFilterParams(filter).setDbEngine(dbEngine)
+ .setLoader(loader).setUrlBuilder(urlBuilder));
Assert.assertNotNull(response);
}
@Test
- public void runNodesQueryExistsTest() throws AAIException{
- UrlBuilder urlBuilder=mock(UrlBuilder.class);
- List<String> filter=new ArrayList<String>();
+ public void runNodesQueryExistsTest() throws AAIException {
+ UrlBuilder urlBuilder = mock(UrlBuilder.class);
+ List<String> filter = new ArrayList<String>();
filter.add("model:EQUALS:DOES-NOT-EXIST:AAI");
- List<String> edgeFilter=new ArrayList<String>();
+ List<String> edgeFilter = new ArrayList<String>();
edgeFilter.add("model:EXISTS:DOES-NOT-EXIST:AAI");
- Response response= searchGraph.runNodesQuery(new NodesQueryBuilder().setHeaders(httpHeaders).setTargetNodeType("model-ver").setEdgeFilterParams(edgeFilter)
- .setFilterParams(filter).setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
+ Response response = searchGraph.runNodesQuery(
+ new NodesQueryBuilder().setHeaders(httpHeaders).setTargetNodeType("model-ver")
+ .setEdgeFilterParams(edgeFilter).setFilterParams(filter).setDbEngine(dbEngine)
+ .setLoader(loader).setUrlBuilder(urlBuilder));
Assert.assertNotNull(response);
}
@Test
- public void runNodesQueryTestDOESNOTEQUAL() throws AAIException{
- UrlBuilder urlBuilder=mock(UrlBuilder.class);
- List<String> filter=new ArrayList<String>();
+ public void runNodesQueryTestDOESNOTEQUAL() throws AAIException {
+ UrlBuilder urlBuilder = mock(UrlBuilder.class);
+ List<String> filter = new ArrayList<String>();
filter.add("model:DOES-NOT-EQUAL:DOES-NOT-EXIST");
- List<String> edgeFilter=new ArrayList<>();
- searchGraph.runNodesQuery(new NodesQueryBuilder().setHeaders(httpHeaders).setTargetNodeType("model-ver").setEdgeFilterParams(edgeFilter)
- .setFilterParams(filter).setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
+ List<String> edgeFilter = new ArrayList<>();
+ searchGraph.runNodesQuery(new NodesQueryBuilder().setHeaders(httpHeaders)
+ .setTargetNodeType("model-ver").setEdgeFilterParams(edgeFilter).setFilterParams(filter)
+ .setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
}
@Test
- public void runNodesQueryTestGreaterThan3() throws AAIException{
- UrlBuilder urlBuilder=mock(UrlBuilder.class);
- List<String> filter=new ArrayList<>();
+ public void runNodesQueryTestGreaterThan3() throws AAIException {
+ UrlBuilder urlBuilder = mock(UrlBuilder.class);
+ List<String> filter = new ArrayList<>();
filter.add("model:DOES-NOT-EQUAL:DOES-NOT-EXIST:AAI");
- List<String> edgeFilter=new ArrayList<>();
- searchGraph.runNodesQuery(new NodesQueryBuilder().setHeaders(httpHeaders).setTargetNodeType("model-ver").setEdgeFilterParams(edgeFilter)
- .setFilterParams(filter).setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
+ List<String> edgeFilter = new ArrayList<>();
+ searchGraph.runNodesQuery(new NodesQueryBuilder().setHeaders(httpHeaders)
+ .setTargetNodeType("model-ver").setEdgeFilterParams(edgeFilter).setFilterParams(filter)
+ .setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
}
@Test
- public void runNodesQueryTestGreaterThanExists() throws AAIException{
- UrlBuilder urlBuilder=mock(UrlBuilder.class);
- List<String> filter=new ArrayList<>();
+ public void runNodesQueryTestGreaterThanExists() throws AAIException {
+ UrlBuilder urlBuilder = mock(UrlBuilder.class);
+ List<String> filter = new ArrayList<>();
filter.add("model:EXISTS:DOES-NOT-EXIST:AAI");
- List<String> edgeFilter=new ArrayList<>();
- searchGraph.runNodesQuery(new NodesQueryBuilder().setHeaders(httpHeaders).setTargetNodeType("model-ver").setEdgeFilterParams(edgeFilter)
- .setFilterParams(filter).setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
+ List<String> edgeFilter = new ArrayList<>();
+ searchGraph.runNodesQuery(new NodesQueryBuilder().setHeaders(httpHeaders)
+ .setTargetNodeType("model-ver").setEdgeFilterParams(edgeFilter).setFilterParams(filter)
+ .setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
}
@Test(expected = AAIException.class)
- public void runNodesQueryTestGreaterThanDoesNotExists() throws AAIException{
- UrlBuilder urlBuilder=mock(UrlBuilder.class);
- List<String> filter=new ArrayList<>();
+ public void runNodesQueryTestGreaterThanDoesNotExists() throws AAIException {
+ UrlBuilder urlBuilder = mock(UrlBuilder.class);
+ List<String> filter = new ArrayList<>();
filter.add("model:DOES_NOT_EXIST:DOES-NOT-EXIST:AAI");
- List<String> edgeFilter=new ArrayList<>();
- searchGraph.runNodesQuery(new NodesQueryBuilder().setHeaders(httpHeaders).setTargetNodeType("model-ver").setEdgeFilterParams(edgeFilter)
- .setFilterParams(filter).setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
+ List<String> edgeFilter = new ArrayList<>();
+ searchGraph.runNodesQuery(new NodesQueryBuilder().setHeaders(httpHeaders)
+ .setTargetNodeType("model-ver").setEdgeFilterParams(edgeFilter).setFilterParams(filter)
+ .setDbEngine(dbEngine).setLoader(loader).setUrlBuilder(urlBuilder));
}
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestConfiguration.java b/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestConfiguration.java
index 4b87cde..0ff845a 100644
--- a/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestConfiguration.java
+++ b/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestConfiguration.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -23,7 +23,9 @@ import com.github.dockerjava.api.model.ExposedPort;
import com.github.dockerjava.api.model.HostConfig;
import com.github.dockerjava.api.model.PortBinding;
import com.github.dockerjava.api.model.Ports;
+
import dasniko.testcontainers.keycloak.KeycloakContainer;
+
import org.keycloak.adapters.springboot.KeycloakSpringBootProperties;
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.KeycloakBuilder;
@@ -42,23 +44,19 @@ class KeycloakTestConfiguration {
@Bean
KeycloakContainer keycloakContainer(KeycloakTestProperties properties) {
KeycloakContainer keycloak = new KeycloakContainer("jboss/keycloak:12.0.4")
- .withRealmImportFile(properties.realmJson)
- .withCreateContainerCmdModifier(cmd -> cmd.withHostConfig(
- new HostConfig().withPortBindings(new PortBinding(Ports.Binding.bindPort(Integer.parseInt(properties.port)), new ExposedPort(8080)))
- ));
+ .withRealmImportFile(properties.realmJson).withCreateContainerCmdModifier(
+ cmd -> cmd.withHostConfig(new HostConfig().withPortBindings(
+ new PortBinding(Ports.Binding.bindPort(Integer.parseInt(properties.port)),
+ new ExposedPort(8080)))));
keycloak.start();
return keycloak;
}
@Bean
Keycloak keycloakAdminClient(KeycloakContainer keycloak, KeycloakTestProperties properties) {
- return KeycloakBuilder.builder()
- .serverUrl(keycloak.getAuthServerUrl())
- .realm(properties.realm)
- .clientId(properties.adminCli)
- .username(keycloak.getAdminUsername())
- .password(keycloak.getAdminPassword())
- .build();
+ return KeycloakBuilder.builder().serverUrl(keycloak.getAuthServerUrl())
+ .realm(properties.realm).clientId(properties.adminCli)
+ .username(keycloak.getAdminUsername()).password(keycloak.getAdminPassword()).build();
}
@Bean
diff --git a/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestProperties.java b/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestProperties.java
index df9db84..72b6f6f 100644
--- a/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestProperties.java
+++ b/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/KeycloakTestProperties.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
diff --git a/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/MultiTenancyIT.java b/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/MultiTenancyIT.java
index b0fddb4..38490f8 100644
--- a/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/MultiTenancyIT.java
+++ b/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/MultiTenancyIT.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,8 +19,17 @@
*/
package org.onap.aai.it.multitenancy;
+import static org.junit.Assert.*;
+
import com.jayway.jsonpath.JsonPath;
+
import dasniko.testcontainers.keycloak.KeycloakContainer;
+
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.List;
+import java.util.Map;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.janusgraph.core.JanusGraphTransaction;
import org.junit.Test;
@@ -35,13 +44,6 @@ import org.springframework.context.annotation.Import;
import org.springframework.http.*;
import org.springframework.test.context.TestPropertySource;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.List;
-import java.util.Map;
-
-import static org.junit.Assert.*;
-
@Import(KeycloakTestConfiguration.class)
@TestPropertySource(locations = "classpath:it/application-keycloak-test.properties")
public class MultiTenancyIT extends AbstractSpringRestTest {
@@ -61,44 +63,30 @@ public class MultiTenancyIT extends AbstractSpringRestTest {
try {
GraphTraversalSource g = transaction.traversal();
- g.addV().property("aai-node-type", "pnf")
- .property("pnf-name", "test-pnf-name-01")
- .property("prov-status", "in_service")
- .property("data-owner", "operator")
- .property("in-maint", false)
- .property("source-of-truth", "JUNIT")
- .property("aai-uri", "/network/pnfs/pnf/test-pnf-name-01").next();
-
- g.addV().property("aai-node-type", "pnf")
- .property("pnf-name", "test-pnf-name-02")
- .property("prov-status", "in_service")
- .property("in-maint", false)
- .property("source-of-truth", "JUNIT")
- .property("aai-uri", "/network/pnfs/pnf/test-pnf-name-02").next();
-
- g.addV().property("aai-node-type", "pnf")
- .property("pnf-name", "test-pnf-name-03")
- .property("prov-status", "in_service")
- .property("data-owner", "selector")
- .property("in-maint", false)
- .property("source-of-truth", "JUNIT")
- .property("aai-uri", "/network/pnfs/pnf/test-pnf-name-03").next();
-
- g.addV().property("aai-node-type", "pnf")
- .property("pnf-name", "test-pnf-name-04")
- .property("prov-status", "in_service")
- .property("data-owner", "selector")
- .property("in-maint", false)
- .property("source-of-truth", "JUNIT")
- .property("aai-uri", "/network/pnfs/pnf/test-pnf-name-04").next();
-
- g.addV().property("aai-node-type", "pnf")
- .property("pnf-name", "test-pnf-name-05")
- .property("prov-status", "in_service")
- .property("data-owner", "selector")
- .property("in-maint", false)
- .property("source-of-truth", "JUNIT")
- .property("aai-uri", "/network/pnfs/pnf/test-pnf-name-05").next();
+ g.addV().property("aai-node-type", "pnf").property("pnf-name", "test-pnf-name-01")
+ .property("prov-status", "in_service").property("data-owner", "operator")
+ .property("in-maint", false).property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/network/pnfs/pnf/test-pnf-name-01").next();
+
+ g.addV().property("aai-node-type", "pnf").property("pnf-name", "test-pnf-name-02")
+ .property("prov-status", "in_service").property("in-maint", false)
+ .property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/network/pnfs/pnf/test-pnf-name-02").next();
+
+ g.addV().property("aai-node-type", "pnf").property("pnf-name", "test-pnf-name-03")
+ .property("prov-status", "in_service").property("data-owner", "selector")
+ .property("in-maint", false).property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/network/pnfs/pnf/test-pnf-name-03").next();
+
+ g.addV().property("aai-node-type", "pnf").property("pnf-name", "test-pnf-name-04")
+ .property("prov-status", "in_service").property("data-owner", "selector")
+ .property("in-maint", false).property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/network/pnfs/pnf/test-pnf-name-04").next();
+
+ g.addV().property("aai-node-type", "pnf").property("pnf-name", "test-pnf-name-05")
+ .property("prov-status", "in_service").property("data-owner", "selector")
+ .property("in-maint", false).property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/network/pnfs/pnf/test-pnf-name-05").next();
} catch (Exception ex) {
success = false;
} finally {
@@ -132,7 +120,8 @@ public class MultiTenancyIT extends AbstractSpringRestTest {
assertEquals(queryResults.size(), 2);
// get pnf with bob (operator_readOnly)
- username = "bob"; password = "bob";
+ username = "bob";
+ password = "bob";
headers = this.getHeaders(username, password);
httpEntity = new HttpEntity(payload, headers);
responseEntity = restTemplate.exchange(endpoint, HttpMethod.PUT, httpEntity, String.class);
@@ -141,7 +130,8 @@ public class MultiTenancyIT extends AbstractSpringRestTest {
assertEquals(queryResults.size(), 2);
// get pnf with ted (selector)
- username = "ted"; password = "ted";
+ username = "ted";
+ password = "ted";
headers = this.getHeaders(username, password);
httpEntity = new HttpEntity(payload, headers);
responseEntity = restTemplate.exchange(endpoint, HttpMethod.PUT, httpEntity, String.class);
@@ -174,13 +164,9 @@ public class MultiTenancyIT extends AbstractSpringRestTest {
private String getStringToken(String username, String password) {
Keycloak keycloakClient = KeycloakBuilder.builder()
- .serverUrl(keycloakContainer.getAuthServerUrl())
- .realm(properties.realm)
- .clientId(properties.clientId)
- .clientSecret(properties.clientSecret)
- .username(username)
- .password(password)
- .build();
+ .serverUrl(keycloakContainer.getAuthServerUrl()).realm(properties.realm)
+ .clientId(properties.clientId).clientSecret(properties.clientSecret).username(username)
+ .password(password).build();
AccessTokenResponse tokenResponse = keycloakClient.tokenManager().getAccessToken();
assertNotNull(tokenResponse);
diff --git a/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/RoleHandler.java b/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/RoleHandler.java
index 763c071..cd4f1b5 100644
--- a/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/RoleHandler.java
+++ b/aai-traversal/src/test/java/org/onap/aai/it/multitenancy/RoleHandler.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,16 +19,16 @@
*/
package org.onap.aai.it.multitenancy;
+import java.util.Collections;
+
import org.keycloak.admin.client.Keycloak;
import org.keycloak.admin.client.resource.RealmResource;
-import java.util.Collections;
-
class RoleHandler {
- /**
- Following roles should be the same as given roles in multi-tenancy-realm json file
- */
+ /**
+ * Following roles should be the same as given roles in multi-tenancy-realm json file
+ */
final static String OPERATOR = "operator";
private final Keycloak adminClient;
private final KeycloakTestProperties properties;
@@ -40,17 +40,13 @@ class RoleHandler {
void addToUser(String role, String username) {
RealmResource realm = adminClient.realm(properties.realm);
- realm.users().get(username)
- .roles()
- .realmLevel()
- .add(Collections.singletonList(realm.roles().get(role).toRepresentation()));
+ realm.users().get(username).roles().realmLevel()
+ .add(Collections.singletonList(realm.roles().get(role).toRepresentation()));
}
void removeFromUser(String role, String username) {
RealmResource realm = adminClient.realm(properties.realm);
- realm.users().get(username)
- .roles()
- .realmLevel()
- .remove(Collections.singletonList(realm.roles().get(role).toRepresentation()));
+ realm.users().get(username).roles().realmLevel()
+ .remove(Collections.singletonList(realm.roles().get(role).toRepresentation()));
}
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/AbstractSpringRestTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/AbstractSpringRestTest.java
index de98a8c..ac71b57 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/AbstractSpringRestTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/AbstractSpringRestTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,11 @@
*/
package org.onap.aai.rest;
+import java.io.UnsupportedEncodingException;
+import java.nio.charset.StandardCharsets;
+import java.util.Base64;
+import java.util.Collections;
+
import org.apache.tinkerpop.gremlin.process.traversal.P;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
@@ -33,8 +38,8 @@ 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.web.server.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
@@ -45,12 +50,9 @@ 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.nio.charset.StandardCharsets;
-import java.util.Base64;
-import java.util.Collections;
-
-@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = TraversalApp.class)
+@SpringBootTest(
+ webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+ classes = TraversalApp.class)
@TestPropertySource(locations = "classpath:application-test.properties")
@Import(TraversalTestConfiguration.class)
public abstract class AbstractSpringRestTest {
@@ -66,14 +68,14 @@ public abstract class AbstractSpringRestTest {
@Autowired
protected NodeIngestor nodeIngestor;
-
+
@LocalServerPort
protected int randomPort;
protected HttpEntity httpEntity;
protected String baseUrl;
- protected HttpHeaders headers ;
+ protected HttpHeaders headers;
@BeforeClass
public static void setupConfig() throws AAIException {
@@ -95,7 +97,8 @@ public abstract class AbstractSpringRestTest {
headers.add("Real-Time", "true");
headers.add("X-FromAppId", "JUNIT");
headers.add("X-TransactionId", "JUNIT");
- String authorization = Base64.getEncoder().encodeToString("AAI:AAI".getBytes(StandardCharsets.UTF_8));
+ String authorization =
+ Base64.getEncoder().encodeToString("AAI:AAI".getBytes(StandardCharsets.UTF_8));
headers.add("Authorization", "Basic " + authorization);
httpEntity = new HttpEntity(headers);
baseUrl = "http://localhost:" + randomPort;
@@ -104,11 +107,12 @@ public abstract class AbstractSpringRestTest {
/*
* Inheritors please override this one
*/
- public void createTestGraph(){
-
+ public void createTestGraph() {
+
}
+
@After
- public void tearDown(){
+ public void tearDown() {
JanusGraph janusGraph = AAIGraph.getInstance().getGraph();
JanusGraphTransaction transaction = janusGraph.newTransaction();
@@ -117,13 +121,12 @@ public abstract class AbstractSpringRestTest {
try {
GraphTraversalSource g = transaction.traversal();
- g.V().has("source-of-truth", P.within("JUNIT", "AAI-EXTENSIONS"))
- .toList()
- .forEach(Vertex::remove);
- } catch(Exception ex){
+ g.V().has("source-of-truth", P.within("JUNIT", "AAI-EXTENSIONS")).toList()
+ .forEach(Vertex::remove);
+ } catch (Exception ex) {
success = false;
} finally {
- if(success){
+ if (success) {
transaction.commit();
} else {
transaction.rollback();
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/BadQueryFormatTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/BadQueryFormatTest.java
index ea31302..eb8902e 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/BadQueryFormatTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/BadQueryFormatTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,15 @@
*/
package org.onap.aai.rest;
+import static org.hamcrest.Matchers.containsString;
+import static org.hamcrest.Matchers.is;
+import static org.hamcrest.junit.MatcherAssert.assertThat;
+
+import java.util.Base64;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
@@ -28,8 +37,8 @@ import org.onap.aai.TraversalApp;
import org.onap.aai.TraversalTestConfiguration;
import org.onap.aai.config.PropertyPasswordConfiguration;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.annotation.Import;
import org.springframework.http.*;
import org.springframework.test.context.ContextConfiguration;
@@ -37,17 +46,10 @@ import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
-import java.util.Base64;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-
-import static org.hamcrest.Matchers.containsString;
-import static org.hamcrest.Matchers.is;
-import static org.hamcrest.junit.MatcherAssert.assertThat;
-
@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = TraversalApp.class)
+@SpringBootTest(
+ webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+ classes = TraversalApp.class)
@TestPropertySource(locations = "classpath:application-test.properties")
@ContextConfiguration(initializers = PropertyPasswordConfiguration.class)
@Import(TraversalTestConfiguration.class)
@@ -99,11 +101,13 @@ public class BadQueryFormatTest {
String endpoint = "/aai/v11/query?format=hello";
httpEntity = new HttpEntity(payload, headers);
- responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
System.out.println(responseEntity.getBody());
assertThat(responseEntity.getStatusCode(), is(HttpStatus.BAD_REQUEST));
- assertThat(responseEntity.getBody().toString(), containsString("Bad Parameter Passed:Unsupported format query parameter hello in request"));
+ assertThat(responseEntity.getBody().toString(), containsString(
+ "Bad Parameter Passed:Unsupported format query parameter hello in request"));
}
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/ConfigurationTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/ConfigurationTest.java
index 5294f24..b0f9869 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/ConfigurationTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/ConfigurationTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,14 @@
*/
package org.onap.aai.rest;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Base64;
+import java.util.Collections;
+
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.TraversalApp;
@@ -34,21 +42,17 @@ import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.TestPropertySource;
import org.springframework.web.client.RestTemplate;
-import java.io.UnsupportedEncodingException;
-import java.util.Base64;
-import java.util.Collections;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-import static org.junit.Assert.assertFalse;
-
/**
* Test REST requests against configuration resource
*/
@TestPropertySource(locations = "classpath:application-test.properties")
-@ContextConfiguration(initializers = PropertyPasswordConfiguration.class, classes = {SpringContextAware.class})
+@ContextConfiguration(
+ initializers = PropertyPasswordConfiguration.class,
+ classes = {SpringContextAware.class})
@Import(TraversalTestConfiguration.class)
-@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = {SpringContextAware.class, TraversalApp.class})
+@SpringBootTest(
+ webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+ classes = {SpringContextAware.class, TraversalApp.class})
public class ConfigurationTest extends AbstractSpringRestTest {
@Autowired
RestTemplate restTemplate;
@@ -59,6 +63,7 @@ public class ConfigurationTest extends AbstractSpringRestTest {
private HttpEntity<String> httpEntity;
private String actuatorurl;
private HttpHeaders headers;
+
@Before
public void setup() throws UnsupportedEncodingException {
@@ -83,24 +88,27 @@ public class ConfigurationTest extends AbstractSpringRestTest {
ResponseEntity responseEntity = null;
String responseBody = null;
- //set Accept as text/plain in order to get access of endpoint "/actuator/prometheus"
- responseEntity = restTemplate.exchange(actuatorurl + "/actuator/prometheus", HttpMethod.GET, httpEntity, String.class);
+ // set Accept as text/plain in order to get access of endpoint "/actuator/prometheus"
+ responseEntity = restTemplate.exchange(actuatorurl + "/actuator/prometheus", HttpMethod.GET,
+ httpEntity, String.class);
responseBody = (String) responseEntity.getBody();
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
System.out.println("responseBody---------" + responseBody);
assertFalse(responseBody.contains("aai_uri"));
assertTrue(responseBody.contains("group_id"));
-
- //Set Accept as MediaType.APPLICATION_JSON in order to get access of endpoint "/actuator/info" and "/actuator/health"
+ // Set Accept as MediaType.APPLICATION_JSON in order to get access of endpoint
+ // "/actuator/info" and "/actuator/health"
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
httpEntity = new HttpEntity<String>(headers);
- responseEntity = restTemplate.exchange(actuatorurl + "/actuator/info", HttpMethod.GET, httpEntity, String.class);
+ responseEntity = restTemplate.exchange(actuatorurl + "/actuator/info", HttpMethod.GET,
+ httpEntity, String.class);
responseBody = (String) responseEntity.getBody();
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
assertTrue(responseBody.contains("aai-traversal"));
- responseEntity = restTemplate.exchange(actuatorurl + "/actuator/health", HttpMethod.GET, httpEntity, String.class);
+ responseEntity = restTemplate.exchange(actuatorurl + "/actuator/health", HttpMethod.GET,
+ httpEntity, String.class);
responseBody = (String) responseEntity.getBody();
assertEquals(HttpStatus.OK, responseEntity.getStatusCode());
assertTrue(responseBody.contains("UP"));
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/DslConsumerTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/DslConsumerTest.java
index 311de49..b72107f 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/DslConsumerTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/DslConsumerTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,10 +19,18 @@
*/
package org.onap.aai.rest;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.CoreMatchers.is;
+import static org.hamcrest.Matchers.not;
+import static org.junit.Assert.*;
+
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+
+import java.util.*;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.JanusGraphTransaction;
@@ -36,873 +44,999 @@ import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.http.*;
-import java.util.*;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.CoreMatchers.is;
-import static org.hamcrest.Matchers.not;
-import static org.junit.Assert.*;
-
public class DslConsumerTest extends AbstractSpringRestTest {
- private static final Logger LOGGER = LoggerFactory.getLogger(DslConsumerTest.class);
-
- @Override
- public void createTestGraph() {
- JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
- boolean success = true;
- try {
- GraphTraversalSource g = transaction.traversal();
- Vertex p1 = g.addV().property("aai-node-type", "pserver").property("hostname", "test-pserver-dsl")
- .property("in-maint", false).property("source-of-truth", "JUNIT")
- .property("aai-uri", "/cloud-infrastructure/pservers/pserver/test-pserver-dsl").next();
- Vertex p2 = g.addV().property("aai-node-type", "pserver").property("hostname", "test-pserver-dsl-02")
- .property("in-maint", false).property("source-of-truth", "JUNIT")
- .property("aai-uri", "/cloud-infrastructure/pservers/pserver/test-pserver-dsl-02").next();
- Vertex p3 = g.addV().property("aai-node-type", "pserver").property("hostname", "test-pserver-dsl-03")
- .property("in-maint", false).property("source-of-truth", "JUNIT")
- .property("aai-uri", "/cloud-infrastructure/pservers/pserver/test-pserver-dsl-03").next();
- Vertex p4 = g.addV().property("aai-node-type", "pserver").property("hostname", "test-pserver-dsl-04")
- .property("in-maint", false).property("source-of-truth", "JUNIT")
- .property("number-of-cpus", 364).property("source-of-truth", "JUNIT")
- .property("aai-uri", "/cloud-infrastructure/pservers/pserver/test-pserver-dsl-04").next();
- Vertex c1 = g.addV().property("aai-node-type", "complex").property("physical-location-id", "test-complex-dsl")
- .property("state", "NJ")
- .property("source-of-truth", "JUNIT")
- .property("aai-uri", "/cloud-infrastructure/complexes/complex/test-complex-dsl").next();
- Vertex cr1 = g.addV().property("aai-node-type", "cloud-region")
- .property("cloud-owner", "test-cloud-owner-01")
- .property("cloud-region-id", "test-cloud-region-id-01")
- .property("source-of-truth", "JUNIT")
- .property("aai-uri", "/cloud-infrastructure/cloud-regions/cloud-region/test-cloud-owner-01/test-cloud-region-id-01").next();
- Vertex pnf01 = g.addV().property("aai-node-type", "pnf")
- .property("pnf-name", "test-pnf-name-01")
- .property("in-maint", false)
- .property("source-of-truth", "JUNIT")
- .property("aai-uri", "/network/pnfs/pnf/test-pnf-name-01").next();
- Vertex vserver2 = g.addV().property("aai-node-type", "vserver")
- .property("vserver-id", "test-vserver-id-2")
- .property("vserver-name", "test-vserver-name-2")
- .property("in-maint", "false")
- .property("source-of-truth", "JUNIT")
- .property("aai-uri", "/vservers/vserver/test-vserver-id-2").next();
- Vertex tenant2 = g.addV().property("aai-node-type", "tenant")
- .property("tenant-id", "test-tenant-id-2")
- .property("tenant-name", "test-tenant-name-2")
- .property("source-of-truth", "JUNIT")
- .property("aai-uri", "/tenants/tenant/test-tenant-id-2").next();
- Vertex linterface2 = g.addV().property("aai-node-type", "l-interface")
- .property("interface-name", "test-interface-name-02")
- .property("priority", "123")
- .property("is-port-mirrored", "true")
- .property("source-of-truth", "JUNIT")
- .property("aai-uri", "/l-interfaces/l-interface/test-interface-name-02").next();
- Vertex oamNetwork2 = g.addV().property("aai-node-type", "oam-network")
- .property("network-uuid", "test-network-uuid-02")
- .property("network-name", "test-network-name-02")
- .property("cvlan-tag", "456")
- .property("source-of-truth", "JUNIT")
- .property("aai-uri", "/oam-networks/oam-network/test-network-uuid-02").next();
- Vertex cr2 = g.addV().property("aai-node-type", "cloud-region")
- .property("cloud-owner", "test-cloud-owner-02")
- .property("cloud-region-id", "test-cloud-region-id-02")
- .property("source-of-truth", "JUNIT")
- .property("aai-uri", "/cloud-infrastructure/cloud-regions/cloud-region/test-cloud-owner-02/test-cloud-region-id-02").next();
-
- // For adding edges, check the dbedgetules and the property from and to node
- // along with the other properties to populate information
- p1.addEdge("org.onap.relationships.inventory.LocatedIn", c1,
- "private", false,
- "prevent-delete", "NONE",
- "delete-other-v", "NONE",
- "contains-other-v", "NONE",
- "default", true);
- p1.addEdge("org.onap.relationships.inventory.LocatedIn", cr1,
- "private", false,
- "prevent-delete", "NONE",
- "delete-other-v", "NONE",
- "contains-other-v", "NONE",
- "default", true);
- p3.addEdge("org.onap.relationships.inventory.LocatedIn", c1,
- "private", false,
- "prevent-delete", "NONE",
- "delete-other-v", "NONE",
- "contains-other-v", "NONE",
- "default", true);
- p4.addEdge("org.onap.relationships.inventory.LocatedIn", c1,
- "private", false,
- "prevent-delete", "NONE",
- "delete-other-v", "NONE",
- "contains-other-v", "NONE",
- "default", true);
- tenant2.addEdge("org.onap.relationships.inventory.BelongsTo", cr2,
- "private", false,
- "prevent-delete", "NONE",
- "delete-other-v", "NONE",
- "contains-other-v", "NONE",
- "default", true);
- vserver2.addEdge("org.onap.relationships.inventory.BelongsTo", tenant2,
- "private", false,
- "prevent-delete", "NONE",
- "delete-other-v", "NONE",
- "contains-other-v", "NONE",
- "default", true);
- linterface2.addEdge("tosca.relationships.network.BindsTo", vserver2,
- "direction", "OUT",
- "multiplicity", "MANY2ONE",
- "contains-other-v", "!OUT",
- "delete-other-v", "!OUT",
- "prevent-delete", "NONE",
- "default", true);
- oamNetwork2.addEdge("org.onap.relationships.inventory.BelongsTo", cr2,
- "direction", "OUT",
- "multiplicity", "MANY2ONE",
- "contains-other-v", "!OUT",
- "delete-other-v", "NONE",
- "prevent-delete", "!OUT",
- "default", true);
-
-
- } catch (Exception ex) {
- success = false;
- } finally {
- if (success) {
- transaction.commit();
- } else {
- transaction.rollback();
- fail("Unable to setup the graph");
- }
- }
- }
-
- @Test
- public void testDslQuery() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=console";
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver*('hostname','test-pserver-dsl')");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- headers.add("X-Dsl-Version", "V1");
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity,
- String.class);
- LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint, responseEntity.getBody());
- System.out.println(responseEntity.getBody());
- assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
- assertEquals("Expected the response to be 200", HttpStatus.OK, responseEntity.getStatusCode());
-
- headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
- httpEntity = new HttpEntity(payload, headers);
- responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity,
- String.class);
- LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint, responseEntity.getBody());
- assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
- assertEquals("Expected the response to be 200", HttpStatus.OK, responseEntity.getStatusCode());
-
- // Make sure that there are no two result <result><result>
- assertThat(responseEntity.getBody().toString(), is(not(containsString("<result><result>"))));
- assertThat(responseEntity.getBody().toString(), is(containsString("<results><result>")));
- }
-
- @Test
- public void testDslQueryV2() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=console";
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver*('hostname','test-pserver-dsl') > complex*");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- headers.add("X-Dsl-Version", "V2");
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity,
- String.class);
- LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint, responseEntity.getBody());
- assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
- assertEquals("Expected the response to be 200", HttpStatus.OK, responseEntity.getStatusCode());
-
- headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
- httpEntity = new HttpEntity(payload, headers);
- responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity,
- String.class);
- LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint, responseEntity.getBody());
- assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
- assertEquals("Expected the response to be 200", HttpStatus.OK, responseEntity.getStatusCode());
-
- // Make sure that there are no two result <result><result>
- assertThat(responseEntity.getBody().toString(), is(not(containsString("<result><result>"))));
- assertThat(responseEntity.getBody().toString(), is(containsString("<results><result>")));
- }
-
- @Test
- public void testDslQueryV2Aggregate() throws Exception {
- String endpoint = "/aai/v17/dsl?format=aggregate";
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver*('hostname','test-pserver-dsl')");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- System.out.println("Payload" + payload);
- headers.add("X-Dsl-Version", "V2");
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity,
- String.class);
- LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint, responseEntity.getBody());
- System.out.println(responseEntity.getBody());
- assertNotNull("Response from /aai/v17/dsl is not null", responseEntity);
- assertEquals("Expected the response to be 200", HttpStatus.OK, responseEntity.getStatusCode());
- }
-
- @Test
- public void testDslQueryException() throws Exception {
- Map<String, String> dslQuerymap = new HashMap<>();
- dslQuerymap.put("dsl-query", "xserver");
-
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQuerymap);
-
- ResponseEntity responseEntity = null;
-
- String endpoint = "/aai/v11/dsl?format=console";
-
- httpEntity = new HttpEntity(payload, headers);
- responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- assertEquals("Expected the response to be 404", HttpStatus.BAD_REQUEST,
- responseEntity.getStatusCode());
- }
-
- @Test
- public void testDslQueryOverride() throws Exception {
- Map<String, String> dslQuerymap = new HashMap<>();
- dslQuerymap.put("dsl-query", "pserver*");
-
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQuerymap);
-
- ResponseEntity responseEntity = null;
-
- String endpoint = "/aai/v11/dsl?format=console";
-
- headers.add("X-DslOverride", AAIConfig.get(TraversalConstants.DSL_OVERRIDE));
- httpEntity = new HttpEntity(payload, headers);
- responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- assertEquals("Expected the response to be 404", HttpStatus.BAD_REQUEST,
- responseEntity.getStatusCode());
- }
-
-
- @Test
- public void testSelectedPropertiesNotRequiredOnDSLStartNode() throws Exception {
- Map<String, String> dslQuerymap = new HashMap<>();
- dslQuerymap.put("dsl-query", "pserver*('equip-model','abc')");
-
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQuerymap);
-
- String endpoint = "/aai/v11/dsl?format=console";
-
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
-
- assertEquals("Expected the response to be " + HttpStatus.OK, HttpStatus.OK,
- responseEntity.getStatusCode());
- }
-
- @Test
- public void testAPropertyIsRequiredOnDSLStartNode() throws Exception {
- Map<String, String> dslQuerymap = new HashMap<>();
- dslQuerymap.put("dsl-query", "pserver*");
-
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQuerymap);
-
- String endpoint = "/aai/v11/dsl?format=console";
-
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
-
- assertEquals("Expected the response to be " + HttpStatus.BAD_REQUEST, HttpStatus.BAD_REQUEST,
- responseEntity.getStatusCode());
- }
-
- @Test
- public void testDslQueryProcessingV2_WithSimpleFormat_WithAsTreeQueryParameter() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver{'hostname', 'ptnii-equip-name', 'in-maint'}('hostname','test-pserver-dsl')");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v16/dsl?format=simple&depth=0&nodesOnly=true&as-tree=true";
-
- // Add header with V2 to use the {} feature as a part of dsl query
- headers.add("X-DslApiVersion","V2");
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
-
- // Extract the properties array from the response and compare in assert statements
- JsonParser jsonParser = new JsonParser();
- JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
- JsonArray resultsArray = results.get("results").getAsJsonArray();
- JsonObject resultsValue = resultsArray.get(0).getAsJsonObject();
- JsonObject properties = resultsValue.get("properties").getAsJsonObject();
- assertEquals(2, properties.size());
- assertTrue(properties.get("hostname").toString().equals("\"test-pserver-dsl\""));
- assertTrue(properties.get("in-maint").toString().equals("false"));
- headers.remove("X-DslApiVersion");
- }
-
- @Test
- public void testDslQueryProcessingV2_WithSimpleFormat_WithoutAsTreeQueryParameter() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver{'hostname', 'ptnii-equip-name', 'in-maint'}('hostname','test-pserver-dsl')");
-
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v16/dsl?format=simple&depth=0&nodesOnly=true";
-
- // Add header with V2 to use the {} feature as a part of dsl query
- headers.add("X-DslApiVersion","V2");
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
- // Extract the properties array from the response and compare in assert statements
- JsonParser jsonParser = new JsonParser();
- JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
- JsonArray resultsArray = results.get("results").getAsJsonArray();
- JsonObject resultsValue = resultsArray.get(0).getAsJsonObject();
- JsonObject properties = resultsValue.get("properties").getAsJsonObject();
- assertEquals(2, properties.size());
- assertTrue(properties.get("hostname").toString().equals("\"test-pserver-dsl\""));
- assertTrue(properties.get("in-maint").toString().equals("false"));
- headers.remove("X-DslApiVersion");
- }
-
- @Test
- public void testDslQueryProcessingV2_WithResourceFormat_WithAsTreeQueryParameter() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver{'hostname', 'ptnii-equip-name', 'in-maint'}('hostname','test-pserver-dsl')");
-
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v16/dsl?format=resource&depth=0&nodesOnly=true&as-tree=true";
-
- // Add header with V2 to use the {} feature as a part of dsl query
- headers.add("X-DslApiVersion","V2");
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
-
- // Extract the properties array from the response and compare in assert statements
- JsonParser jsonParser = new JsonParser();
- JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
- JsonArray resultsArray = results.get("results").getAsJsonArray();
- JsonObject resultsValue = resultsArray.get(0).getAsJsonObject();
- JsonObject properties = resultsValue.get("pserver").getAsJsonObject();
- assertEquals(2, properties.size());
- assertTrue(properties.get("hostname").toString().equals("\"test-pserver-dsl\""));
- assertTrue(properties.get("in-maint").toString().equals("false"));
- headers.remove("X-DslApiVersion");
- }
-
- @Test
- public void testDslQueryProcessingV2_WithResourceFormat_WithoutAsTreeQueryParameter() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver{'hostname', 'ptnii-equip-name', 'in-maint'}('hostname','test-pserver-dsl')");
-
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v16/dsl?format=resource&depth=0&nodesOnly=true";
-
- // Add header with V2 to use the {} feature as a part of dsl query
- headers.add("X-DslApiVersion","V2");
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
-
- // Extract the properties array from the response and compare in assert statements
- JsonParser jsonParser = new JsonParser();
- JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
- JsonArray resultsArray = results.get("results").getAsJsonArray();
- JsonObject resultsValue = resultsArray.get(0).getAsJsonObject();
- JsonObject properties = resultsValue.get("pserver").getAsJsonObject();
- assertEquals(2, properties.size());
- assertTrue(properties.get("hostname").toString().equals("\"test-pserver-dsl\""));
- assertTrue(properties.get("in-maint").toString().equals("false"));
- headers.remove("X-DslApiVersion");
- }
-
- @Test
- public void testDslQueryProcessingV2_WithResourceAndUrlFormat_WithAsTreeQueryParameter() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver{'hostname', 'ptnii-equip-name', 'in-maint'}('hostname','test-pserver-dsl')");
-
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v16/dsl?format=resource_and_url&depth=0&nodesOnly=true&as-tree=true";
-
- // Add header with V2 to use the {} feature as a part of dsl query
- headers.add("X-DslApiVersion","V2");
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
-
- // Extract the properties array from the response and compare in assert statements
- JsonParser jsonParser = new JsonParser();
- JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
- JsonArray resultsArray = results.get("results").getAsJsonArray();
- JsonObject resultsValue = resultsArray.get(0).getAsJsonObject();
- JsonObject properties = resultsValue.get("pserver").getAsJsonObject();
- assertEquals(2, properties.size());
- assertTrue(properties.get("hostname").toString().equals("\"test-pserver-dsl\""));
- assertTrue(properties.get("in-maint").toString().equals("false"));
- headers.remove("X-DslApiVersion");
- }
-
- @Test
- public void testDslQueryProcessingV2_WithResourceAndUrlFormat_WithoutAsTreeQueryParameter() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver{'hostname', 'ptnii-equip-name', 'in-maint'}('hostname','test-pserver-dsl')");
-
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v16/dsl?format=resource_and_url&depth=0&nodesOnly=true";
-
- // Add header with V2 to use the {} feature as a part of dsl query
- headers.add("X-DslApiVersion","V2");
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
-
- // Extract the properties array from the response and compare in assert statements
- JsonParser jsonParser = new JsonParser();
- JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
- JsonArray resultsArray = results.get("results").getAsJsonArray();
- JsonObject resultsValue = resultsArray.get(0).getAsJsonObject();
- JsonObject properties = resultsValue.get("pserver").getAsJsonObject();
- assertEquals(2, properties.size());
- assertTrue(properties.get("hostname").toString().equals("\"test-pserver-dsl\""));
- assertTrue(properties.get("in-maint").toString().equals("false"));
- headers.remove("X-DslApiVersion");
- }
-
- @Test
- public void testDslQueryTestAggregateFormatLastNodeNotSelectedAndNotReturned() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver{'hostname'}('hostname','test-pserver-dsl') > complex");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v16/dsl?format=aggregate";
-
- // Add header with V2 to use the {} feature as a part of dsl query
- headers.add("X-DslApiVersion","V2");
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
- // Extract the properties array from the response and compare in assert statements
- JsonParser jsonParser = new JsonParser();
- JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
- JsonArray resultsArray = results.get("results").getAsJsonArray();
- JsonObject resultsValue = resultsArray.get(0).getAsJsonObject();
- assertNull(resultsValue.get("/aai/v16/cloud-infrastructure/complexes/complex/test-complex-dsl")); //assert complex is not returned since it is not selected
- JsonObject properties = resultsValue.get("/aai/v16/cloud-infrastructure/pservers/pserver/test-pserver-dsl").getAsJsonObject().get("properties").getAsJsonObject();
- assertEquals(1, properties.size());
- assertThat(properties.get("hostname").toString(), is("\"test-pserver-dsl\"")); //assert only hostname is selected
- assertNull(properties.get("in-maint")); //assert that in-maint is not returned in the properties list
- headers.remove("X-DslApiVersion");
- }
-
- @Test
- public void testDslQueryTestAggregateFormatLastNodeSelectedAndReturned() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver{'hostname'}('hostname','test-pserver-dsl') > complex*");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v16/dsl?format=aggregate";
-
- // Add header with V2 to use the {} feature as a part of dsl query
- headers.add("X-DslApiVersion","V2");
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
- // Extract the properties array from the response and compare in assert statements
- JsonParser jsonParser = new JsonParser();
- JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
- JsonArray resultsArray = results.get("results").getAsJsonArray();
- JsonArray resultsValue = resultsArray.get(0).getAsJsonArray();
- assertNotNull(resultsValue.get(1).getAsJsonObject().get("/aai/v16/cloud-infrastructure/complexes/complex/test-complex-dsl")); //assert complex is returned since it is selected
- JsonObject properties = resultsValue.get(0).getAsJsonObject().get("/aai/v16/cloud-infrastructure/pservers/pserver/test-pserver-dsl").getAsJsonObject().get("properties").getAsJsonObject();
- assertEquals(1, properties.size());
- assertThat(properties.get("hostname").toString(), is("\"test-pserver-dsl\"")); //verify that only selected attribute (hostname) is displayed
- assertNull(properties.get("in-maint")); //assert that in-maint is not returned in the properties list
- JsonObject complexProperties = resultsValue.get(1).getAsJsonObject().get("/aai/v16/cloud-infrastructure/complexes/complex/test-complex-dsl").getAsJsonObject().get("properties").getAsJsonObject();
- assertEquals(2, complexProperties.size()); //internal properties like source-of-truth, node-type and aai-uri are not returned.
- headers.remove("X-DslApiVersion");
- }
-
- @Test
- public void testDslQueryTestAggregateFormatInternalPropsNotReturned() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver*('hostname','test-pserver-dsl')");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v16/dsl?format=aggregate";
-
- // Add header with V2 to use the {} feature as a part of dsl query
- headers.add("X-DslApiVersion","V2");
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
- // Extract the properties array from the response and compare in assert statements
- JsonParser jsonParser = new JsonParser();
- JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
- JsonArray resultsArray = results.get("results").getAsJsonArray();
- JsonObject properties = resultsArray.get(0).getAsJsonObject().get("/aai/v16/cloud-infrastructure/pservers/pserver/test-pserver-dsl").getAsJsonObject().get("properties").getAsJsonObject();
- assertEquals(2, properties.size());
- assertThat(properties.get("hostname").toString(), is("\"test-pserver-dsl\"")); //verify that only hostname is displayed
- assertNull(properties.get("source-of-truth")); //assert that source-of-truth is not returned in properties list
- headers.remove("X-DslApiVersion");
- }
-
- @Test
- public void testDslQueryTestWithMultipleWheres() throws Exception {
- // Return pservers where pserver has edge to complex "AND" same pserver also has an edge to cloud-region
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver*('hostname','test-pserver-dsl')(> complex)(> cloud-region)");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v18/dsl?format=aggregate";
-
- // Add header with V2 to use the {} feature as a part of dsl query
- headers.add("X-DslApiVersion","V2");
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
- // Extract the properties array from the response and compare in assert statements
- JsonParser jsonParser = new JsonParser();
- JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
- JsonArray resultsArray = results.get("results").getAsJsonArray();
- assertEquals(1, resultsArray.size()); // Returns only test-pserver-dsl, does not return test-pserver-dsl-03 since it does not have an edge to cloud-region
- assertEquals(null, resultsArray.get(0).getAsJsonObject().get("/aai/v18/cloud-infrastructure/pservers/pserver/test-pserver-dsl-03")); //not returned
- assertNotNull(resultsArray.get(0).getAsJsonObject().get("/aai/v18/cloud-infrastructure/pservers/pserver/test-pserver-dsl"));
- headers.remove("X-DslApiVersion");
- }
-
- @Test
- public void testDslQueryTestWithMultipleWhereNots() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver*('hostname')!(> complex)!(> cloud-region)");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v18/dsl?format=aggregate";
-
- // Add header with V2 to use the {} feature as a part of dsl query
- headers.add("X-DslApiVersion","V2");
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
- // Extract the properties array from the response and compare in assert statements
- JsonParser jsonParser = new JsonParser();
- JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
- JsonArray resultsArray = results.get("results").getAsJsonArray();
- assertEquals(1, resultsArray.size()); // Returns only test-pserver-dsl-02
- assertEquals(null, resultsArray.get(0).getAsJsonObject().get("/aai/v18/cloud-infrastructure/pservers/pserver/test-pserver-dsl")); //not returned
- assertNotNull(resultsArray.get(0).getAsJsonObject().get("/aai/v18/cloud-infrastructure/pservers/pserver/test-pserver-dsl-02"));
- headers.remove("X-DslApiVersion");
- }
-
- @Test
- public void testDslQueryProcessing_ExpectedError_WrongDataType() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver*('number-of-cpus','test')");
-
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v16/dsl?format=simple";
-
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
- Assert.assertTrue(responseString.contains(
- "Value ['test'] is not an instance of the expected data type for property key ['number-of-cpus'] and cannot be converted. " +
- "Expected: class java.lang.Integer, found: class java.lang.String"));
- }
-
- @Test
- public void testDslQueryOnComplex_WithResourceFormatWithUnionAsStartNode_ReturnSuccessfulResponse() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "[complex*('source-of-truth', 'JUNIT'), complex*('aai-uri', '/cloud-infrastructure/complexes/complex/test-complex-dsl')]");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v16/dsl?format=resource";
-
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
-
- // Extract the properties array from the response and compare in assert statements
- JsonParser jsonParser = new JsonParser();
- JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
- JsonArray resultsArray = results.get("results").getAsJsonArray();
- JsonObject resultValue = resultsArray.get(0).getAsJsonObject();
- JsonObject complex = resultValue.get("complex").getAsJsonObject();
- Assert.assertEquals("\"test-complex-dsl\"", complex.get("physical-location-id").toString());
- }
-
- @Test
- public void testDslQueryOnPserver_WithResourceFormatWithUnionAsStartNode_ReturnSuccessfulResponse() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "[pserver*('hostname','test-pserver-dsl'), complex*('physical-location-id', 'test-complex-dsl')]");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v16/dsl?format=resource";
-
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
-
- // Extract the properties array from the response and compare in assert statements
- JsonParser jsonParser = new JsonParser();
- JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
- JsonArray resultsArray = results.get("results").getAsJsonArray();
- for (JsonElement je : resultsArray) {
- JsonObject jo = je.getAsJsonObject();
- if (jo.get("complex") != null) {
- Assert.assertEquals("\"test-complex-dsl\"", jo.get("complex").getAsJsonObject().get("physical-location-id").toString());
- }
- else if (jo.get("pserver") != null) {
- Assert.assertEquals("\"test-pserver-dsl\"", jo.get("pserver").getAsJsonObject().get("hostname").toString());
- } else {
- Assert.fail();
- }
- }
- }
-
- @Test
- public void testDslQueryOnNodesWithEdges_WithResourceFormatWithUnionAsStartNode_ReturnSuccessfulResponse() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "[pserver*('hostname','test-pserver-dsl-02'), pserver*('hostname','test-pserver-dsl')>complex*, pnf('pnf-name','pnf-name-noResults')>lag-interface>l-interface] > complex*");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v16/dsl?format=resource";
-
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString(); // pnf should have no results
-
- JsonParser jsonParser = new JsonParser();
- JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
- JsonArray resultsArray = results.get("results").getAsJsonArray();
- boolean hasPserver1 = false, hasPserver2 = false;
- for (JsonElement je : resultsArray) {
- JsonObject jo = je.getAsJsonObject();
- if (jo.get("complex") != null) {
- Assert.assertEquals("\"test-complex-dsl\"", jo.get("complex").getAsJsonObject().get("physical-location-id").toString());
- }
- else if (jo.get("pserver") != null) {
- if (jo.get("pserver").getAsJsonObject().get("hostname").toString().equals("\"test-pserver-dsl\"")){
- hasPserver1 = true;
- }
- if (jo.get("pserver").getAsJsonObject().get("hostname").toString().equals("\"test-pserver-dsl-02\"")) {
- hasPserver2 = true;
- }
- } else {
- Assert.fail();
- }
- }
- Assert.assertTrue(hasPserver1 && hasPserver2);
- }
-
- @Test
- public void testDslQueryOnNodesWithEdges2_WithResourceFormatWithUnionAsStartNode_ReturnSuccessfulResponse() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "[pnf*('pnf-name','test-pnf-name-01'),pserver(>cloud-region*('cloud-owner','test-cloud-owner-01'))]");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- String endpoint = "/aai/v16/dsl?format=resource";
-
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
-
- JsonParser jsonParser = new JsonParser();
- JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
- JsonArray resultsArray = results.get("results").getAsJsonArray();
- for (JsonElement je : resultsArray) {
- JsonObject jo = je.getAsJsonObject();
- if (jo.get("pnf") != null) {
- Assert.assertEquals("\"test-pnf-name-01\"", jo.get("pnf").getAsJsonObject().get("pnf-name").toString());
- }
- else if (jo.get("cloud-region") != null) {
- Assert.assertEquals("\"test-cloud-owner-01\"", jo.get("cloud-region").getAsJsonObject().get("cloud-owner").toString());
- } else {
- Assert.fail();
- }
- }
- }
-
- @Test
- public void testDslQuery_IsAgnosticWithBooleanPropertyAsString_ReturnSuccessfulResponse() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
-
- // With expected boolean value "false" as a boolean value (no quotes)
- dslQueryMap.put("dsl-query", "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 1)");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
-
- // Confirm that the vserver was returned in the response
- Assert.assertTrue(responseString.contains("\"vserver-id\":\"test-vserver-id-2\"") );
-
- dslQueryMap.remove("dsl-query", "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 1)");
-
- // With expected boolean value of in-maint, "false", in string form (with single quotes)
- dslQueryMap.put("dsl-query", "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 'false')");
- payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
-
- httpEntity = new HttpEntity(payload, headers);
- responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- responseString = responseEntity.getBody().toString();
- // Confirm that the vserver was returned in the response
- Assert.assertTrue(responseString.contains("\"vserver-id\":\"test-vserver-id-2\"") );
- }
-
- @Test
- public void testDslQuery_IsAgnosticWithWrongBooleanPropertyAsString_ReturnSuccessfulResponse() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
-
- // all string values not boolean related default to false
- dslQueryMap.put("dsl-query", "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 'bogusBoolean')>l-interface*('priority', 123)");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
-
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
- // Confirm that the l-interface was returned in the response
- Assert.assertTrue(responseString.contains("\"interface-name\":\"test-interface-name-02\"") );
- }
-
- @Test
- public void testDslQuery_IsAgnosticWithBooleanPropertyAsInteger0_ReturnSuccessfulResponse() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
-
- // 0 is false, should return value
- dslQueryMap.put("dsl-query", "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 0)>l-interface*('priority', 123)");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
-
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
- // Confirm that the l-interface was returned in the response
- Assert.assertTrue(responseString.contains("\"interface-name\":\"test-interface-name-02\"") );
- }
-
- @Test
- public void testDslQuery_IsAgnosticWithBooleanPropertyAsInteger1_ReturnSuccessfulResponse() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
-
- // 0 is false, should return value
- dslQueryMap.put("dsl-query", "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 1)>l-interface*('priority', 123)");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
-
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
- // Confirm that the l-interface was returned in the response
- Assert.assertTrue(!responseString.contains("\"interface-name\":\"test-interface-name-02\"") );
- }
-
- @Test
- public void testDslQuery_IsAgnosticWithBooleanPropertyAsTrue_ReturnSuccessfulResponse() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
-
- // 0 is false, should return value
- dslQueryMap.put("dsl-query", "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', true)>l-interface*('priority', 123)");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
-
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
- // Confirm that the l-interface was returned in the response
- Assert.assertTrue(!responseString.contains("\"interface-name\":\"test-interface-name-02\"") );
- }
-
- @Test
- public void testDslQuery_IsAgnosticWithBooleanPropertyAsTrueString_ReturnSuccessfulResponse() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
-
- // 0 is false, should return value
- dslQueryMap.put("dsl-query", "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 'true')>l-interface*('priority', 123)");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
-
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
- // Confirm that the l-interface was returned in the response
- Assert.assertTrue(!responseString.contains("\"interface-name\":\"test-interface-name-02\"") );
- }
-
- @Test
- public void testDslQuery_IsAgnosticWithIntegerPropertyAsString_ReturnSuccessfulResponse() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
-
- // With expected boolean value "false" as a boolean value (no quotes)
- dslQueryMap.put("dsl-query", "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', false)>l-interface*('priority', '00123')");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
-
- // Confirm that the l-interface was returned in the response
- Assert.assertTrue(responseString.contains("\"interface-name\":\"test-interface-name-02\"") );
- dslQueryMap.remove("dsl-query", "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', false)>l-interface*('priority', '00123')");
-
- // With expected boolean value of in-maint, "false", in string form (with single quotes)
- dslQueryMap.put("dsl-query", "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 'false')>l-interface*('priority', 00123)");
- payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
-
- httpEntity = new HttpEntity(payload, headers);
- responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- responseString = responseEntity.getBody().toString();
-
- // Confirm that the l-interface was returned in the response
- Assert.assertTrue(responseString.contains("\"interface-name\":\"test-interface-name-02\"") );
- }
-
- @Test
- public void testDslQuery_IsAgnosticWithLongPropertyAsString_ReturnSuccessfulResponse() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
-
- // With expected boolean value "false" as a boolean value (no quotes)
- dslQueryMap.put("dsl-query", "cloud-region*('cloud-owner', 'test-cloud-owner-02')>oam-network*('cvlan-tag', '456')");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
-
- // Confirm that the oam-network was returned in the response
- Assert.assertTrue(responseString.contains("\"cvlan-tag\":456"));
- dslQueryMap.remove("dsl-query", "cloud-region*('cloud-owner', 'test-cloud-owner-02')>oam-network*('cvlan-tag', '456')");
-
- dslQueryMap.put("dsl-query", "cloud-region*('cloud-owner', 'test-cloud-owner-02')>oam-network*('cvlan-tag', 456)");
- payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
-
- httpEntity = new HttpEntity(payload, headers);
- responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- responseString = responseEntity.getBody().toString();
-
- // Confirm that the oam-network was returned in the response
- Assert.assertTrue(responseString.contains("\"cvlan-tag\":456"));
- }
-
- @Test
- public void testDslQuery_IsAgnosticWithPrimitivePropertiesInList_ReturnSuccessfulResponse() throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
-
- // With expected boolean value "false" as a boolean value (no quotes)
- dslQueryMap.put("dsl-query", "complex('state')>pserver*('number-of-cpus', '234', '364', 2342)");
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- String responseString = responseEntity.getBody().toString();
-
- // Confirm that the pserver was returned in the response
- Assert.assertTrue(responseString.contains("\"number-of-cpus\":364"));
- dslQueryMap.remove("dsl-query", "complex('state')>pserver*('number-of-cpus', '234', '364', 2342)");
-
- dslQueryMap.put("dsl-query", "complex('state')>pserver*('number-of-cpus', '234', 364, 2342)");
- payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
-
- httpEntity = new HttpEntity(payload, headers);
- responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- responseString = responseEntity.getBody().toString();
-
- // Confirm that the pserver was returned in the response
- Assert.assertTrue(responseString.contains("\"number-of-cpus\":364"));
- }
+ private static final Logger LOGGER = LoggerFactory.getLogger(DslConsumerTest.class);
+
+ @Override
+ public void createTestGraph() {
+ JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
+ boolean success = true;
+ try {
+ GraphTraversalSource g = transaction.traversal();
+ Vertex p1 = g.addV().property("aai-node-type", "pserver")
+ .property("hostname", "test-pserver-dsl").property("in-maint", false)
+ .property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/cloud-infrastructure/pservers/pserver/test-pserver-dsl")
+ .next();
+ Vertex p2 = g.addV().property("aai-node-type", "pserver")
+ .property("hostname", "test-pserver-dsl-02").property("in-maint", false)
+ .property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/cloud-infrastructure/pservers/pserver/test-pserver-dsl-02")
+ .next();
+ Vertex p3 = g.addV().property("aai-node-type", "pserver")
+ .property("hostname", "test-pserver-dsl-03").property("in-maint", false)
+ .property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/cloud-infrastructure/pservers/pserver/test-pserver-dsl-03")
+ .next();
+ Vertex p4 = g.addV().property("aai-node-type", "pserver")
+ .property("hostname", "test-pserver-dsl-04").property("in-maint", false)
+ .property("source-of-truth", "JUNIT").property("number-of-cpus", 364)
+ .property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/cloud-infrastructure/pservers/pserver/test-pserver-dsl-04")
+ .next();
+ Vertex c1 = g.addV().property("aai-node-type", "complex")
+ .property("physical-location-id", "test-complex-dsl").property("state", "NJ")
+ .property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/cloud-infrastructure/complexes/complex/test-complex-dsl")
+ .next();
+ Vertex cr1 = g.addV().property("aai-node-type", "cloud-region")
+ .property("cloud-owner", "test-cloud-owner-01")
+ .property("cloud-region-id", "test-cloud-region-id-01")
+ .property("source-of-truth", "JUNIT")
+ .property("aai-uri",
+ "/cloud-infrastructure/cloud-regions/cloud-region/test-cloud-owner-01/test-cloud-region-id-01")
+ .next();
+ Vertex pnf01 =
+ g.addV().property("aai-node-type", "pnf").property("pnf-name", "test-pnf-name-01")
+ .property("in-maint", false).property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/network/pnfs/pnf/test-pnf-name-01").next();
+ Vertex vserver2 = g.addV().property("aai-node-type", "vserver")
+ .property("vserver-id", "test-vserver-id-2")
+ .property("vserver-name", "test-vserver-name-2").property("in-maint", "false")
+ .property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/vservers/vserver/test-vserver-id-2").next();
+ Vertex tenant2 = g.addV().property("aai-node-type", "tenant")
+ .property("tenant-id", "test-tenant-id-2")
+ .property("tenant-name", "test-tenant-name-2").property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/tenants/tenant/test-tenant-id-2").next();
+ Vertex linterface2 = g.addV().property("aai-node-type", "l-interface")
+ .property("interface-name", "test-interface-name-02").property("priority", "123")
+ .property("is-port-mirrored", "true").property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/l-interfaces/l-interface/test-interface-name-02").next();
+ Vertex oamNetwork2 = g.addV().property("aai-node-type", "oam-network")
+ .property("network-uuid", "test-network-uuid-02")
+ .property("network-name", "test-network-name-02").property("cvlan-tag", "456")
+ .property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/oam-networks/oam-network/test-network-uuid-02").next();
+ Vertex cr2 = g.addV().property("aai-node-type", "cloud-region")
+ .property("cloud-owner", "test-cloud-owner-02")
+ .property("cloud-region-id", "test-cloud-region-id-02")
+ .property("source-of-truth", "JUNIT")
+ .property("aai-uri",
+ "/cloud-infrastructure/cloud-regions/cloud-region/test-cloud-owner-02/test-cloud-region-id-02")
+ .next();
+
+ // For adding edges, check the dbedgetules and the property from and to node
+ // along with the other properties to populate information
+ p1.addEdge("org.onap.relationships.inventory.LocatedIn", c1, "private", false,
+ "prevent-delete", "NONE", "delete-other-v", "NONE", "contains-other-v", "NONE",
+ "default", true);
+ p1.addEdge("org.onap.relationships.inventory.LocatedIn", cr1, "private", false,
+ "prevent-delete", "NONE", "delete-other-v", "NONE", "contains-other-v", "NONE",
+ "default", true);
+ p3.addEdge("org.onap.relationships.inventory.LocatedIn", c1, "private", false,
+ "prevent-delete", "NONE", "delete-other-v", "NONE", "contains-other-v", "NONE",
+ "default", true);
+ p4.addEdge("org.onap.relationships.inventory.LocatedIn", c1, "private", false,
+ "prevent-delete", "NONE", "delete-other-v", "NONE", "contains-other-v", "NONE",
+ "default", true);
+ tenant2.addEdge("org.onap.relationships.inventory.BelongsTo", cr2, "private", false,
+ "prevent-delete", "NONE", "delete-other-v", "NONE", "contains-other-v", "NONE",
+ "default", true);
+ vserver2.addEdge("org.onap.relationships.inventory.BelongsTo", tenant2, "private",
+ false, "prevent-delete", "NONE", "delete-other-v", "NONE", "contains-other-v",
+ "NONE", "default", true);
+ linterface2.addEdge("tosca.relationships.network.BindsTo", vserver2, "direction", "OUT",
+ "multiplicity", "MANY2ONE", "contains-other-v", "!OUT", "delete-other-v", "!OUT",
+ "prevent-delete", "NONE", "default", true);
+ oamNetwork2.addEdge("org.onap.relationships.inventory.BelongsTo", cr2, "direction",
+ "OUT", "multiplicity", "MANY2ONE", "contains-other-v", "!OUT", "delete-other-v",
+ "NONE", "prevent-delete", "!OUT", "default", true);
+
+ } catch (Exception ex) {
+ success = false;
+ } finally {
+ if (success) {
+ transaction.commit();
+ } else {
+ transaction.rollback();
+ fail("Unable to setup the graph");
+ }
+ }
+ }
+
+ @Test
+ public void testDslQuery() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=console";
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query", "pserver*('hostname','test-pserver-dsl')");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ headers.add("X-Dsl-Version", "V1");
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint,
+ responseEntity.getBody());
+ System.out.println(responseEntity.getBody());
+ assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
+ assertEquals("Expected the response to be 200", HttpStatus.OK,
+ responseEntity.getStatusCode());
+
+ headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
+ httpEntity = new HttpEntity(payload, headers);
+ responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint,
+ responseEntity.getBody());
+ assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
+ assertEquals("Expected the response to be 200", HttpStatus.OK,
+ responseEntity.getStatusCode());
+
+ // Make sure that there are no two result <result><result>
+ assertThat(responseEntity.getBody().toString(),
+ is(not(containsString("<result><result>"))));
+ assertThat(responseEntity.getBody().toString(), is(containsString("<results><result>")));
+ }
+
+ @Test
+ public void testDslQueryV2() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=console";
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query", "pserver*('hostname','test-pserver-dsl') > complex*");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ headers.add("X-Dsl-Version", "V2");
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint,
+ responseEntity.getBody());
+ assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
+ assertEquals("Expected the response to be 200", HttpStatus.OK,
+ responseEntity.getStatusCode());
+
+ headers.setAccept(Collections.singletonList(MediaType.APPLICATION_XML));
+ httpEntity = new HttpEntity(payload, headers);
+ responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint,
+ responseEntity.getBody());
+ assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
+ assertEquals("Expected the response to be 200", HttpStatus.OK,
+ responseEntity.getStatusCode());
+
+ // Make sure that there are no two result <result><result>
+ assertThat(responseEntity.getBody().toString(),
+ is(not(containsString("<result><result>"))));
+ assertThat(responseEntity.getBody().toString(), is(containsString("<results><result>")));
+ }
+
+ @Test
+ public void testDslQueryV2Aggregate() throws Exception {
+ String endpoint = "/aai/v17/dsl?format=aggregate";
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query", "pserver*('hostname','test-pserver-dsl')");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ System.out.println("Payload" + payload);
+ headers.add("X-Dsl-Version", "V2");
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint,
+ responseEntity.getBody());
+ System.out.println(responseEntity.getBody());
+ assertNotNull("Response from /aai/v17/dsl is not null", responseEntity);
+ assertEquals("Expected the response to be 200", HttpStatus.OK,
+ responseEntity.getStatusCode());
+ }
+
+ @Test
+ public void testDslQueryException() throws Exception {
+ Map<String, String> dslQuerymap = new HashMap<>();
+ dslQuerymap.put("dsl-query", "xserver");
+
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQuerymap);
+
+ ResponseEntity responseEntity = null;
+
+ String endpoint = "/aai/v11/dsl?format=console";
+
+ httpEntity = new HttpEntity(payload, headers);
+ responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ assertEquals("Expected the response to be 404", HttpStatus.BAD_REQUEST,
+ responseEntity.getStatusCode());
+ }
+
+ @Test
+ public void testDslQueryOverride() throws Exception {
+ Map<String, String> dslQuerymap = new HashMap<>();
+ dslQuerymap.put("dsl-query", "pserver*");
+
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQuerymap);
+
+ ResponseEntity responseEntity = null;
+
+ String endpoint = "/aai/v11/dsl?format=console";
+
+ headers.add("X-DslOverride", AAIConfig.get(TraversalConstants.DSL_OVERRIDE));
+ httpEntity = new HttpEntity(payload, headers);
+ responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ assertEquals("Expected the response to be 404", HttpStatus.BAD_REQUEST,
+ responseEntity.getStatusCode());
+ }
+
+ @Test
+ public void testSelectedPropertiesNotRequiredOnDSLStartNode() throws Exception {
+ Map<String, String> dslQuerymap = new HashMap<>();
+ dslQuerymap.put("dsl-query", "pserver*('equip-model','abc')");
+
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQuerymap);
+
+ String endpoint = "/aai/v11/dsl?format=console";
+
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+
+ assertEquals("Expected the response to be " + HttpStatus.OK, HttpStatus.OK,
+ responseEntity.getStatusCode());
+ }
+
+ @Test
+ public void testAPropertyIsRequiredOnDSLStartNode() throws Exception {
+ Map<String, String> dslQuerymap = new HashMap<>();
+ dslQuerymap.put("dsl-query", "pserver*");
+
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQuerymap);
+
+ String endpoint = "/aai/v11/dsl?format=console";
+
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+
+ assertEquals("Expected the response to be " + HttpStatus.BAD_REQUEST,
+ HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
+ }
+
+ @Test
+ public void testDslQueryProcessingV2_WithSimpleFormat_WithAsTreeQueryParameter()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "pserver{'hostname', 'ptnii-equip-name', 'in-maint'}('hostname','test-pserver-dsl')");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint = "/aai/v16/dsl?format=simple&depth=0&nodesOnly=true&as-tree=true";
+
+ // Add header with V2 to use the {} feature as a part of dsl query
+ headers.add("X-DslApiVersion", "V2");
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+
+ // Extract the properties array from the response and compare in assert statements
+ JsonParser jsonParser = new JsonParser();
+ JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
+ JsonArray resultsArray = results.get("results").getAsJsonArray();
+ JsonObject resultsValue = resultsArray.get(0).getAsJsonObject();
+ JsonObject properties = resultsValue.get("properties").getAsJsonObject();
+ assertEquals(2, properties.size());
+ assertTrue(properties.get("hostname").toString().equals("\"test-pserver-dsl\""));
+ assertTrue(properties.get("in-maint").toString().equals("false"));
+ headers.remove("X-DslApiVersion");
+ }
+
+ @Test
+ public void testDslQueryProcessingV2_WithSimpleFormat_WithoutAsTreeQueryParameter()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "pserver{'hostname', 'ptnii-equip-name', 'in-maint'}('hostname','test-pserver-dsl')");
+
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint = "/aai/v16/dsl?format=simple&depth=0&nodesOnly=true";
+
+ // Add header with V2 to use the {} feature as a part of dsl query
+ headers.add("X-DslApiVersion", "V2");
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+ // Extract the properties array from the response and compare in assert statements
+ JsonParser jsonParser = new JsonParser();
+ JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
+ JsonArray resultsArray = results.get("results").getAsJsonArray();
+ JsonObject resultsValue = resultsArray.get(0).getAsJsonObject();
+ JsonObject properties = resultsValue.get("properties").getAsJsonObject();
+ assertEquals(2, properties.size());
+ assertTrue(properties.get("hostname").toString().equals("\"test-pserver-dsl\""));
+ assertTrue(properties.get("in-maint").toString().equals("false"));
+ headers.remove("X-DslApiVersion");
+ }
+
+ @Test
+ public void testDslQueryProcessingV2_WithResourceFormat_WithAsTreeQueryParameter()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "pserver{'hostname', 'ptnii-equip-name', 'in-maint'}('hostname','test-pserver-dsl')");
+
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint = "/aai/v16/dsl?format=resource&depth=0&nodesOnly=true&as-tree=true";
+
+ // Add header with V2 to use the {} feature as a part of dsl query
+ headers.add("X-DslApiVersion", "V2");
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+
+ // Extract the properties array from the response and compare in assert statements
+ JsonParser jsonParser = new JsonParser();
+ JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
+ JsonArray resultsArray = results.get("results").getAsJsonArray();
+ JsonObject resultsValue = resultsArray.get(0).getAsJsonObject();
+ JsonObject properties = resultsValue.get("pserver").getAsJsonObject();
+ assertEquals(2, properties.size());
+ assertTrue(properties.get("hostname").toString().equals("\"test-pserver-dsl\""));
+ assertTrue(properties.get("in-maint").toString().equals("false"));
+ headers.remove("X-DslApiVersion");
+ }
+
+ @Test
+ public void testDslQueryProcessingV2_WithResourceFormat_WithoutAsTreeQueryParameter()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "pserver{'hostname', 'ptnii-equip-name', 'in-maint'}('hostname','test-pserver-dsl')");
+
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint = "/aai/v16/dsl?format=resource&depth=0&nodesOnly=true";
+
+ // Add header with V2 to use the {} feature as a part of dsl query
+ headers.add("X-DslApiVersion", "V2");
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+
+ // Extract the properties array from the response and compare in assert statements
+ JsonParser jsonParser = new JsonParser();
+ JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
+ JsonArray resultsArray = results.get("results").getAsJsonArray();
+ JsonObject resultsValue = resultsArray.get(0).getAsJsonObject();
+ JsonObject properties = resultsValue.get("pserver").getAsJsonObject();
+ assertEquals(2, properties.size());
+ assertTrue(properties.get("hostname").toString().equals("\"test-pserver-dsl\""));
+ assertTrue(properties.get("in-maint").toString().equals("false"));
+ headers.remove("X-DslApiVersion");
+ }
+
+ @Test
+ public void testDslQueryProcessingV2_WithResourceAndUrlFormat_WithAsTreeQueryParameter()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "pserver{'hostname', 'ptnii-equip-name', 'in-maint'}('hostname','test-pserver-dsl')");
+
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint =
+ "/aai/v16/dsl?format=resource_and_url&depth=0&nodesOnly=true&as-tree=true";
+
+ // Add header with V2 to use the {} feature as a part of dsl query
+ headers.add("X-DslApiVersion", "V2");
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+
+ // Extract the properties array from the response and compare in assert statements
+ JsonParser jsonParser = new JsonParser();
+ JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
+ JsonArray resultsArray = results.get("results").getAsJsonArray();
+ JsonObject resultsValue = resultsArray.get(0).getAsJsonObject();
+ JsonObject properties = resultsValue.get("pserver").getAsJsonObject();
+ assertEquals(2, properties.size());
+ assertTrue(properties.get("hostname").toString().equals("\"test-pserver-dsl\""));
+ assertTrue(properties.get("in-maint").toString().equals("false"));
+ headers.remove("X-DslApiVersion");
+ }
+
+ @Test
+ public void testDslQueryProcessingV2_WithResourceAndUrlFormat_WithoutAsTreeQueryParameter()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "pserver{'hostname', 'ptnii-equip-name', 'in-maint'}('hostname','test-pserver-dsl')");
+
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint = "/aai/v16/dsl?format=resource_and_url&depth=0&nodesOnly=true";
+
+ // Add header with V2 to use the {} feature as a part of dsl query
+ headers.add("X-DslApiVersion", "V2");
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+
+ // Extract the properties array from the response and compare in assert statements
+ JsonParser jsonParser = new JsonParser();
+ JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
+ JsonArray resultsArray = results.get("results").getAsJsonArray();
+ JsonObject resultsValue = resultsArray.get(0).getAsJsonObject();
+ JsonObject properties = resultsValue.get("pserver").getAsJsonObject();
+ assertEquals(2, properties.size());
+ assertTrue(properties.get("hostname").toString().equals("\"test-pserver-dsl\""));
+ assertTrue(properties.get("in-maint").toString().equals("false"));
+ headers.remove("X-DslApiVersion");
+ }
+
+ @Test
+ public void testDslQueryTestAggregateFormatLastNodeNotSelectedAndNotReturned()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "pserver{'hostname'}('hostname','test-pserver-dsl') > complex");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint = "/aai/v16/dsl?format=aggregate";
+
+ // Add header with V2 to use the {} feature as a part of dsl query
+ headers.add("X-DslApiVersion", "V2");
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+ // Extract the properties array from the response and compare in assert statements
+ JsonParser jsonParser = new JsonParser();
+ JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
+ JsonArray resultsArray = results.get("results").getAsJsonArray();
+ JsonObject resultsValue = resultsArray.get(0).getAsJsonObject();
+ assertNull(
+ resultsValue.get("/aai/v16/cloud-infrastructure/complexes/complex/test-complex-dsl")); // assert
+ // complex
+ // is
+ // not
+ // returned
+ // since
+ // it
+ // is
+ // not
+ // selected
+ JsonObject properties =
+ resultsValue.get("/aai/v16/cloud-infrastructure/pservers/pserver/test-pserver-dsl")
+ .getAsJsonObject().get("properties").getAsJsonObject();
+ assertEquals(1, properties.size());
+ assertThat(properties.get("hostname").toString(), is("\"test-pserver-dsl\"")); // assert
+ // only
+ // hostname
+ // is
+ // selected
+ assertNull(properties.get("in-maint")); // assert that in-maint is not returned in the
+ // properties list
+ headers.remove("X-DslApiVersion");
+ }
+
+ @Test
+ public void testDslQueryTestAggregateFormatLastNodeSelectedAndReturned() throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "pserver{'hostname'}('hostname','test-pserver-dsl') > complex*");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint = "/aai/v16/dsl?format=aggregate";
+
+ // Add header with V2 to use the {} feature as a part of dsl query
+ headers.add("X-DslApiVersion", "V2");
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+ // Extract the properties array from the response and compare in assert statements
+ JsonParser jsonParser = new JsonParser();
+ JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
+ JsonArray resultsArray = results.get("results").getAsJsonArray();
+ JsonArray resultsValue = resultsArray.get(0).getAsJsonArray();
+ assertNotNull(resultsValue.get(1).getAsJsonObject()
+ .get("/aai/v16/cloud-infrastructure/complexes/complex/test-complex-dsl")); // assert
+ // complex is
+ // returned
+ // since it
+ // is
+ // selected
+ JsonObject properties = resultsValue.get(0).getAsJsonObject()
+ .get("/aai/v16/cloud-infrastructure/pservers/pserver/test-pserver-dsl")
+ .getAsJsonObject().get("properties").getAsJsonObject();
+ assertEquals(1, properties.size());
+ assertThat(properties.get("hostname").toString(), is("\"test-pserver-dsl\"")); // verify
+ // that only
+ // selected
+ // attribute
+ // (hostname)
+ // is
+ // displayed
+ assertNull(properties.get("in-maint")); // assert that in-maint is not returned in the
+ // properties list
+ JsonObject complexProperties = resultsValue.get(1).getAsJsonObject()
+ .get("/aai/v16/cloud-infrastructure/complexes/complex/test-complex-dsl")
+ .getAsJsonObject().get("properties").getAsJsonObject();
+ assertEquals(2, complexProperties.size()); // internal properties like source-of-truth,
+ // node-type and aai-uri are not returned.
+ headers.remove("X-DslApiVersion");
+ }
+
+ @Test
+ public void testDslQueryTestAggregateFormatInternalPropsNotReturned() throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query", "pserver*('hostname','test-pserver-dsl')");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint = "/aai/v16/dsl?format=aggregate";
+
+ // Add header with V2 to use the {} feature as a part of dsl query
+ headers.add("X-DslApiVersion", "V2");
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+ // Extract the properties array from the response and compare in assert statements
+ JsonParser jsonParser = new JsonParser();
+ JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
+ JsonArray resultsArray = results.get("results").getAsJsonArray();
+ JsonObject properties = resultsArray.get(0).getAsJsonObject()
+ .get("/aai/v16/cloud-infrastructure/pservers/pserver/test-pserver-dsl")
+ .getAsJsonObject().get("properties").getAsJsonObject();
+ assertEquals(2, properties.size());
+ assertThat(properties.get("hostname").toString(), is("\"test-pserver-dsl\"")); // verify
+ // that only
+ // hostname
+ // is
+ // displayed
+ assertNull(properties.get("source-of-truth")); // assert that source-of-truth is not
+ // returned in properties list
+ headers.remove("X-DslApiVersion");
+ }
+
+ @Test
+ public void testDslQueryTestWithMultipleWheres() throws Exception {
+ // Return pservers where pserver has edge to complex "AND" same pserver also has an edge to
+ // cloud-region
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "pserver*('hostname','test-pserver-dsl')(> complex)(> cloud-region)");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint = "/aai/v18/dsl?format=aggregate";
+
+ // Add header with V2 to use the {} feature as a part of dsl query
+ headers.add("X-DslApiVersion", "V2");
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+ // Extract the properties array from the response and compare in assert statements
+ JsonParser jsonParser = new JsonParser();
+ JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
+ JsonArray resultsArray = results.get("results").getAsJsonArray();
+ assertEquals(1, resultsArray.size()); // Returns only test-pserver-dsl, does not return
+ // test-pserver-dsl-03 since it does not have an edge
+ // to cloud-region
+ assertEquals(null, resultsArray.get(0).getAsJsonObject()
+ .get("/aai/v18/cloud-infrastructure/pservers/pserver/test-pserver-dsl-03")); // not
+ // returned
+ assertNotNull(resultsArray.get(0).getAsJsonObject()
+ .get("/aai/v18/cloud-infrastructure/pservers/pserver/test-pserver-dsl"));
+ headers.remove("X-DslApiVersion");
+ }
+
+ @Test
+ public void testDslQueryTestWithMultipleWhereNots() throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query", "pserver*('hostname')!(> complex)!(> cloud-region)");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint = "/aai/v18/dsl?format=aggregate";
+
+ // Add header with V2 to use the {} feature as a part of dsl query
+ headers.add("X-DslApiVersion", "V2");
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+ // Extract the properties array from the response and compare in assert statements
+ JsonParser jsonParser = new JsonParser();
+ JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
+ JsonArray resultsArray = results.get("results").getAsJsonArray();
+ assertEquals(1, resultsArray.size()); // Returns only test-pserver-dsl-02
+ assertEquals(null, resultsArray.get(0).getAsJsonObject()
+ .get("/aai/v18/cloud-infrastructure/pservers/pserver/test-pserver-dsl")); // not
+ // returned
+ assertNotNull(resultsArray.get(0).getAsJsonObject()
+ .get("/aai/v18/cloud-infrastructure/pservers/pserver/test-pserver-dsl-02"));
+ headers.remove("X-DslApiVersion");
+ }
+
+ @Test
+ public void testDslQueryProcessing_ExpectedError_WrongDataType() throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query", "pserver*('number-of-cpus','test')");
+
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint = "/aai/v16/dsl?format=simple";
+
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+ Assert.assertTrue(responseString.contains(
+ "Value ['test'] is not an instance of the expected data type for property key ['number-of-cpus'] and cannot be converted. "
+ + "Expected: class java.lang.Integer, found: class java.lang.String"));
+ }
+
+ @Test
+ public void testDslQueryOnComplex_WithResourceFormatWithUnionAsStartNode_ReturnSuccessfulResponse()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "[complex*('source-of-truth', 'JUNIT'), complex*('aai-uri', '/cloud-infrastructure/complexes/complex/test-complex-dsl')]");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint = "/aai/v16/dsl?format=resource";
+
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+
+ // Extract the properties array from the response and compare in assert statements
+ JsonParser jsonParser = new JsonParser();
+ JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
+ JsonArray resultsArray = results.get("results").getAsJsonArray();
+ JsonObject resultValue = resultsArray.get(0).getAsJsonObject();
+ JsonObject complex = resultValue.get("complex").getAsJsonObject();
+ Assert.assertEquals("\"test-complex-dsl\"", complex.get("physical-location-id").toString());
+ }
+
+ @Test
+ public void testDslQueryOnPserver_WithResourceFormatWithUnionAsStartNode_ReturnSuccessfulResponse()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "[pserver*('hostname','test-pserver-dsl'), complex*('physical-location-id', 'test-complex-dsl')]");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint = "/aai/v16/dsl?format=resource";
+
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+
+ // Extract the properties array from the response and compare in assert statements
+ JsonParser jsonParser = new JsonParser();
+ JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
+ JsonArray resultsArray = results.get("results").getAsJsonArray();
+ for (JsonElement je : resultsArray) {
+ JsonObject jo = je.getAsJsonObject();
+ if (jo.get("complex") != null) {
+ Assert.assertEquals("\"test-complex-dsl\"",
+ jo.get("complex").getAsJsonObject().get("physical-location-id").toString());
+ } else if (jo.get("pserver") != null) {
+ Assert.assertEquals("\"test-pserver-dsl\"",
+ jo.get("pserver").getAsJsonObject().get("hostname").toString());
+ } else {
+ Assert.fail();
+ }
+ }
+ }
+
+ @Test
+ public void testDslQueryOnNodesWithEdges_WithResourceFormatWithUnionAsStartNode_ReturnSuccessfulResponse()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "[pserver*('hostname','test-pserver-dsl-02'), pserver*('hostname','test-pserver-dsl')>complex*, pnf('pnf-name','pnf-name-noResults')>lag-interface>l-interface] > complex*");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint = "/aai/v16/dsl?format=resource";
+
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString(); // pnf should have no results
+
+ JsonParser jsonParser = new JsonParser();
+ JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
+ JsonArray resultsArray = results.get("results").getAsJsonArray();
+ boolean hasPserver1 = false, hasPserver2 = false;
+ for (JsonElement je : resultsArray) {
+ JsonObject jo = je.getAsJsonObject();
+ if (jo.get("complex") != null) {
+ Assert.assertEquals("\"test-complex-dsl\"",
+ jo.get("complex").getAsJsonObject().get("physical-location-id").toString());
+ } else if (jo.get("pserver") != null) {
+ if (jo.get("pserver").getAsJsonObject().get("hostname").toString()
+ .equals("\"test-pserver-dsl\"")) {
+ hasPserver1 = true;
+ }
+ if (jo.get("pserver").getAsJsonObject().get("hostname").toString()
+ .equals("\"test-pserver-dsl-02\"")) {
+ hasPserver2 = true;
+ }
+ } else {
+ Assert.fail();
+ }
+ }
+ Assert.assertTrue(hasPserver1 && hasPserver2);
+ }
+
+ @Test
+ public void testDslQueryOnNodesWithEdges2_WithResourceFormatWithUnionAsStartNode_ReturnSuccessfulResponse()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "[pnf*('pnf-name','test-pnf-name-01'),pserver(>cloud-region*('cloud-owner','test-cloud-owner-01'))]");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ String endpoint = "/aai/v16/dsl?format=resource";
+
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+
+ JsonParser jsonParser = new JsonParser();
+ JsonObject results = jsonParser.parse(responseString).getAsJsonObject();
+ JsonArray resultsArray = results.get("results").getAsJsonArray();
+ for (JsonElement je : resultsArray) {
+ JsonObject jo = je.getAsJsonObject();
+ if (jo.get("pnf") != null) {
+ Assert.assertEquals("\"test-pnf-name-01\"",
+ jo.get("pnf").getAsJsonObject().get("pnf-name").toString());
+ } else if (jo.get("cloud-region") != null) {
+ Assert.assertEquals("\"test-cloud-owner-01\"",
+ jo.get("cloud-region").getAsJsonObject().get("cloud-owner").toString());
+ } else {
+ Assert.fail();
+ }
+ }
+ }
+
+ @Test
+ public void testDslQuery_IsAgnosticWithBooleanPropertyAsString_ReturnSuccessfulResponse()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
+
+ // With expected boolean value "false" as a boolean value (no quotes)
+ dslQueryMap.put("dsl-query",
+ "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 1)");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+
+ // Confirm that the vserver was returned in the response
+ Assert.assertTrue(responseString.contains("\"vserver-id\":\"test-vserver-id-2\""));
+
+ dslQueryMap.remove("dsl-query",
+ "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 1)");
+
+ // With expected boolean value of in-maint, "false", in string form (with single quotes)
+ dslQueryMap.put("dsl-query",
+ "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 'false')");
+ payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+
+ httpEntity = new HttpEntity(payload, headers);
+ responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ responseString = responseEntity.getBody().toString();
+ // Confirm that the vserver was returned in the response
+ Assert.assertTrue(responseString.contains("\"vserver-id\":\"test-vserver-id-2\""));
+ }
+
+ @Test
+ public void testDslQuery_IsAgnosticWithWrongBooleanPropertyAsString_ReturnSuccessfulResponse()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
+
+ // all string values not boolean related default to false
+ dslQueryMap.put("dsl-query",
+ "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 'bogusBoolean')>l-interface*('priority', 123)");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+ // Confirm that the l-interface was returned in the response
+ Assert.assertTrue(responseString.contains("\"interface-name\":\"test-interface-name-02\""));
+ }
+
+ @Test
+ public void testDslQuery_IsAgnosticWithBooleanPropertyAsInteger0_ReturnSuccessfulResponse()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
+
+ // 0 is false, should return value
+ dslQueryMap.put("dsl-query",
+ "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 0)>l-interface*('priority', 123)");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+ // Confirm that the l-interface was returned in the response
+ Assert.assertTrue(responseString.contains("\"interface-name\":\"test-interface-name-02\""));
+ }
+
+ @Test
+ public void testDslQuery_IsAgnosticWithBooleanPropertyAsInteger1_ReturnSuccessfulResponse()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
+
+ // 0 is false, should return value
+ dslQueryMap.put("dsl-query",
+ "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 1)>l-interface*('priority', 123)");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+ // Confirm that the l-interface was returned in the response
+ Assert
+ .assertTrue(!responseString.contains("\"interface-name\":\"test-interface-name-02\""));
+ }
+
+ @Test
+ public void testDslQuery_IsAgnosticWithBooleanPropertyAsTrue_ReturnSuccessfulResponse()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
+
+ // 0 is false, should return value
+ dslQueryMap.put("dsl-query",
+ "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', true)>l-interface*('priority', 123)");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+ // Confirm that the l-interface was returned in the response
+ Assert
+ .assertTrue(!responseString.contains("\"interface-name\":\"test-interface-name-02\""));
+ }
+
+ @Test
+ public void testDslQuery_IsAgnosticWithBooleanPropertyAsTrueString_ReturnSuccessfulResponse()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
+
+ // 0 is false, should return value
+ dslQueryMap.put("dsl-query",
+ "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 'true')>l-interface*('priority', 123)");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+ // Confirm that the l-interface was returned in the response
+ Assert
+ .assertTrue(!responseString.contains("\"interface-name\":\"test-interface-name-02\""));
+ }
+
+ @Test
+ public void testDslQuery_IsAgnosticWithIntegerPropertyAsString_ReturnSuccessfulResponse()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
+
+ // With expected boolean value "false" as a boolean value (no quotes)
+ dslQueryMap.put("dsl-query",
+ "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', false)>l-interface*('priority', '00123')");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+
+ // Confirm that the l-interface was returned in the response
+ Assert.assertTrue(responseString.contains("\"interface-name\":\"test-interface-name-02\""));
+ dslQueryMap.remove("dsl-query",
+ "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', false)>l-interface*('priority', '00123')");
+
+ // With expected boolean value of in-maint, "false", in string form (with single quotes)
+ dslQueryMap.put("dsl-query",
+ "cloud-region*('cloud-owner', 'test-cloud-owner-02')>tenant*>vserver*('in-maint', 'false')>l-interface*('priority', 00123)");
+ payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+
+ httpEntity = new HttpEntity(payload, headers);
+ responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ responseString = responseEntity.getBody().toString();
+
+ // Confirm that the l-interface was returned in the response
+ Assert.assertTrue(responseString.contains("\"interface-name\":\"test-interface-name-02\""));
+ }
+
+ @Test
+ public void testDslQuery_IsAgnosticWithLongPropertyAsString_ReturnSuccessfulResponse()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
+
+ // With expected boolean value "false" as a boolean value (no quotes)
+ dslQueryMap.put("dsl-query",
+ "cloud-region*('cloud-owner', 'test-cloud-owner-02')>oam-network*('cvlan-tag', '456')");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+
+ // Confirm that the oam-network was returned in the response
+ Assert.assertTrue(responseString.contains("\"cvlan-tag\":456"));
+ dslQueryMap.remove("dsl-query",
+ "cloud-region*('cloud-owner', 'test-cloud-owner-02')>oam-network*('cvlan-tag', '456')");
+
+ dslQueryMap.put("dsl-query",
+ "cloud-region*('cloud-owner', 'test-cloud-owner-02')>oam-network*('cvlan-tag', 456)");
+ payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+
+ httpEntity = new HttpEntity(payload, headers);
+ responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ responseString = responseEntity.getBody().toString();
+
+ // Confirm that the oam-network was returned in the response
+ Assert.assertTrue(responseString.contains("\"cvlan-tag\":456"));
+ }
+
+ @Test
+ public void testDslQuery_IsAgnosticWithPrimitivePropertiesInList_ReturnSuccessfulResponse()
+ throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ String endpoint = "/aai/v19/dsl?format=resource&nodesOnly=true";
+
+ // With expected boolean value "false" as a boolean value (no quotes)
+ dslQueryMap.put("dsl-query",
+ "complex('state')>pserver*('number-of-cpus', '234', '364', 2342)");
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ String responseString = responseEntity.getBody().toString();
+
+ // Confirm that the pserver was returned in the response
+ Assert.assertTrue(responseString.contains("\"number-of-cpus\":364"));
+ dslQueryMap.remove("dsl-query",
+ "complex('state')>pserver*('number-of-cpus', '234', '364', 2342)");
+
+ dslQueryMap.put("dsl-query",
+ "complex('state')>pserver*('number-of-cpus', '234', 364, 2342)");
+ payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+
+ httpEntity = new HttpEntity(payload, headers);
+ responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ responseString = responseEntity.getBody().toString();
+
+ // Confirm that the pserver was returned in the response
+ Assert.assertTrue(responseString.contains("\"number-of-cpus\":364"));
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/ExceptionHandlerTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/ExceptionHandlerTest.java
index 6a7bd7e..6281892 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/ExceptionHandlerTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/ExceptionHandlerTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,15 +19,18 @@
*/
package org.onap.aai.rest;
+import static org.junit.Assert.*;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
import com.fasterxml.jackson.core.JsonLocation;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.sun.istack.SAXParseException2;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.InjectMocks;
-import org.mockito.Mock;
-import org.mockito.MockitoAnnotations;
+
+import java.util.ArrayList;
+import java.util.List;
+import java.util.UUID;
import javax.servlet.http.HttpServletRequest;
import javax.ws.rs.WebApplicationException;
@@ -35,13 +38,12 @@ import javax.ws.rs.core.HttpHeaders;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.MultivaluedHashMap;
import javax.ws.rs.core.Response;
-import java.util.ArrayList;
-import java.util.List;
-import java.util.UUID;
-import static org.junit.Assert.*;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.InjectMocks;
+import org.mockito.Mock;
+import org.mockito.MockitoAnnotations;
public class ExceptionHandlerTest {
@@ -57,10 +59,10 @@ public class ExceptionHandlerTest {
private ExceptionHandler handler = new ExceptionHandler();
@Before
- public void setup(){
+ public void setup() {
MockitoAnnotations.initMocks(this);
- MultivaluedHashMap headersMultiMap = new MultivaluedHashMap<>();
+ MultivaluedHashMap headersMultiMap = new MultivaluedHashMap<>();
headersMultiMap.add("X-FromAppId", "JUNIT");
headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
@@ -82,11 +84,12 @@ public class ExceptionHandlerTest {
assertNotNull(response);
assertNull(response.getEntity());
- assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
+ assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
}
@Test
- public void testConversionOfWebApplicationResponseWhenUmarshalExceptionResultBadRequest() throws Exception {
+ public void testConversionOfWebApplicationResponseWhenUmarshalExceptionResultBadRequest()
+ throws Exception {
SAXParseException2 mockSaxParseException = mock(SAXParseException2.class);
Exception exception = new WebApplicationException(mockSaxParseException);
@@ -94,7 +97,7 @@ public class ExceptionHandlerTest {
assertNotNull(response);
assertNotNull(response.getEntity());
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
@@ -106,7 +109,7 @@ public class ExceptionHandlerTest {
assertNotNull(response);
assertNotNull(response.getEntity());
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
@@ -118,7 +121,7 @@ public class ExceptionHandlerTest {
assertNotNull(response);
assertNotNull(response.getEntity());
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
@@ -131,13 +134,13 @@ public class ExceptionHandlerTest {
assertNotNull(response);
assertNotNull(response.getEntity());
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
-
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
@Test
- public void testConversionWhenUnknownExceptionResultBadRequestForXmlResponseType() throws Exception {
+ public void testConversionWhenUnknownExceptionResultBadRequestForXmlResponseType()
+ throws Exception {
List<MediaType> outputMediaTypes = new ArrayList<>();
outputMediaTypes.add(MediaType.valueOf("application/xml"));
@@ -149,6 +152,6 @@ public class ExceptionHandlerTest {
assertNotNull(response);
assertNotNull(response.getEntity());
- assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
+ assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
}
-} \ No newline at end of file
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/GfpVserverDataStoredQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/GfpVserverDataStoredQueryTest.java
index 8acbd4e..845ddf9 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/GfpVserverDataStoredQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/GfpVserverDataStoredQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,15 +19,25 @@
*/
package org.onap.aai.rest;
-import org.onap.aai.config.PropertyPasswordConfiguration;
-import org.onap.aai.transforms.XmlFormatTransformer;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import static org.hamcrest.CoreMatchers.containsString;
+import static org.hamcrest.MatcherAssert.assertThat;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
import com.att.eelf.configuration.EELFManager;
import com.jayway.jsonpath.JsonPath;
+
+import java.util.*;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.*;
+
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.janusgraph.core.JanusGraph;
import org.janusgraph.core.JanusGraphTransaction;
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
@@ -35,26 +45,19 @@ import org.mockito.Mockito;
import org.onap.aai.AAISetup;
import org.onap.aai.HttpTestUtil;
import org.onap.aai.PayloadUtil;
+import org.onap.aai.config.PropertyPasswordConfiguration;
import org.onap.aai.dbmap.AAIGraph;
import org.onap.aai.setup.SchemaVersion;
+import org.onap.aai.transforms.XmlFormatTransformer;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.test.context.ContextConfiguration;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.*;
-import java.util.*;
-
-import static org.hamcrest.CoreMatchers.containsString;
-import static org.hamcrest.MatcherAssert.assertThat;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
@ContextConfiguration(initializers = PropertyPasswordConfiguration.class)
-public class GfpVserverDataStoredQueryTest extends AAISetup{
+public class GfpVserverDataStoredQueryTest extends AAISetup {
- private static final Logger logger = LoggerFactory.getLogger(GfpVserverDataStoredQueryTest.class);
+ private static final Logger logger =
+ LoggerFactory.getLogger(GfpVserverDataStoredQueryTest.class);
protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
@@ -79,9 +82,8 @@ public class GfpVserverDataStoredQueryTest extends AAISetup{
version = schemaVersions.getDefaultVersion();
- cloudRegionUri = "/aai/" + version.toString()
- + "/cloud-infrastructure/cloud-regions/"
- + "cloud-region/testOwner1/testRegion1";
+ cloudRegionUri = "/aai/" + version.toString() + "/cloud-infrastructure/cloud-regions/"
+ + "cloud-region/testOwner1/testRegion1";
httpTestUtil = new HttpTestUtil();
Map<String, String> templateValues = new HashMap<>();
@@ -97,8 +99,8 @@ public class GfpVserverDataStoredQueryTest extends AAISetup{
templateValues.put("ipv6-address", "2001:0db8:85a3:0000:0000:8a2e:0370:7334");
templateValues.put("vlan-interface", "vlan-interface1");
- String cloudRegionPayload = PayloadUtil.
- getTemplatePayload("cloud-region-with-linterface.json", templateValues);
+ String cloudRegionPayload =
+ PayloadUtil.getTemplatePayload("cloud-region-with-linterface.json", templateValues);
Response response = httpTestUtil.doPut(cloudRegionUri, cloudRegionPayload);
logger.info("Response status received {}", response.getEntity());
@@ -107,12 +109,13 @@ public class GfpVserverDataStoredQueryTest extends AAISetup{
assertEquals("Expecting the cloud region to be created", 201, response.getStatus());
logger.info("Successfully created the cloud region with linterface");
- queryConsumer = new QueryConsumer(traversalUriHttpEntry, schemaVersions, gremlinServerSingleton, new XmlFormatTransformer(), basePath);
+ queryConsumer = new QueryConsumer(traversalUriHttpEntry, schemaVersions,
+ gremlinServerSingleton, new XmlFormatTransformer(), basePath);
- httpHeaders = mock(HttpHeaders.class);
+ httpHeaders = mock(HttpHeaders.class);
- headersMultiMap = new MultivaluedHashMap<>();
- queryParameters = Mockito.spy(new MultivaluedHashMap<>());
+ headersMultiMap = new MultivaluedHashMap<>();
+ queryParameters = Mockito.spy(new MultivaluedHashMap<>());
headersMultiMap.add("X-FromAppId", "JUNIT");
headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
@@ -138,7 +141,8 @@ public class GfpVserverDataStoredQueryTest extends AAISetup{
}
@Test
- public void testStoredQueryVerifyDoesNotThrowMethodTooLargeWhenLargeNumberOfStartingVertexes() throws Exception {
+ public void testStoredQueryVerifyDoesNotThrowMethodTooLargeWhenLargeNumberOfStartingVertexes()
+ throws Exception {
// Add hundred thousand vserver vertexes to properly
// test the scenario where the application was
@@ -166,23 +170,15 @@ public class GfpVserverDataStoredQueryTest extends AAISetup{
Mockito.when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
when(uriInfo.getPath()).thenReturn(query);
HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
- when(mockRequest.getRequestURL()).thenReturn(new StringBuffer("https://localhost:8446" + query));
-
- Response response = queryConsumer.executeQuery(
- payload,
- version.toString(),
- "resource_and_url", "" +
- "no_op",
- httpHeaders,
- mockRequest,
- uriInfo,
- "-1",
- "-1"
- );
+ when(mockRequest.getRequestURL())
+ .thenReturn(new StringBuffer("https://localhost:8446" + query));
+
+ Response response = queryConsumer.executeQuery(payload, version.toString(),
+ "resource_and_url", "" + "no_op", httpHeaders, mockRequest, uriInfo, "-1", "-1");
String entity = response.getEntity().toString();
- assertEquals("Expected the response to be 200 but got this returned: " + response.getEntity().toString(),
- 200, response.getStatus());
+ assertEquals("Expected the response to be 200 but got this returned: "
+ + response.getEntity().toString(), 200, response.getStatus());
List<String> urls = JsonPath.read(entity, "$.results[*].url");
assertEquals("Expected the urls to be 3", 3, urls.size());
removeVertexes();
@@ -207,31 +203,24 @@ public class GfpVserverDataStoredQueryTest extends AAISetup{
when(uriInfo.getPath()).thenReturn(query);
HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
- when(mockRequest.getRequestURL()).thenReturn(new StringBuffer("https://localhost:8446" + query));
-
- Response response = queryConsumer.executeQuery(
- payload,
- version.toString(),
- "resource_and_url", "" +
- "no_op",
- httpHeaders,
- mockRequest,
- uriInfo,
- "-1",
- "-1"
- );
+ when(mockRequest.getRequestURL())
+ .thenReturn(new StringBuffer("https://localhost:8446" + query));
+
+ Response response = queryConsumer.executeQuery(payload, version.toString(),
+ "resource_and_url", "" + "no_op", httpHeaders, mockRequest, uriInfo, "-1", "-1");
String entity = response.getEntity().toString();
- assertEquals("Expected the response to be 400 but got this returned: " + entity,
- 400, response.getStatus());
+ assertEquals("Expected the response to be 400 but got this returned: " + entity, 400,
+ response.getStatus());
assertThat("Expecting error message since query doesn't exist", entity,
- containsString("Query payload is invalid"));
+ containsString("Query payload is invalid"));
}
@Test
- public void testStoredQueryWhenStartFilterReturnsZeroVertexesItShouldHandleProperly() throws Exception {
+ public void testStoredQueryWhenStartFilterReturnsZeroVertexesItShouldHandleProperly()
+ throws Exception {
Map<String, String> templateValues = new HashMap<>();
@@ -248,35 +237,27 @@ public class GfpVserverDataStoredQueryTest extends AAISetup{
Mockito.when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
when(uriInfo.getPath()).thenReturn(query);
HttpServletRequest mockRequest = Mockito.mock(HttpServletRequest.class);
- when(mockRequest.getRequestURL()).thenReturn(new StringBuffer("https://localhost:8446" + query));
-
+ when(mockRequest.getRequestURL())
+ .thenReturn(new StringBuffer("https://localhost:8446" + query));
- Response response = queryConsumer.executeQuery(
- payload,
- version.toString(),
- "resource_and_url", "" +
- "no_op",
- httpHeaders,
- mockRequest,
- uriInfo,
- "-1",
- "-1"
- );
+ Response response = queryConsumer.executeQuery(payload, version.toString(),
+ "resource_and_url", "" + "no_op", httpHeaders, mockRequest, uriInfo, "-1", "-1");
String entity = response.getEntity().toString();
- assertEquals("Expected the response to be 404 but got this returned: " + entity,
- 404, response.getStatus());
+ assertEquals("Expected the response to be 404 but got this returned: " + entity, 404,
+ response.getStatus());
- assertThat(entity, containsString("Start URI returned no vertexes, please check the start URI"));
+ assertThat(entity,
+ containsString("Start URI returned no vertexes, please check the start URI"));
}
@After
- public void tearDown(){
+ public void tearDown() {
removeVertexes();
}
- private void removeVertexes(){
+ private void removeVertexes() {
JanusGraph JanusGraph = AAIGraph.getInstance().getGraph();
JanusGraphTransaction transaction = JanusGraph.newTransaction();
@@ -286,12 +267,12 @@ public class GfpVserverDataStoredQueryTest extends AAISetup{
try {
GraphTraversalSource g = transaction.traversal();
g.V().has("source-of-truth", "JUNIT").toList().stream()
- .forEach((vertex) -> vertex.remove());
- } catch(Exception ex){
+ .forEach((vertex) -> vertex.remove());
+ } catch (Exception ex) {
success = false;
logger.error("Unable to remove all of the junit vservers due to {}", ex);
} finally {
- if(success){
+ if (success) {
transaction.commit();
} else {
transaction.rollback();
@@ -300,7 +281,7 @@ public class GfpVserverDataStoredQueryTest extends AAISetup{
}
- private void addVservers(int vserversCount){
+ private void addVservers(int vserversCount) {
JanusGraph JanusGraph = AAIGraph.getInstance().getGraph();
JanusGraphTransaction transaction = JanusGraph.newTransaction();
@@ -310,20 +291,19 @@ public class GfpVserverDataStoredQueryTest extends AAISetup{
try {
GraphTraversalSource g = transaction.traversal();
- for(int index = 0; index < vserversCount; index++){
+ for (int index = 0; index < vserversCount; index++) {
String randomVserverId = UUID.randomUUID().toString();
g.addV().property("aai-node-type", "vserver")
- .property( "vserver-id", "random-" + randomVserverId)
- .property( "vserver-name", "junit-vservers")
- .property( "source-of-truth", "JUNIT")
- .next();
+ .property("vserver-id", "random-" + randomVserverId)
+ .property("vserver-name", "junit-vservers").property("source-of-truth", "JUNIT")
+ .next();
}
- } catch(Exception ex){
+ } catch (Exception ex) {
success = false;
logger.error("Unable to add all of the vservers due to {}", ex);
} finally {
- if(success){
+ if (success) {
transaction.commit();
} else {
transaction.rollback();
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/QueryConsumerTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/QueryConsumerTest.java
index 2570690..cfb81d4 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/QueryConsumerTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/QueryConsumerTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,19 @@
*/
package org.onap.aai.rest;
+import static org.hamcrest.core.Is.is;
+import static org.hamcrest.core.StringContains.containsString;
+import static org.junit.Assert.*;
+
+import java.io.UnsupportedEncodingException;
+import java.util.Base64;
+import java.util.Collections;
+import java.util.HashMap;
+import java.util.Map;
+import java.util.UUID;
+
+import javax.ws.rs.core.Response;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.janusgraph.core.JanusGraphTransaction;
import org.junit.After;
@@ -32,9 +45,11 @@ import org.onap.aai.TraversalTestConfiguration;
import org.onap.aai.config.PropertyPasswordConfiguration;
import org.onap.aai.dbmap.AAIGraph;
import org.onap.aai.exceptions.AAIException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
-import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.annotation.Import;
import org.springframework.http.*;
import org.springframework.test.context.ContextConfiguration;
@@ -42,171 +57,160 @@ import org.springframework.test.context.TestPropertySource;
import org.springframework.test.context.junit4.SpringRunner;
import org.springframework.web.client.RestTemplate;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-
-import java.io.UnsupportedEncodingException;
-import java.util.Base64;
-import java.util.Collections;
-import java.util.HashMap;
-import java.util.Map;
-import java.util.UUID;
-
-import javax.ws.rs.core.Response;
-
-import static org.hamcrest.core.Is.is;
-import static org.hamcrest.core.StringContains.containsString;
-import static org.junit.Assert.*;
-
@RunWith(SpringRunner.class)
-@SpringBootTest(webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT, classes = TraversalApp.class)
+@SpringBootTest(
+ webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+ classes = TraversalApp.class)
@TestPropertySource(locations = "classpath:application-test.properties")
@ContextConfiguration(initializers = PropertyPasswordConfiguration.class)
@Import(TraversalTestConfiguration.class)
public class QueryConsumerTest {
- private static final Logger LOGGER = LoggerFactory.getLogger(QueryConsumerTest.class);
- private HttpTestUtil httpTestUtil;
-
- private String pserverUri;
-
- @Autowired
- RestTemplate restTemplate;
-
- @LocalServerPort
- int randomPort;
-
- private HttpEntity httpEntity;
-
- private HttpHeaders headers;
-
- private String baseUrl;
-
- private String cloudRegionUri;
-
- @Before
- public void setup() throws Exception {
-
- 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);
- baseUrl = "http://localhost:" + randomPort;
- httpTestUtil = new HttpTestUtil();
- addPserver();
-
- }
-
- private void addPserver() throws Exception, UnsupportedEncodingException, AAIException {
- String hostname = "test-" + UUID.randomUUID().toString();
- pserverUri = "/aai/v11/cloud-infrastructure/pservers/pserver/" + hostname;
- Map<String, String> pserverMap = new HashMap<>();
- pserverMap.put("hostname", hostname);
- String payload = PayloadUtil.getTemplatePayload("pserver.json", pserverMap);
- httpTestUtil.doPut(pserverUri, payload);
- }
-
- private void addCloudRegion(Map<String, String> cloudRegionMap, String cloudRegionUri)
- throws Exception, UnsupportedEncodingException, AAIException {
- String cloudRegionPayload = PayloadUtil.getTemplatePayload("cloud-region-with-vserver.json", cloudRegionMap);
- Response response = httpTestUtil.doPut(cloudRegionUri, cloudRegionPayload);
- }
-
- private void addComplex(Map<String, String> complexMap, String complexUri)
- throws Exception, UnsupportedEncodingException, AAIException {
- String complexPayload = PayloadUtil.getTemplatePayload("complex.json", complexMap);
- Response response = httpTestUtil.doPut(complexUri, complexPayload);
- }
-
-// @Test
- public void testRequiredAGood() throws Exception {
- String endpoint = "/aai/v14/query?format=pathed";
- Map<String, String> cloudRegionMap = new HashMap<>();
- cloudRegionMap.put("cloud-owner", "test-owner-id1111");
- cloudRegionMap.put("cloud-region-id", "test-region-id1111");
- cloudRegionMap.put("tenant-id", "test-tenant-id1111");
- cloudRegionMap.put("tenant-name", "test-tenant-name-id1111");
- cloudRegionMap.put("vserver-id", "some-vserver-id-id1111");
- cloudRegionMap.put("vserver-name", "test-vserver-name-id1111");
- cloudRegionMap.put("pserver-uri", pserverUri);
- cloudRegionUri = "/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/test-owner-id1111/test-region-id1111";
- addCloudRegion(cloudRegionMap, cloudRegionUri);
-
- Map<String, String> complexMap = new HashMap<>();
- complexMap.put("physical-location-id", "location-1111");
- complexMap.put("cloud-region-uri", cloudRegionUri);
- String complexUri = "/aai/v14/cloud-infrastructure/complexes/complex/location-1111";
- addComplex(complexMap, complexUri);
-
- Map<String, String> customQueryMap = new HashMap<>();
-
- customQueryMap.put("start", "cloud-infrastructure/cloud-regions");
- customQueryMap.put("query", "cloud-region-sites?owner=test-owner-id1111");
-
- String payload = PayloadUtil.getTemplatePayload("custom-query.json", customQueryMap);
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity,
- String.class);
- LOGGER.info("Response of custom query : {}", responseEntity.getBody().toString());
- assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));
-
- // assertThat(responseEntity.getBody().toString(),
- // containsString(customerUri2));
- }
-
- @Test
- public void testRequiredBad() throws Exception {
- String endpoint = "/aai/v14/query?format=pathed";
- Map<String, String> cloudRegionMap = new HashMap<>();
- cloudRegionMap.put("cloud-owner", "test-owner-id2222");
- cloudRegionMap.put("cloud-region-id", "test-region-id2222");
- cloudRegionMap.put("tenant-id", "test-tenant-id2222");
- cloudRegionMap.put("tenant-name", "test-tenant-name-id2222");
- cloudRegionMap.put("vserver-id", "some-vserver-id-id2222");
- cloudRegionMap.put("vserver-name", "test-vserver-name-id2222");
- cloudRegionMap.put("pserver-uri", pserverUri);
- cloudRegionUri = "/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/test-owner-id2222/test-region-id2222";
- addCloudRegion(cloudRegionMap, cloudRegionUri);
-
- Map<String, String> customQueryMap = new HashMap<>();
-
- customQueryMap.put("start", "cloud-infrastructure/cloud-regions");
- customQueryMap.put("query", "cloud-region-sites?owner=test-owner-id2222&extra=extraParam");
-
- String payload = PayloadUtil.getTemplatePayload("custom-query.json", customQueryMap);
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity,
- String.class);
- LOGGER.info("Response of custom query : {}", responseEntity.getBody().toString());
- assertThat(responseEntity.getStatusCode(), is(HttpStatus.BAD_REQUEST));
-
- assertThat(responseEntity.getBody().toString(), containsString("3022"));
- }
-
- @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");
- }
- }
- }
+ private static final Logger LOGGER = LoggerFactory.getLogger(QueryConsumerTest.class);
+ private HttpTestUtil httpTestUtil;
+
+ private String pserverUri;
+
+ @Autowired
+ RestTemplate restTemplate;
+
+ @LocalServerPort
+ int randomPort;
+
+ private HttpEntity httpEntity;
+
+ private HttpHeaders headers;
+
+ private String baseUrl;
+
+ private String cloudRegionUri;
+
+ @Before
+ public void setup() throws Exception {
+
+ 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);
+ baseUrl = "http://localhost:" + randomPort;
+ httpTestUtil = new HttpTestUtil();
+ addPserver();
+
+ }
+
+ private void addPserver() throws Exception, UnsupportedEncodingException, AAIException {
+ String hostname = "test-" + UUID.randomUUID().toString();
+ pserverUri = "/aai/v11/cloud-infrastructure/pservers/pserver/" + hostname;
+ Map<String, String> pserverMap = new HashMap<>();
+ pserverMap.put("hostname", hostname);
+ String payload = PayloadUtil.getTemplatePayload("pserver.json", pserverMap);
+ httpTestUtil.doPut(pserverUri, payload);
+ }
+
+ private void addCloudRegion(Map<String, String> cloudRegionMap, String cloudRegionUri)
+ throws Exception, UnsupportedEncodingException, AAIException {
+ String cloudRegionPayload =
+ PayloadUtil.getTemplatePayload("cloud-region-with-vserver.json", cloudRegionMap);
+ Response response = httpTestUtil.doPut(cloudRegionUri, cloudRegionPayload);
+ }
+
+ private void addComplex(Map<String, String> complexMap, String complexUri)
+ throws Exception, UnsupportedEncodingException, AAIException {
+ String complexPayload = PayloadUtil.getTemplatePayload("complex.json", complexMap);
+ Response response = httpTestUtil.doPut(complexUri, complexPayload);
+ }
+
+ // @Test
+ public void testRequiredAGood() throws Exception {
+ String endpoint = "/aai/v14/query?format=pathed";
+ Map<String, String> cloudRegionMap = new HashMap<>();
+ cloudRegionMap.put("cloud-owner", "test-owner-id1111");
+ cloudRegionMap.put("cloud-region-id", "test-region-id1111");
+ cloudRegionMap.put("tenant-id", "test-tenant-id1111");
+ cloudRegionMap.put("tenant-name", "test-tenant-name-id1111");
+ cloudRegionMap.put("vserver-id", "some-vserver-id-id1111");
+ cloudRegionMap.put("vserver-name", "test-vserver-name-id1111");
+ cloudRegionMap.put("pserver-uri", pserverUri);
+ cloudRegionUri =
+ "/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/test-owner-id1111/test-region-id1111";
+ addCloudRegion(cloudRegionMap, cloudRegionUri);
+
+ Map<String, String> complexMap = new HashMap<>();
+ complexMap.put("physical-location-id", "location-1111");
+ complexMap.put("cloud-region-uri", cloudRegionUri);
+ String complexUri = "/aai/v14/cloud-infrastructure/complexes/complex/location-1111";
+ addComplex(complexMap, complexUri);
+
+ Map<String, String> customQueryMap = new HashMap<>();
+
+ customQueryMap.put("start", "cloud-infrastructure/cloud-regions");
+ customQueryMap.put("query", "cloud-region-sites?owner=test-owner-id1111");
+
+ String payload = PayloadUtil.getTemplatePayload("custom-query.json", customQueryMap);
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ LOGGER.info("Response of custom query : {}", responseEntity.getBody().toString());
+ assertThat(responseEntity.getStatusCode(), is(HttpStatus.OK));
+
+ // assertThat(responseEntity.getBody().toString(),
+ // containsString(customerUri2));
+ }
+
+ @Test
+ public void testRequiredBad() throws Exception {
+ String endpoint = "/aai/v14/query?format=pathed";
+ Map<String, String> cloudRegionMap = new HashMap<>();
+ cloudRegionMap.put("cloud-owner", "test-owner-id2222");
+ cloudRegionMap.put("cloud-region-id", "test-region-id2222");
+ cloudRegionMap.put("tenant-id", "test-tenant-id2222");
+ cloudRegionMap.put("tenant-name", "test-tenant-name-id2222");
+ cloudRegionMap.put("vserver-id", "some-vserver-id-id2222");
+ cloudRegionMap.put("vserver-name", "test-vserver-name-id2222");
+ cloudRegionMap.put("pserver-uri", pserverUri);
+ cloudRegionUri =
+ "/aai/v14/cloud-infrastructure/cloud-regions/cloud-region/test-owner-id2222/test-region-id2222";
+ addCloudRegion(cloudRegionMap, cloudRegionUri);
+
+ Map<String, String> customQueryMap = new HashMap<>();
+
+ customQueryMap.put("start", "cloud-infrastructure/cloud-regions");
+ customQueryMap.put("query", "cloud-region-sites?owner=test-owner-id2222&extra=extraParam");
+
+ String payload = PayloadUtil.getTemplatePayload("custom-query.json", customQueryMap);
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ LOGGER.info("Response of custom query : {}", responseEntity.getBody().toString());
+ assertThat(responseEntity.getStatusCode(), is(HttpStatus.BAD_REQUEST));
+
+ assertThat(responseEntity.getBody().toString(), containsString("3022"));
+ }
+
+ @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-traversal/src/test/java/org/onap/aai/rest/RecentApiTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/RecentApiTest.java
index 10ff7b9..d9d1809 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/RecentApiTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/RecentApiTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,144 +19,165 @@
*/
package org.onap.aai.rest;
+import static org.junit.Assert.*;
+
+import com.att.eelf.configuration.EELFManager;
+
+import java.util.Collections;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.janusgraph.core.JanusGraphTransaction;
import org.junit.Test;
import org.onap.aai.dbmap.AAIGraph;
-import org.springframework.http.*;
-import org.springframework.web.util.UriComponentsBuilder;
-
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import com.att.eelf.configuration.EELFManager;
-
-import java.util.Collections;
-
-import static org.junit.Assert.*;
+import org.springframework.http.*;
+import org.springframework.web.util.UriComponentsBuilder;
public class RecentApiTest extends AbstractSpringRestTest {
- private static final Logger LOGGER = LoggerFactory.getLogger(RecentApiTest.class);
-
- @Override
- public void createTestGraph() {
- JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
- boolean success = true;
- try {
- GraphTraversalSource g = transaction.traversal();
- g.addV().property("aai-node-type", "pserver").property("hostname", "test-pserver-recents")
- .property("in-maint", false).property("source-of-truth", "JUNIT")
- .property("aai-uri", "/cloud-infrastructure/pservers/pserver/test-pserver-recents").next();
- } catch (Exception ex) {
- success = false;
- } finally {
- if (success) {
- transaction.commit();
- } else {
- transaction.rollback();
- fail("Unable to setup the graph");
- }
- }
- }
-
- @Test
- public void testRecentsQuery() {
-
- String endpoint = "/aai/recents/v14/pserver";
- httpEntity = new HttpEntity(headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl + endpoint).queryParam("hours", "190");
- ResponseEntity responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity,
- String.class);
- LOGGER.debug("Response for GET request with uri {} : {}", builder.toUriString(), responseEntity.getBody());
- assertNotNull("Response from /aai/recents/v14/pserver is not null", responseEntity);
- assertEquals("Expected the response to be 200", HttpStatus.OK, responseEntity.getStatusCode());
-
- // Check different application xml headers for accept
- headers.set("Accept", "application/xml");
- httpEntity = new HttpEntity(headers);
-
- responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity,
- String.class);
- LOGGER.debug("Response for GET request with uri {} : {}", builder.toUriString(), responseEntity.getBody());
- assertNotNull("Response from /aai/recents/v14/pserver is not null", responseEntity);
- assertEquals("Expected the response to be 200", HttpStatus.OK, responseEntity.getStatusCode());
-
- headers.set("Accept", "application/xml; charset=UTF-8");
- httpEntity = new HttpEntity(headers);
-
- responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity,
- String.class);
- LOGGER.debug("Response for GET request with uri {} : {}", builder.toUriString(), responseEntity.getBody());
- assertNotNull("Response from /aai/recents/v14/pserver is not null", responseEntity);
- assertEquals("Expected the response to be 200", HttpStatus.OK, responseEntity.getStatusCode());
- }
-
- @Test
- public void testRecentsHoursWrongNumber() {
- String endpoint = "/aai/recents/v14/pserver";
- httpEntity = new HttpEntity(headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl + endpoint).queryParam("hours", "1900000000000000000000000000000000000000000000000");
- ResponseEntity responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity,
- String.class);
-
- LOGGER.debug("Response for PUT request with uri {} : {}", builder.toUriString(), responseEntity.getBody());
- assertNotNull("Response from /aai/recents/v14/pserver is null", responseEntity);
- assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
- }
-
- @Test
- public void testRecentsStartTimeWrongNumber() {
- String endpoint = "/aai/recents/v14/pserver";
- httpEntity = new HttpEntity(headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl + endpoint).queryParam("date-time", "190000000000000000000000000000000000000000000");
- ResponseEntity responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity,
- String.class);
-
- LOGGER.debug("Response for PUT request with uri {} : {}", builder.toUriString(), responseEntity.getBody());
- assertNotNull("Response from /aai/recents/v14/pserver is null", responseEntity);
- assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
- }
-
- @Test
- public void testRecentsQueryException() {
- String endpoint = "/aai/recents/v14/xserver";
- httpEntity = new HttpEntity(headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl + endpoint).queryParam("hours", "190");
- ResponseEntity responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity,
- String.class);
-
- LOGGER.debug("Response for PUT request with uri {} : {}", builder.toUriString(), responseEntity.getBody());
- assertNotNull("Response from /aai/recents/v14/pserver is null", responseEntity);
- assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
- }
-
- @Test
- public void testRecentsQueryExceptionHours() {
- String endpoint = "/aai/recents/v14/pserver";
- httpEntity = new HttpEntity(headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl + endpoint).queryParam("hours", "200");
-
- ResponseEntity responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity,
- String.class);
- LOGGER.debug("Response for PUT request with uri {} : {}", builder.toUriString(), responseEntity.getBody());
- assertNotNull("Response from /aai/recents/v14/pserver is null", responseEntity);
- assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST,
- responseEntity.getStatusCode());
-
- }
-
- @Test
- public void testRecentsQueryExceptionDateTime() {
- String endpoint = "/aai/recents/v14/pserver";
- httpEntity = new HttpEntity(headers);
- UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl + endpoint).queryParam("date-time",
- "200");
-
- ResponseEntity responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity,
- String.class);
- LOGGER.debug("Response for PUT request with uri {} : {}", builder.toUriString(), responseEntity.getBody());
- assertNotNull("Response from /aai/recents/v14/pserver is null", responseEntity);
- assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST,
- responseEntity.getStatusCode());
- }
+ private static final Logger LOGGER = LoggerFactory.getLogger(RecentApiTest.class);
+
+ @Override
+ public void createTestGraph() {
+ JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
+ boolean success = true;
+ try {
+ GraphTraversalSource g = transaction.traversal();
+ g.addV().property("aai-node-type", "pserver")
+ .property("hostname", "test-pserver-recents").property("in-maint", false)
+ .property("source-of-truth", "JUNIT")
+ .property("aai-uri", "/cloud-infrastructure/pservers/pserver/test-pserver-recents")
+ .next();
+ } catch (Exception ex) {
+ success = false;
+ } finally {
+ if (success) {
+ transaction.commit();
+ } else {
+ transaction.rollback();
+ fail("Unable to setup the graph");
+ }
+ }
+ }
+
+ @Test
+ public void testRecentsQuery() {
+
+ String endpoint = "/aai/recents/v14/pserver";
+ httpEntity = new HttpEntity(headers);
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(baseUrl + endpoint).queryParam("hours", "190");
+ ResponseEntity responseEntity =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
+ LOGGER.debug("Response for GET request with uri {} : {}", builder.toUriString(),
+ responseEntity.getBody());
+ assertNotNull("Response from /aai/recents/v14/pserver is not null", responseEntity);
+ assertEquals("Expected the response to be 200", HttpStatus.OK,
+ responseEntity.getStatusCode());
+
+ // Check different application xml headers for accept
+ headers.set("Accept", "application/xml");
+ httpEntity = new HttpEntity(headers);
+
+ responseEntity =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
+ LOGGER.debug("Response for GET request with uri {} : {}", builder.toUriString(),
+ responseEntity.getBody());
+ assertNotNull("Response from /aai/recents/v14/pserver is not null", responseEntity);
+ assertEquals("Expected the response to be 200", HttpStatus.OK,
+ responseEntity.getStatusCode());
+
+ headers.set("Accept", "application/xml; charset=UTF-8");
+ httpEntity = new HttpEntity(headers);
+
+ responseEntity =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
+ LOGGER.debug("Response for GET request with uri {} : {}", builder.toUriString(),
+ responseEntity.getBody());
+ assertNotNull("Response from /aai/recents/v14/pserver is not null", responseEntity);
+ assertEquals("Expected the response to be 200", HttpStatus.OK,
+ responseEntity.getStatusCode());
+ }
+
+ @Test
+ public void testRecentsHoursWrongNumber() {
+ String endpoint = "/aai/recents/v14/pserver";
+ httpEntity = new HttpEntity(headers);
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl + endpoint)
+ .queryParam("hours", "1900000000000000000000000000000000000000000000000");
+ ResponseEntity responseEntity =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
+
+ LOGGER.debug("Response for PUT request with uri {} : {}", builder.toUriString(),
+ responseEntity.getBody());
+ assertNotNull("Response from /aai/recents/v14/pserver is null", responseEntity);
+ assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST,
+ responseEntity.getStatusCode());
+ }
+
+ @Test
+ public void testRecentsStartTimeWrongNumber() {
+ String endpoint = "/aai/recents/v14/pserver";
+ httpEntity = new HttpEntity(headers);
+ UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl + endpoint)
+ .queryParam("date-time", "190000000000000000000000000000000000000000000");
+ ResponseEntity responseEntity =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
+
+ LOGGER.debug("Response for PUT request with uri {} : {}", builder.toUriString(),
+ responseEntity.getBody());
+ assertNotNull("Response from /aai/recents/v14/pserver is null", responseEntity);
+ assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST,
+ responseEntity.getStatusCode());
+ }
+
+ @Test
+ public void testRecentsQueryException() {
+ String endpoint = "/aai/recents/v14/xserver";
+ httpEntity = new HttpEntity(headers);
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(baseUrl + endpoint).queryParam("hours", "190");
+ ResponseEntity responseEntity =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
+
+ LOGGER.debug("Response for PUT request with uri {} : {}", builder.toUriString(),
+ responseEntity.getBody());
+ assertNotNull("Response from /aai/recents/v14/pserver is null", responseEntity);
+ assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST,
+ responseEntity.getStatusCode());
+ }
+
+ @Test
+ public void testRecentsQueryExceptionHours() {
+ String endpoint = "/aai/recents/v14/pserver";
+ httpEntity = new HttpEntity(headers);
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(baseUrl + endpoint).queryParam("hours", "200");
+
+ ResponseEntity responseEntity =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
+ LOGGER.debug("Response for PUT request with uri {} : {}", builder.toUriString(),
+ responseEntity.getBody());
+ assertNotNull("Response from /aai/recents/v14/pserver is null", responseEntity);
+ assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST,
+ responseEntity.getStatusCode());
+
+ }
+
+ @Test
+ public void testRecentsQueryExceptionDateTime() {
+ String endpoint = "/aai/recents/v14/pserver";
+ httpEntity = new HttpEntity(headers);
+ UriComponentsBuilder builder =
+ UriComponentsBuilder.fromHttpUrl(baseUrl + endpoint).queryParam("date-time", "200");
+
+ ResponseEntity responseEntity =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
+ LOGGER.debug("Response for PUT request with uri {} : {}", builder.toUriString(),
+ responseEntity.getBody());
+ assertNotNull("Response from /aai/recents/v14/pserver is null", responseEntity);
+ assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST,
+ responseEntity.getStatusCode());
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/SearchProviderRestTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/SearchProviderRestTest.java
index 6980753..c36ef6b 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/SearchProviderRestTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/SearchProviderRestTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,20 +19,21 @@
*/
package org.onap.aai.rest;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import com.att.eelf.configuration.EELFManager;
-import org.junit.Test;
-import org.springframework.http.*;
-import org.springframework.web.util.UriComponentsBuilder;
-
-import java.util.Collections;
-
import static org.hamcrest.CoreMatchers.containsString;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
+import com.att.eelf.configuration.EELFManager;
+
+import java.util.Collections;
+
+import org.junit.Test;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+import org.springframework.http.*;
+import org.springframework.web.util.UriComponentsBuilder;
+
public class SearchProviderRestTest extends AbstractSpringRestTest {
private static final Logger LOGGER = LoggerFactory.getLogger(SearchProviderRestTest.class);
@@ -45,15 +46,18 @@ public class SearchProviderRestTest extends AbstractSpringRestTest {
httpEntity = new HttpEntity(headers);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl + endpoint)
- .queryParam("key", "cloud-region.cloud-owner:test-aic")
- .queryParam("include", "cloud-region");
+ .queryParam("key", "cloud-region.cloud-owner:test-aic")
+ .queryParam("include", "cloud-region");
- ResponseEntity responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
- LOGGER.debug("Response for GET request with uri {} : {}", builder.toUriString(), responseEntity.getBody());
+ LOGGER.debug("Response for GET request with uri {} : {}", builder.toUriString(),
+ responseEntity.getBody());
assertNotNull("Response from /aai/latest/search is null", responseEntity);
- assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
+ assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST,
+ responseEntity.getStatusCode());
}
@Test
@@ -64,19 +68,22 @@ public class SearchProviderRestTest extends AbstractSpringRestTest {
httpEntity = new HttpEntity(headers);
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl + endpoint)
- .queryParam("key", "cloud-region.cloud-owner:test-aic")
- .queryParam("include", "cloud-region");
+ .queryParam("key", "cloud-region.cloud-owner:test-aic")
+ .queryParam("include", "cloud-region");
- ResponseEntity responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
- LOGGER.debug("Response for GET request with uri {} : {}", builder.toUriString(), responseEntity.getBody());
+ LOGGER.debug("Response for GET request with uri {} : {}", builder.toUriString(),
+ responseEntity.getBody());
assertNotNull("Response from /aai/latest/search is null", responseEntity);
- assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
+ assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST,
+ responseEntity.getStatusCode());
}
@Test
- public void testGenericQueryBypassTimeout(){
+ public void testGenericQueryBypassTimeout() {
headers = new HttpHeaders();
headers.setAccept(Collections.singletonList(MediaType.APPLICATION_JSON));
@@ -88,16 +95,18 @@ public class SearchProviderRestTest extends AbstractSpringRestTest {
String endpoint = "/aai/latest/search/generic-query";
UriComponentsBuilder builder = UriComponentsBuilder.fromHttpUrl(baseUrl + endpoint)
- .queryParam("key", "cloud-region.cloud-owner:test-aic")
- .queryParam("include", "cloud-region")
- .queryParam("start-node-type", "cloud-region");
+ .queryParam("key", "cloud-region.cloud-owner:test-aic")
+ .queryParam("include", "cloud-region").queryParam("start-node-type", "cloud-region");
- ResponseEntity responseEntity = restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(builder.toUriString(), HttpMethod.GET, httpEntity, String.class);
- LOGGER.debug("Response for GET request with uri {} : {}", builder.toUriString(), responseEntity.getBody());
+ LOGGER.debug("Response for GET request with uri {} : {}", builder.toUriString(),
+ responseEntity.getBody());
assertNotNull("Response from /aai/latest/search is null", responseEntity);
- assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST, responseEntity.getStatusCode());
+ assertEquals("Expected the response to be 400", HttpStatus.BAD_REQUEST,
+ responseEntity.getStatusCode());
assertThat(responseEntity.getBody().toString(), containsString("4009"));
}
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslContextTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslContextTest.java
index e85e250..9c89964 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslContextTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslContextTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -18,17 +18,17 @@
* ============LICENSE_END=========================================================
*/
-package org.onap.aai.rest.dsl;
+package org.onap.aai.rest.dsl;
-import org.antlr.v4.runtime.ParserRuleContext;
-import org.junit.Assert;
-import org.junit.Before;
-import org.junit.Test;
+import static org.junit.Assert.*;
import java.util.Deque;
import java.util.List;
-import static org.junit.Assert.*;
+import org.antlr.v4.runtime.ParserRuleContext;
+import org.junit.Assert;
+import org.junit.Before;
+import org.junit.Test;
public class DslContextTest {
DslContext dslContext;
@@ -36,7 +36,7 @@ public class DslContextTest {
@Before
public void setUp() {
- dslContext= new DslContext();
+ dslContext = new DslContext();
dslContext.setCtx(null);
}
@@ -135,15 +135,13 @@ public class DslContextTest {
}
@Test
- public void testSetValidationFlag()
- {
+ public void testSetValidationFlag() {
dslContext.setValidationFlag(true);
Assert.assertTrue(dslContext.isValidationFlag());
}
@Test
- public void testUnionStartNodes()
- {
+ public void testUnionStartNodes() {
dslContext.setUnionStartNodes(null);
assertNull(dslContext.getUnionStartNodes());
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslQueryBuilderTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslQueryBuilderTest.java
index fe75d80..159485f 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslQueryBuilderTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslQueryBuilderTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -24,35 +24,30 @@ import static org.junit.Assert.assertSame;
import java.util.HashSet;
-import org.onap.aai.introspection.Loader;
import org.junit.Before;
import org.junit.Test;
import org.onap.aai.edges.EdgeIngestor;
-
-
+import org.onap.aai.introspection.Loader;
public class DslQueryBuilderTest {
DslQueryBuilder dslQueryBuilder;
-
+
@Before
- public void setUp()
- {
- EdgeIngestor edgeIngestor= new EdgeIngestor(new HashSet<>());
- dslQueryBuilder= new DslQueryBuilder(edgeIngestor, null);
+ public void setUp() {
+ EdgeIngestor edgeIngestor = new EdgeIngestor(new HashSet<>());
+ dslQueryBuilder = new DslQueryBuilder(edgeIngestor, null);
}
-
+
@Test
- public void testQuery()
- {
- StringBuilder query= new StringBuilder();
+ public void testQuery() {
+ StringBuilder query = new StringBuilder();
dslQueryBuilder.setQuery(query);
assertSame(query, dslQueryBuilder.getQuery());
}
-
+
@Test
- public void testQueryException()
- {
- StringBuilder queryException= new StringBuilder();
+ public void testQueryException() {
+ StringBuilder queryException = new StringBuilder();
dslQueryBuilder.setQueryException(queryException);
assertSame(queryException, dslQueryBuilder.getQueryException());
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslQueryProcessorV1Test.java b/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslQueryProcessorV1Test.java
index aa3e297..8d90b5e 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslQueryProcessorV1Test.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslQueryProcessorV1Test.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,582 +19,682 @@
*/
package org.onap.aai.rest.dsl;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertTrue;
+
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+
+import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
-import org.junit.Ignore;
import org.junit.rules.ExpectedException;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.rest.enums.QueryVersion;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertTrue;
-
/**
* The Class DslMain.
*/
public class DslQueryProcessorV1Test extends AAISetup {
- @Rule
- public ExpectedException expectedEx = ExpectedException.none();
-
- @Test
- public void dbAliasTest() throws AAIException {
- String aaiQuery = "logical-link* ('model-invariant-id','invid')";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'logical-link').getVerticesByProperty('model-invariant-id-local','invid')"
- + ".store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void apostropheTest() throws AAIException {
- String aaiQuery = "logical-link*('link-id','dsl\\'link')";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'logical-link').getVerticesByProperty('link-id','dsl\\'link')"
- + ".store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void parseCancellationExceptionTest() throws AAIException {
- boolean thrown = false;
- String aaiQuery = "logical-link*('link-id','dsl\\'link)";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'logical-link').getVerticesByProperty('link-id','dsl\\'link')"
- + ".store('x').cap('x').unfold().dedup()";
-
- try {
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
- } catch (AAIException e) {
- thrown = true;
- }
- assertTrue(thrown);
- }
-
- @Test
- public void cloudRegionFromVnf() throws AAIException {
- String aaiQuery = "generic-vnf*('vnf-name','xyz') > [ vnfc* > vserver* > [pserver*, tenant* > cloud-region*], "+
- "vserver* > [pserver*, tenant* > cloud-region*] ]";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-name','xyz').store('x').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vnfc').store('x')."
- +"createEdgeTraversal(EdgeType.COUSIN, 'vnfc','vserver').store('x').union(builder.newInstance().createEdgeTraversal"
- +"(EdgeType.COUSIN, 'vserver','pserver').store('x'),builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'vserver','tenant')"
- +".store('x').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region').store('x')),builder.newInstance().createEdgeTraversal"
- +"(EdgeType.COUSIN, 'generic-vnf','vserver').store('x').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vserver'"
- +",'pserver').store('x'),builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').store('x').createEdgeTraversal"
- +"(EdgeType.TREE, 'tenant','cloud-region').store('x'))).cap('x').unfold().dedup()";
-
-
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void cloudRegionSites() throws AAIException {
- String aaiQuery = "cloud-region*('cloud-owner','xyz') > complex*";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner'"
- +",'xyz').store('x').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','complex').store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void pserverWithNoComplexTest() throws AAIException {
- String aaiQuery = "pserver*('hostname','xyz')!(> complex)";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('hostname','xyz').where(builder.newInstance().not("
- +"builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex'))).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void pserverWhereNotTest() throws AAIException {
- String aaiQuery = "pserver('hostname','xyz')>vserver*!(> vnfc > configuration))";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('hostname','xyz').createEdgeTraversal" +
- "(EdgeType.COUSIN, 'pserver','vserver').where(builder.newInstance().not(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN,"+
- " 'vserver','vnfc').createEdgeTraversal(EdgeType.COUSIN, 'vnfc','configuration'))).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void singleNode1() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner','coid')";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
- + ".store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void singleNodeLimit() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner','coid') LIMIT 10";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
- + ".store('x').cap('x').unfold().dedup().limit(10)";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void specialCharacterTest() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner','coidhello:?_-)(!@#$%^&*+={}[]|/.<,') LIMIT 10";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coidhello:?_-)(!@#$%^&*+={}[]|/.<,')"
- + ".store('x').cap('x').unfold().dedup().limit(10)";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void singleNodeLimitBlah() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner','coid') LIMIT blah";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
- + ".getVerticesByProperty('cloud-region-id','cr id').store('x').cap('x').unfold().dedup().limit(10)";
-
- expectedEx.expect(org.onap.aai.exceptions.AAIException.class);
- expectedEx.expectMessage("DSL Syntax Error while processing the query");
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- }
-
- @Test
- public void singleNodeLimitNull() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner','coid') LIMIT ";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
- + ".getVerticesByProperty('cloud-region-id','cr id').store('x').cap('x').unfold().dedup().limit(10)";
-
- expectedEx.expect(org.onap.aai.exceptions.AAIException.class);
- expectedEx.expectMessage("DSL Syntax Error while processing the query");
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- }
-
- @Test
- public void cloudRegion1Test() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner','coid')('cloud-region-id','cr id') LIMIT 10";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
- + ".getVerticesByProperty('cloud-region-id','cr id').store('x').cap('x').unfold().dedup().limit(10)";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void cloudRegion_entitlementTest() throws AAIException {
-
- /*
- A store within a where makes no sense
- */
- String aaiQuery = "generic-vnf('vnf-id','vnfId') ( > vserver > tenant > cloud-region('cloud-region-id','One')) > entitlement*";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where("
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region')"
- + ".getVerticesByProperty('cloud-region-id','One'))"
- + ".createEdgeTraversal(EdgeType.TREE, 'generic-vnf','entitlement').store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void cloudRegion_entitlementTestWithLabels() throws AAIException {
-
- String aaiQuery = "generic-vnf('vnf-id','vnfId') (> ('tosca.relationships.HostedOn') vserver > ('org.onap.relationships.inventory.BelongsTo') tenant > ('org.onap.relationships.inventory.BelongsTo') cloud-region('cloud-region-id','One')) > ('org.onap.relationships.inventory.ComposedOf')service-instance*";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where("
- + "builder.newInstance().createEdgeTraversalWithLabels( 'generic-vnf','vserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).createEdgeTraversalWithLabels( 'vserver','tenant', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo'))).createEdgeTraversalWithLabels( 'tenant','cloud-region', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo')))"
- + ".getVerticesByProperty('cloud-region-id','One'))"
- + ".createEdgeTraversalWithLabels( 'generic-vnf','service-instance', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.ComposedOf'))).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void complex_az_fromComplexTest() throws AAIException {
-
- String aaiQuery = "cloud-region('cloud-owner','coid')('cloud-region-id','crid') > [ availability-zone* , complex*]";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region')"
- + ".getVerticesByProperty('cloud-owner','coid').getVerticesByProperty('cloud-region-id','crid')"
- + ".union(builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'cloud-region','availability-zone').store('x')"
- + ",builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','complex').store('x')).cap('x').unfold().dedup()";
-
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void complex_az_fromComplexTestWithLabels() throws AAIException {
-
- String aaiQuery = "cloud-region('cloud-owner','coid')('cloud-region-id','crid') > [ ('org.onap.relationships.inventory.BelongsTo')availability-zone* , ('org.onap.relationships.inventory.LocatedIn')complex*]";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region')"
- + ".getVerticesByProperty('cloud-owner','coid').getVerticesByProperty('cloud-region-id','crid')"
- + ".union(builder.newInstance().createEdgeTraversalWithLabels( 'cloud-region','availability-zone', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo'))).store('x')"
- + ",builder.newInstance().createEdgeTraversalWithLabels( 'cloud-region','complex', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.LocatedIn'))).store('x')).cap('x').unfold().dedup()";
-
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void cloudRegion_fromComplex1Test() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'complex').getVerticesByProperty('data-center-code','data-center-code-name')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').store('x').cap('x').unfold().dedup()";
- String aaiQuery = "complex('data-center-code','data-center-code-name') > cloud-region*";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void cloudRegion_fromComplex2Test() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'complex').getVerticesByProperty('data-center-code','data-center-code-name')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').getVerticesByProperty('cloud-region-version','crv')"
- + ".store('x').cap('x').unfold().dedup()";
- String aaiQuery = "complex('data-center-code','data-center-code-name') > cloud-region*('cloud-region-version','crv')";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void cloudRegion_fromNfTypeTest() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'image').getVerticesByProperty('application-vendor','F5')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'image','vserver')"
- + ".where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vserver','generic-vnf').getVerticesByProperty('vnf-name','ZALL1MMSC03'))"
- + ".createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region')"
- + ".store('x').cap('x').unfold().dedup()";
-
- String aaiQuery = "image('application-vendor','F5') > vserver (> generic-vnf('vnf-name','ZALL1MMSC03')) > tenant > cloud-region*";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void cloudRegion_fromNfTypeVendorVersionTest() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'image').getVerticesByProperty('application-vendor','vendor')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'image','vserver').where("
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vserver','generic-vnf').getVerticesByProperty('nf-type','nfType')"
- + ").createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region')"
- + ".store('x').cap('x').unfold().dedup()";
-
- String aaiQuery = "image('application-vendor','vendor') > vserver(> generic-vnf('nf-type', 'nfType') ) > tenant > cloud-region*";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void cloud_region_fromVnfTest() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vnfc').store('x')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'vnfc','vserver').store('x')"
- + ".createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').store('x')"
- + ".createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region').store('x')"
- + ".cap('x').unfold().dedup()";
-
- String aaiQuery = "generic-vnf('vnf-id','vnfId') > vnfc* > vserver* > tenant* > cloud-region*";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void cloud_region_sitesTest() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region')."
- + "getVerticesByProperty('cloud-owner','co').store('x').createEdgeTraversal(EdgeType.COUSIN, "
- + "'cloud-region','complex').store('x').cap('x').unfold().dedup()";
-
- String aaiQuery = "cloud-region*('cloud-owner','co') > complex*";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void complex_fromVnf2Test() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').store('x').union("
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').store('x')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x')"
- + ").cap('x').unfold().dedup()";
-
- String aaiQuery = "generic-vnf*('vnf-id','vnfId') > [ pserver* > complex*, "
- + " vserver > pserver* > complex* " + "]";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void complex_fromVnfTest2() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').store('x').union("
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').store('x'))"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x')"
- + ".cap('x').unfold().dedup()";
-
- String aaiQuery = "generic-vnf*('vnf-id','vnfId') > [ pserver* , "
- + " vserver > pserver* ] > complex*";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void fn_topology1Test() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'customer')"
- + ".getVerticesByProperty('global-customer-id','a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb')"
- + ".createEdgeTraversal(EdgeType.TREE, 'customer','service-subscription').getVerticesByProperty('service-subscription-id','Nimbus')"
- + ".createEdgeTraversal(EdgeType.TREE, 'service-subscription','service-instance').getVerticesByProperty('service-instance-id','sid')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'service-instance','generic-vnf').store('x')"
- + ".union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vnfc').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pnf').store('x')).cap('x').unfold().dedup()";
-
- String aaiQuery = "customer('global-customer-id', 'a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb') > service-subscription('service-subscription-id', 'Nimbus') "
- + " > service-instance('service-instance-id','sid') > generic-vnf* "
- + " > [ vnfc* , vserver*, pserver* , pnf* ]";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void vnf_Dsl() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where(builder.newInstance().union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver')"
- + ".getVerticesByProperty('hostname','hostname1'),builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').getVerticesByProperty('hostname','hostname1'))).store('x').cap('x').unfold().dedup()";
-
- String aaiQuery = "generic-vnf*('vnf-id','vnfId') (> [ pserver('hostname','hostname1'), "
- + " vserver > pserver('hostname','hostname1')])";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void hasPropertyTest() throws AAIException {
- String aaiQuery = "cloud-region* ('cloud-owner')";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner').store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void hasPropertyValuesTest() throws AAIException {
- String aaiQuery = "cloud-region* ('cloud-owner','cloud-owner1','cloud-owner2')";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner', new ArrayList<>(Arrays.asList('cloud-owner1','cloud-owner2'))).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void hasNotPropertyValuesTest() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner','cloud-owner1','cloud-owner2')";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner', new ArrayList<>(Arrays.asList('cloud-owner1','cloud-owner2'))).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void hasNotPropertyNullValuesTest() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner',' ',' null ')";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner', new ArrayList<>(Arrays.asList(' ',' null '))).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Ignore
- @Test
- public void hasPropertyIntegerTest() throws AAIException {
- String aaiQuery = "cloud-region('cloud-owner', 'att-nc')('cloud-region-id', 'MTN61a') > vlan-range > vlan-tag*('vlan-id-inner', 20)";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','att-nc').getVerticesByProperty('cloud-region-id','MTN61a')"
- + ".createEdgeTraversal(EdgeType.TREE, 'cloud-region','vlan-range').createEdgeTraversal(EdgeType.TREE, 'vlan-range','vlan-tag').getVerticesByProperty('vlan-id-inner',20).store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void noEdgeRuleTest() throws AAIException {
- String aaiQuery = "vserver('vserver-id','abc') > logical-link* > l-interface*";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'vserver').getVerticesByProperty('vserver-id','abc').createEdgeTraversal(EdgeType.TREE, 'vserver','logical-link').store('x').createEdgeTraversal('logical-link','l-interface').store('x')cap('x').unfold().dedup()";
- expectedEx.expect(org.onap.aai.exceptions.AAIException.class);
- expectedEx.expectMessage("No EdgeRule found for passed nodeTypes: vserver, logical-link");
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void multipleEdgeRuleTest() throws AAIException {
- String aaiQuery = "vserver('vserver-id','abc') > l-interface* > lag-interface*";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'vserver').getVerticesByProperty('vserver-id','abc').createEdgeTraversal(EdgeType.TREE, 'vserver','l-interface').store('x').createEdgeTraversal( 'l-interface','lag-interface').store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void multipleEdgeRuleTestWithLabels() throws AAIException {
- String aaiQuery = "vserver('vserver-id','abc') > l-interface* > ('org.onap.relationships.inventory.BelongsTo') lag-interface*";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'vserver').getVerticesByProperty('vserver-id','abc').createEdgeTraversal(EdgeType.TREE, 'vserver','l-interface').store('x').createEdgeTraversalWithLabels( 'l-interface','lag-interface', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo'))).store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void hasNotPropertyTest() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner')";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner').store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void overlyNestedQueryTest() throws AAIException {
- String aaiQuery = "generic-vnf*('vnf-id','vnfId') (> [ pserver('hostname','hostname1'), vserver (> [ pserver('hostname','hostname1'), pserver('hostname','hostname1')])]) > vserver";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where(builder.newInstance().union" +
- "(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').getVerticesByProperty('hostname','hostname1')," +
- "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').where(builder.newInstance().union(builder.newInstance()" +
- ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').getVerticesByProperty('hostname','hostname1'),builder.newInstance()." +
- "createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').getVerticesByProperty('hostname','hostname1'))))).store('x').createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void overlyNestedQueryTestWithLabels() throws AAIException {
- String aaiQuery = "generic-vnf*('vnf-id','vnfId') (> [ ('tosca.relationships.HostedOn')pserver('hostname','hostname1'), ('tosca.relationships.HostedOn')vserver (> [ ('tosca.relationships.HostedOn')pserver('hostname','hostname1'), ('tosca.relationships.HostedOn')pserver('hostname','hostname1')])]) > ('org.onap.relationships.inventory.PartOf')allotted-resource";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where(builder.newInstance().union" +
- "(builder.newInstance().createEdgeTraversalWithLabels( 'generic-vnf','pserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).getVerticesByProperty('hostname','hostname1')," +
- "builder.newInstance().createEdgeTraversalWithLabels( 'generic-vnf','vserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).where(builder.newInstance().union(builder.newInstance()" +
- ".createEdgeTraversalWithLabels( 'vserver','pserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).getVerticesByProperty('hostname','hostname1'),builder.newInstance()." +
- "createEdgeTraversalWithLabels( 'vserver','pserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).getVerticesByProperty('hostname','hostname1'))))).store('x').createEdgeTraversalWithLabels( 'generic-vnf','allotted-resource', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.PartOf'))).cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void getPserverWithAnEdgeToComplexAndCloudRegion() throws AAIException {
- String aaiQuery = "pserver*('prov-status')(> complex)(> cloud-region)";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('prov-status').where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex')).where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','cloud-region')).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void getPserverWithAnEdgeToComplexButNotToCloudRegion() throws AAIException {
- String aaiQuery = "pserver*('prov-status')(> complex)!(> cloud-region)";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('prov-status').where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex')).where(builder.newInstance().not(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','cloud-region'))).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void nestedUnionQueryTest() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').store('x').union("
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').store('x'))"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x')"
- + ".union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'complex','availability-zone')"
- + ".createEdgeTraversal(EdgeType.TREE, 'availability-zone','cloud-region').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'complex','ctag-pool').store('x').union("
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'ctag-pool','availability-zone').store('x')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'availability-zone','complex').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'ctag-pool','generic-vnf').store('x')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','availability-zone').store('x')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'availability-zone','complex').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'ctag-pool','vpls-pe').store('x')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'vpls-pe','complex').store('x'))"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').store('x'))"
- + ".createEdgeTraversal(EdgeType.TREE, 'cloud-region','tenant').store('x')"
- + ".cap('x').unfold().dedup()";
-
- String aaiQuery = "generic-vnf*('vnf-id','vnfId') > [ pserver* , "
- + " vserver > pserver* ] > complex* > [ availability-zone > cloud-region*, cloud-region*, " +
- " ctag-pool* > [ availability-zone* > complex* , generic-vnf* > availability-zone* > complex*, vpls-pe* > complex*] > cloud-region*] > tenant* " ;
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void booleanPropertyValuesTest() throws AAIException {
- String aaiQuery = "cloud-region ('cloud-owner','cloud-owner1') > zone*('in-maint',true)";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','cloud-owner1').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','zone').getVerticesByBooleanProperty('in-maint',true).store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void upperCaseBooleanPropertyValuesTest() throws AAIException {
- String aaiQuery = "cloud-region ('cloud-owner','cloud-owner1') > zone*('in-maint',TRUE)";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','cloud-owner1').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','zone').getVerticesByBooleanProperty('in-maint',true).store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void booleanPropertyTest() throws AAIException {
- String aaiQuery = "cloud-region ('cloud-owner','cloud-owner1') > zone*('in-maint')";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','cloud-owner1').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','zone').getVerticesByProperty('in-maint').store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test(expected = AAIException.class)
- public void filterOnUnion_vserverFromTentantFromCloudRegion_BadRequest() throws AAIException {
- String aaiQuery = "cloud-region('cloud-owner', 'test-aic')>[tenant*('tenant-id', 'tenant1'), tenant*('tenant-id', 'tenant2')]('tenant-name', 'tenant1')>[vserver*]";
- dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- }
+ @Rule
+ public ExpectedException expectedEx = ExpectedException.none();
+
+ @Test
+ public void dbAliasTest() throws AAIException {
+ String aaiQuery = "logical-link* ('model-invariant-id','invid')";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'logical-link').getVerticesByProperty('model-invariant-id-local','invid')"
+ + ".store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void apostropheTest() throws AAIException {
+ String aaiQuery = "logical-link*('link-id','dsl\\'link')";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'logical-link').getVerticesByProperty('link-id','dsl\\'link')"
+ + ".store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void parseCancellationExceptionTest() throws AAIException {
+ boolean thrown = false;
+ String aaiQuery = "logical-link*('link-id','dsl\\'link)";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'logical-link').getVerticesByProperty('link-id','dsl\\'link')"
+ + ".store('x').cap('x').unfold().dedup()";
+
+ try {
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ } catch (AAIException e) {
+ thrown = true;
+ }
+ assertTrue(thrown);
+ }
+
+ @Test
+ public void cloudRegionFromVnf() throws AAIException {
+ String aaiQuery =
+ "generic-vnf*('vnf-name','xyz') > [ vnfc* > vserver* > [pserver*, tenant* > cloud-region*], "
+ + "vserver* > [pserver*, tenant* > cloud-region*] ]";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-name','xyz').store('x').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vnfc').store('x')."
+ + "createEdgeTraversal(EdgeType.COUSIN, 'vnfc','vserver').store('x').union(builder.newInstance().createEdgeTraversal"
+ + "(EdgeType.COUSIN, 'vserver','pserver').store('x'),builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'vserver','tenant')"
+ + ".store('x').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region').store('x')),builder.newInstance().createEdgeTraversal"
+ + "(EdgeType.COUSIN, 'generic-vnf','vserver').store('x').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vserver'"
+ + ",'pserver').store('x'),builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').store('x').createEdgeTraversal"
+ + "(EdgeType.TREE, 'tenant','cloud-region').store('x'))).cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void cloudRegionSites() throws AAIException {
+ String aaiQuery = "cloud-region*('cloud-owner','xyz') > complex*";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner'"
+ + ",'xyz').store('x').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','complex').store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void pserverWithNoComplexTest() throws AAIException {
+ String aaiQuery = "pserver*('hostname','xyz')!(> complex)";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('hostname','xyz').where(builder.newInstance().not("
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex'))).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void pserverWhereNotTest() throws AAIException {
+ String aaiQuery = "pserver('hostname','xyz')>vserver*!(> vnfc > configuration))";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('hostname','xyz').createEdgeTraversal"
+ + "(EdgeType.COUSIN, 'pserver','vserver').where(builder.newInstance().not(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN,"
+ + " 'vserver','vnfc').createEdgeTraversal(EdgeType.COUSIN, 'vnfc','configuration'))).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void singleNode1() throws AAIException {
+ String aaiQuery = "cloud-region* !('cloud-owner','coid')";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
+ + ".store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void singleNodeLimit() throws AAIException {
+ String aaiQuery = "cloud-region* !('cloud-owner','coid') LIMIT 10";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
+ + ".store('x').cap('x').unfold().dedup().limit(10)";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void specialCharacterTest() throws AAIException {
+ String aaiQuery =
+ "cloud-region* !('cloud-owner','coidhello:?_-)(!@#$%^&*+={}[]|/.<,') LIMIT 10";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coidhello:?_-)(!@#$%^&*+={}[]|/.<,')"
+ + ".store('x').cap('x').unfold().dedup().limit(10)";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void singleNodeLimitBlah() throws AAIException {
+ String aaiQuery = "cloud-region* !('cloud-owner','coid') LIMIT blah";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
+ + ".getVerticesByProperty('cloud-region-id','cr id').store('x').cap('x').unfold().dedup().limit(10)";
+
+ expectedEx.expect(org.onap.aai.exceptions.AAIException.class);
+ expectedEx.expectMessage("DSL Syntax Error while processing the query");
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ }
+
+ @Test
+ public void singleNodeLimitNull() throws AAIException {
+ String aaiQuery = "cloud-region* !('cloud-owner','coid') LIMIT ";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
+ + ".getVerticesByProperty('cloud-region-id','cr id').store('x').cap('x').unfold().dedup().limit(10)";
+
+ expectedEx.expect(org.onap.aai.exceptions.AAIException.class);
+ expectedEx.expectMessage("DSL Syntax Error while processing the query");
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ }
+
+ @Test
+ public void cloudRegion1Test() throws AAIException {
+ String aaiQuery =
+ "cloud-region* !('cloud-owner','coid')('cloud-region-id','cr id') LIMIT 10";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
+ + ".getVerticesByProperty('cloud-region-id','cr id').store('x').cap('x').unfold().dedup().limit(10)";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void cloudRegion_entitlementTest() throws AAIException {
+
+ /*
+ * A store within a where makes no sense
+ */
+ String aaiQuery =
+ "generic-vnf('vnf-id','vnfId') ( > vserver > tenant > cloud-region('cloud-region-id','One')) > entitlement*";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where("
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region')"
+ + ".getVerticesByProperty('cloud-region-id','One'))"
+ + ".createEdgeTraversal(EdgeType.TREE, 'generic-vnf','entitlement').store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void cloudRegion_entitlementTestWithLabels() throws AAIException {
+
+ String aaiQuery =
+ "generic-vnf('vnf-id','vnfId') (> ('tosca.relationships.HostedOn') vserver > ('org.onap.relationships.inventory.BelongsTo') tenant > ('org.onap.relationships.inventory.BelongsTo') cloud-region('cloud-region-id','One')) > ('org.onap.relationships.inventory.ComposedOf')service-instance*";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where("
+ + "builder.newInstance().createEdgeTraversalWithLabels( 'generic-vnf','vserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).createEdgeTraversalWithLabels( 'vserver','tenant', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo'))).createEdgeTraversalWithLabels( 'tenant','cloud-region', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo')))"
+ + ".getVerticesByProperty('cloud-region-id','One'))"
+ + ".createEdgeTraversalWithLabels( 'generic-vnf','service-instance', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.ComposedOf'))).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void complex_az_fromComplexTest() throws AAIException {
+
+ String aaiQuery =
+ "cloud-region('cloud-owner','coid')('cloud-region-id','crid') > [ availability-zone* , complex*]";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region')"
+ + ".getVerticesByProperty('cloud-owner','coid').getVerticesByProperty('cloud-region-id','crid')"
+ + ".union(builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'cloud-region','availability-zone').store('x')"
+ + ",builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','complex').store('x')).cap('x').unfold().dedup()";
+
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void complex_az_fromComplexTestWithLabels() throws AAIException {
+
+ String aaiQuery =
+ "cloud-region('cloud-owner','coid')('cloud-region-id','crid') > [ ('org.onap.relationships.inventory.BelongsTo')availability-zone* , ('org.onap.relationships.inventory.LocatedIn')complex*]";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region')"
+ + ".getVerticesByProperty('cloud-owner','coid').getVerticesByProperty('cloud-region-id','crid')"
+ + ".union(builder.newInstance().createEdgeTraversalWithLabels( 'cloud-region','availability-zone', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo'))).store('x')"
+ + ",builder.newInstance().createEdgeTraversalWithLabels( 'cloud-region','complex', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.LocatedIn'))).store('x')).cap('x').unfold().dedup()";
+
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void cloudRegion_fromComplex1Test() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'complex').getVerticesByProperty('data-center-code','data-center-code-name')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').store('x').cap('x').unfold().dedup()";
+ String aaiQuery = "complex('data-center-code','data-center-code-name') > cloud-region*";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void cloudRegion_fromComplex2Test() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'complex').getVerticesByProperty('data-center-code','data-center-code-name')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').getVerticesByProperty('cloud-region-version','crv')"
+ + ".store('x').cap('x').unfold().dedup()";
+ String aaiQuery =
+ "complex('data-center-code','data-center-code-name') > cloud-region*('cloud-region-version','crv')";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void cloudRegion_fromNfTypeTest() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'image').getVerticesByProperty('application-vendor','F5')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'image','vserver')"
+ + ".where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vserver','generic-vnf').getVerticesByProperty('vnf-name','ZALL1MMSC03'))"
+ + ".createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region')"
+ + ".store('x').cap('x').unfold().dedup()";
+
+ String aaiQuery =
+ "image('application-vendor','F5') > vserver (> generic-vnf('vnf-name','ZALL1MMSC03')) > tenant > cloud-region*";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void cloudRegion_fromNfTypeVendorVersionTest() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'image').getVerticesByProperty('application-vendor','vendor')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'image','vserver').where("
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vserver','generic-vnf').getVerticesByProperty('nf-type','nfType')"
+ + ").createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region')"
+ + ".store('x').cap('x').unfold().dedup()";
+
+ String aaiQuery =
+ "image('application-vendor','vendor') > vserver(> generic-vnf('nf-type', 'nfType') ) > tenant > cloud-region*";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void cloud_region_fromVnfTest() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vnfc').store('x')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'vnfc','vserver').store('x')"
+ + ".createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').store('x')"
+ + ".createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region').store('x')"
+ + ".cap('x').unfold().dedup()";
+
+ String aaiQuery =
+ "generic-vnf('vnf-id','vnfId') > vnfc* > vserver* > tenant* > cloud-region*";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void cloud_region_sitesTest() throws AAIException {
+
+ String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region')."
+ + "getVerticesByProperty('cloud-owner','co').store('x').createEdgeTraversal(EdgeType.COUSIN, "
+ + "'cloud-region','complex').store('x').cap('x').unfold().dedup()";
+
+ String aaiQuery = "cloud-region*('cloud-owner','co') > complex*";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void complex_fromVnf2Test() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').store('x').union("
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').store('x')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x')"
+ + ").cap('x').unfold().dedup()";
+
+ String aaiQuery = "generic-vnf*('vnf-id','vnfId') > [ pserver* > complex*, "
+ + " vserver > pserver* > complex* " + "]";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void complex_fromVnfTest2() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').store('x').union("
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').store('x'))"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x')"
+ + ".cap('x').unfold().dedup()";
+
+ String aaiQuery = "generic-vnf*('vnf-id','vnfId') > [ pserver* , "
+ + " vserver > pserver* ] > complex*";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void fn_topology1Test() throws AAIException {
+
+ String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'customer')"
+ + ".getVerticesByProperty('global-customer-id','a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb')"
+ + ".createEdgeTraversal(EdgeType.TREE, 'customer','service-subscription').getVerticesByProperty('service-subscription-id','Nimbus')"
+ + ".createEdgeTraversal(EdgeType.TREE, 'service-subscription','service-instance').getVerticesByProperty('service-instance-id','sid')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'service-instance','generic-vnf').store('x')"
+ + ".union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vnfc').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pnf').store('x')).cap('x').unfold().dedup()";
+
+ String aaiQuery =
+ "customer('global-customer-id', 'a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb') > service-subscription('service-subscription-id', 'Nimbus') "
+ + " > service-instance('service-instance-id','sid') > generic-vnf* "
+ + " > [ vnfc* , vserver*, pserver* , pnf* ]";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void vnf_Dsl() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where(builder.newInstance().union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver')"
+ + ".getVerticesByProperty('hostname','hostname1'),builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').getVerticesByProperty('hostname','hostname1'))).store('x').cap('x').unfold().dedup()";
+
+ String aaiQuery = "generic-vnf*('vnf-id','vnfId') (> [ pserver('hostname','hostname1'), "
+ + " vserver > pserver('hostname','hostname1')])";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void hasPropertyTest() throws AAIException {
+ String aaiQuery = "cloud-region* ('cloud-owner')";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner').store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void hasPropertyValuesTest() throws AAIException {
+ String aaiQuery = "cloud-region* ('cloud-owner','cloud-owner1','cloud-owner2')";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner', new ArrayList<>(Arrays.asList('cloud-owner1','cloud-owner2'))).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void hasNotPropertyValuesTest() throws AAIException {
+ String aaiQuery = "cloud-region* !('cloud-owner','cloud-owner1','cloud-owner2')";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner', new ArrayList<>(Arrays.asList('cloud-owner1','cloud-owner2'))).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void hasNotPropertyNullValuesTest() throws AAIException {
+ String aaiQuery = "cloud-region* !('cloud-owner',' ',' null ')";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner', new ArrayList<>(Arrays.asList(' ',' null '))).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Ignore
+ @Test
+ public void hasPropertyIntegerTest() throws AAIException {
+ String aaiQuery =
+ "cloud-region('cloud-owner', 'att-nc')('cloud-region-id', 'MTN61a') > vlan-range > vlan-tag*('vlan-id-inner', 20)";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','att-nc').getVerticesByProperty('cloud-region-id','MTN61a')"
+ + ".createEdgeTraversal(EdgeType.TREE, 'cloud-region','vlan-range').createEdgeTraversal(EdgeType.TREE, 'vlan-range','vlan-tag').getVerticesByProperty('vlan-id-inner',20).store('x').cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void noEdgeRuleTest() throws AAIException {
+ String aaiQuery = "vserver('vserver-id','abc') > logical-link* > l-interface*";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'vserver').getVerticesByProperty('vserver-id','abc').createEdgeTraversal(EdgeType.TREE, 'vserver','logical-link').store('x').createEdgeTraversal('logical-link','l-interface').store('x')cap('x').unfold().dedup()";
+ expectedEx.expect(org.onap.aai.exceptions.AAIException.class);
+ expectedEx.expectMessage("No EdgeRule found for passed nodeTypes: vserver, logical-link");
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void multipleEdgeRuleTest() throws AAIException {
+ String aaiQuery = "vserver('vserver-id','abc') > l-interface* > lag-interface*";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'vserver').getVerticesByProperty('vserver-id','abc').createEdgeTraversal(EdgeType.TREE, 'vserver','l-interface').store('x').createEdgeTraversal( 'l-interface','lag-interface').store('x').cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void multipleEdgeRuleTestWithLabels() throws AAIException {
+ String aaiQuery =
+ "vserver('vserver-id','abc') > l-interface* > ('org.onap.relationships.inventory.BelongsTo') lag-interface*";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'vserver').getVerticesByProperty('vserver-id','abc').createEdgeTraversal(EdgeType.TREE, 'vserver','l-interface').store('x').createEdgeTraversalWithLabels( 'l-interface','lag-interface', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo'))).store('x').cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void hasNotPropertyTest() throws AAIException {
+ String aaiQuery = "cloud-region* !('cloud-owner')";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner').store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void overlyNestedQueryTest() throws AAIException {
+ String aaiQuery =
+ "generic-vnf*('vnf-id','vnfId') (> [ pserver('hostname','hostname1'), vserver (> [ pserver('hostname','hostname1'), pserver('hostname','hostname1')])]) > vserver";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where(builder.newInstance().union"
+ + "(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').getVerticesByProperty('hostname','hostname1'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').where(builder.newInstance().union(builder.newInstance()"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').getVerticesByProperty('hostname','hostname1'),builder.newInstance()."
+ + "createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').getVerticesByProperty('hostname','hostname1'))))).store('x').createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void overlyNestedQueryTestWithLabels() throws AAIException {
+ String aaiQuery =
+ "generic-vnf*('vnf-id','vnfId') (> [ ('tosca.relationships.HostedOn')pserver('hostname','hostname1'), ('tosca.relationships.HostedOn')vserver (> [ ('tosca.relationships.HostedOn')pserver('hostname','hostname1'), ('tosca.relationships.HostedOn')pserver('hostname','hostname1')])]) > ('org.onap.relationships.inventory.PartOf')allotted-resource";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where(builder.newInstance().union"
+ + "(builder.newInstance().createEdgeTraversalWithLabels( 'generic-vnf','pserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).getVerticesByProperty('hostname','hostname1'),"
+ + "builder.newInstance().createEdgeTraversalWithLabels( 'generic-vnf','vserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).where(builder.newInstance().union(builder.newInstance()"
+ + ".createEdgeTraversalWithLabels( 'vserver','pserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).getVerticesByProperty('hostname','hostname1'),builder.newInstance()."
+ + "createEdgeTraversalWithLabels( 'vserver','pserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).getVerticesByProperty('hostname','hostname1'))))).store('x').createEdgeTraversalWithLabels( 'generic-vnf','allotted-resource', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.PartOf'))).cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void getPserverWithAnEdgeToComplexAndCloudRegion() throws AAIException {
+ String aaiQuery = "pserver*('prov-status')(> complex)(> cloud-region)";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('prov-status').where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex')).where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','cloud-region')).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void getPserverWithAnEdgeToComplexButNotToCloudRegion() throws AAIException {
+ String aaiQuery = "pserver*('prov-status')(> complex)!(> cloud-region)";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('prov-status').where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex')).where(builder.newInstance().not(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','cloud-region'))).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void nestedUnionQueryTest() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').store('x').union("
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').store('x'))"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x')"
+ + ".union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'complex','availability-zone')"
+ + ".createEdgeTraversal(EdgeType.TREE, 'availability-zone','cloud-region').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'complex','ctag-pool').store('x').union("
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'ctag-pool','availability-zone').store('x')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'availability-zone','complex').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'ctag-pool','generic-vnf').store('x')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','availability-zone').store('x')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'availability-zone','complex').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'ctag-pool','vpls-pe').store('x')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'vpls-pe','complex').store('x'))"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').store('x'))"
+ + ".createEdgeTraversal(EdgeType.TREE, 'cloud-region','tenant').store('x')"
+ + ".cap('x').unfold().dedup()";
+
+ String aaiQuery = "generic-vnf*('vnf-id','vnfId') > [ pserver* , "
+ + " vserver > pserver* ] > complex* > [ availability-zone > cloud-region*, cloud-region*, "
+ + " ctag-pool* > [ availability-zone* > complex* , generic-vnf* > availability-zone* > complex*, vpls-pe* > complex*] > cloud-region*] > tenant* ";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void booleanPropertyValuesTest() throws AAIException {
+ String aaiQuery = "cloud-region ('cloud-owner','cloud-owner1') > zone*('in-maint',true)";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','cloud-owner1').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','zone').getVerticesByBooleanProperty('in-maint',true).store('x').cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void upperCaseBooleanPropertyValuesTest() throws AAIException {
+ String aaiQuery = "cloud-region ('cloud-owner','cloud-owner1') > zone*('in-maint',TRUE)";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','cloud-owner1').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','zone').getVerticesByBooleanProperty('in-maint',true).store('x').cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void booleanPropertyTest() throws AAIException {
+ String aaiQuery = "cloud-region ('cloud-owner','cloud-owner1') > zone*('in-maint')";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','cloud-owner1').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','zone').getVerticesByProperty('in-maint').store('x').cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test(expected = AAIException.class)
+ public void filterOnUnion_vserverFromTentantFromCloudRegion_BadRequest() throws AAIException {
+ String aaiQuery =
+ "cloud-region('cloud-owner', 'test-aic')>[tenant*('tenant-id', 'tenant1'), tenant*('tenant-id', 'tenant2')]('tenant-name', 'tenant1')>[vserver*]";
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslQueryProcessorV2Test.java b/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslQueryProcessorV2Test.java
index 9ff42e0..6d3d69c 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslQueryProcessorV2Test.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/dsl/DslQueryProcessorV2Test.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,8 @@
*/
package org.onap.aai.rest.dsl;
+import static org.junit.Assert.assertEquals;
+
import org.junit.Ignore;
import org.junit.Rule;
import org.junit.Test;
@@ -27,597 +29,704 @@ import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.rest.enums.QueryVersion;
-import static org.junit.Assert.assertEquals;
-
/**
* The Class DslMain.
*/
public class DslQueryProcessorV2Test extends AAISetup {
- @Rule
- public ExpectedException expectedEx = ExpectedException.none();
-
- @Test
- public void dbAliasTest() throws AAIException {
- String aaiQuery = "logical-link* ('model-invariant-id','invid')";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'logical-link').getVerticesByProperty('model-invariant-id-local','invid')"
- + ".store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
- @Test
- public void apostropheTest() throws AAIException {
- String aaiQuery = "logical-link*('link-id','dsl\\'link')";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'logical-link').getVerticesByProperty('link-id','dsl\\'link')"
- + ".store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void cloudRegionFromVnf() throws AAIException {
- String aaiQuery = "generic-vnf*('vnf-name','xyz') [> vnfc* > vserver* [>pserver*, > tenant* > cloud-region*], "+
- "> vserver* [> pserver*, >tenant* > cloud-region*] ]";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-name','xyz').store('x').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vnfc').store('x')."
- +"createEdgeTraversal(EdgeType.COUSIN, 'vnfc','vserver').store('x').union(builder.newInstance().createEdgeTraversal"
- +"(EdgeType.COUSIN, 'vserver','pserver').store('x'),builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'vserver','tenant')"
- +".store('x').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region').store('x')),builder.newInstance().createEdgeTraversal"
- +"(EdgeType.COUSIN, 'generic-vnf','vserver').store('x').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vserver'"
- +",'pserver').store('x'),builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').store('x').createEdgeTraversal"
- +"(EdgeType.TREE, 'tenant','cloud-region').store('x'))).cap('x').unfold().dedup()";
-
-
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void cloudRegionFromVnfWithDirection() throws AAIException {
- String aaiQuery = "generic-vnf*('vnf-name','xyz') [>> vnfc* >> vserver* [>>pserver*, >> tenant* >> cloud-region*], "+
- ">> vserver* [>> pserver*, >>tenant* >> cloud-region*] ]";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-name','xyz').store('x').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vnfc').store('x')."
- +"createEdgeTraversal(EdgeType.COUSIN, 'vnfc','vserver').store('x').union(builder.newInstance().createEdgeTraversal"
- +"(EdgeType.COUSIN, 'vserver','pserver').store('x'),builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'vserver','tenant')"
- +".store('x').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region').store('x')),builder.newInstance().createEdgeTraversal"
- +"(EdgeType.COUSIN, 'generic-vnf','vserver').store('x').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vserver'"
- +",'pserver').store('x'),builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').store('x').createEdgeTraversal"
- +"(EdgeType.TREE, 'tenant','cloud-region').store('x'))).cap('x').unfold().dedup()";
-
-
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
- @Test
- public void cloudRegionSites() throws AAIException {
- String aaiQuery = "cloud-region*('cloud-owner','xyz') > complex*";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner'"
- +",'xyz').store('x').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','complex').store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void pserverWithNoComplexTest() throws AAIException {
- String aaiQuery = "pserver*('hostname','xyz')!(> complex)";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('hostname','xyz').where(builder.newInstance().not("
- +"builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex'))).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void pserverWhereNotTest() throws AAIException {
- String aaiQuery = "pserver('hostname','xyz')>vserver*!(> vnfc > configuration))";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('hostname','xyz').createEdgeTraversal" +
- "(EdgeType.COUSIN, 'pserver','vserver').where(builder.newInstance().not(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN,"+
- " 'vserver','vnfc').createEdgeTraversal(EdgeType.COUSIN, 'vnfc','configuration'))).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void singleNode1() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner','coid')";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
- + ".store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void singleNodeLimit() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner','coid') LIMIT 10";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
- + ".store('x').cap('x').unfold().dedup().limit(10)";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void specialCharacterTest() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner','coidhello:?_-)(!@#$%^&*+={}[]|/.<,') LIMIT 10";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coidhello:?_-)(!@#$%^&*+={}[]|/.<,')"
- + ".store('x').cap('x').unfold().dedup().limit(10)";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void singleNodeLimitBlah() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner','coid') LIMIT blah";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
- + ".getVerticesByProperty('cloud-region-id','cr id').store('x').cap('x').unfold().dedup().limit(10)";
-
- expectedEx.expect(AAIException.class);
- expectedEx.expectMessage("DSL Syntax Error while processing the query");
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- }
-
- @Test
- public void singleNodeLimitNull() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner','coid') LIMIT ";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
- + ".getVerticesByProperty('cloud-region-id','cr id').store('x').cap('x').unfold().dedup().limit(10)";
-
- expectedEx.expect(AAIException.class);
- expectedEx.expectMessage("DSL Syntax Error while processing the query");
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- }
-
- @Test
- public void cloudRegion1Test() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner','coid')('cloud-region-id','cr id') LIMIT 10";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
- + ".getVerticesByProperty('cloud-region-id','cr id').store('x').cap('x').unfold().dedup().limit(10)";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void cloudRegion_entitlementTest() throws AAIException {
-
- /*
- A store within a where makes no sense
- */
- String aaiQuery = "generic-vnf('vnf-id','vnfId') ( > vserver > tenant > cloud-region('cloud-region-id','One')) > entitlement*";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where("
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region')"
- + ".getVerticesByProperty('cloud-region-id','One'))"
- + ".createEdgeTraversal(EdgeType.TREE, 'generic-vnf','entitlement').store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void cloudRegion_entitlementTestWithLabels() throws AAIException {
-
- String aaiQuery = "generic-vnf('vnf-id','vnfId') (> ('tosca.relationships.HostedOn') vserver > ('org.onap.relationships.inventory.BelongsTo') tenant > ('org.onap.relationships.inventory.BelongsTo') cloud-region('cloud-region-id','One')) > ('org.onap.relationships.inventory.ComposedOf')service-instance*";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where("
- + "builder.newInstance().createEdgeTraversalWithLabels( 'generic-vnf','vserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).createEdgeTraversalWithLabels( 'vserver','tenant', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo'))).createEdgeTraversalWithLabels( 'tenant','cloud-region', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo')))"
- + ".getVerticesByProperty('cloud-region-id','One'))"
- + ".createEdgeTraversalWithLabels( 'generic-vnf','service-instance', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.ComposedOf'))).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void complex_az_fromComplexTest() throws AAIException {
-
- String aaiQuery = "cloud-region('cloud-owner','coid')('cloud-region-id','crid') [> availability-zone* ,> complex*]";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region')"
- + ".getVerticesByProperty('cloud-owner','coid').getVerticesByProperty('cloud-region-id','crid')"
- + ".union(builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'cloud-region','availability-zone').store('x')"
- + ",builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','complex').store('x')).cap('x').unfold().dedup()";
-
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void complex_az_fromComplexTestWithLabels() throws AAIException {
-
- String aaiQuery = "cloud-region('cloud-owner','coid')('cloud-region-id','crid') [> ('org.onap.relationships.inventory.BelongsTo')availability-zone* ,> ('org.onap.relationships.inventory.LocatedIn')complex*]";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region')"
- + ".getVerticesByProperty('cloud-owner','coid').getVerticesByProperty('cloud-region-id','crid')"
- + ".union(builder.newInstance().createEdgeTraversalWithLabels( 'cloud-region','availability-zone', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo'))).store('x')"
- + ",builder.newInstance().createEdgeTraversalWithLabels( 'cloud-region','complex', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.LocatedIn'))).store('x')).cap('x').unfold().dedup()";
-
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void cloudRegion_fromComplex1Test() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'complex').getVerticesByProperty('data-center-code','data-center-code-name')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').store('x').cap('x').unfold().dedup()";
- String aaiQuery = "complex('data-center-code','data-center-code-name') > cloud-region*";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void cloudRegion_fromComplex2Test() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'complex').getVerticesByProperty('data-center-code','data-center-code-name')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').getVerticesByProperty('cloud-region-version','crv')"
- + ".store('x').cap('x').unfold().dedup()";
- String aaiQuery = "complex('data-center-code','data-center-code-name') > cloud-region*('cloud-region-version','crv')";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void cloudRegion_fromNfTypeTest() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'image').getVerticesByProperty('application-vendor','F5')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'image','vserver')"
- + ".where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vserver','generic-vnf').getVerticesByProperty('vnf-name','ZALL1MMSC03'))"
- + ".createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region')"
- + ".store('x').cap('x').unfold().dedup()";
-
- String aaiQuery = "image('application-vendor','F5') > vserver (> generic-vnf('vnf-name','ZALL1MMSC03')) > tenant > cloud-region*";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void cloudRegion_fromNfTypeVendorVersionTest() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'image').getVerticesByProperty('application-vendor','vendor')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'image','vserver').where("
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vserver','generic-vnf').getVerticesByProperty('nf-type','nfType')"
- + ").createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region')"
- + ".store('x').cap('x').unfold().dedup()";
-
- String aaiQuery = "image('application-vendor','vendor') > vserver(> generic-vnf('nf-type', 'nfType') ) > tenant > cloud-region*";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void cloud_region_fromVnfTest() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vnfc').store('x')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'vnfc','vserver').store('x')"
- + ".createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').store('x')"
- + ".createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region').store('x')"
- + ".cap('x').unfold().dedup()";
-
- String aaiQuery = "generic-vnf('vnf-id','vnfId') > vnfc* > vserver* > tenant* > cloud-region*";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void cloud_region_sitesTest() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region')."
- + "getVerticesByProperty('cloud-owner','co').store('x').createEdgeTraversal(EdgeType.COUSIN, "
- + "'cloud-region','complex').store('x').cap('x').unfold().dedup()";
-
- String aaiQuery = "cloud-region*('cloud-owner','co') > complex*";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void complex_fromVnf2Test() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').store('x').union("
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').store('x')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x')"
- + ").cap('x').unfold().dedup()";
-
- String aaiQuery = "generic-vnf*('vnf-id','vnfId') [ > pserver* > complex*, "
- + " >vserver > pserver* > complex* " + "]";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void complex_fromVnfTest2() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').store('x').union("
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').store('x'))"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x')"
- + ".cap('x').unfold().dedup()";
-
- String aaiQuery = "generic-vnf*('vnf-id','vnfId') [> pserver* , "
- + " > vserver > pserver* ] > complex*";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void fn_topology1Test() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'customer')"
- + ".getVerticesByProperty('global-customer-id','a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb')"
- + ".createEdgeTraversal(EdgeType.TREE, 'customer','service-subscription').getVerticesByProperty('service-subscription-id','Nimbus')"
- + ".createEdgeTraversal(EdgeType.TREE, 'service-subscription','service-instance').getVerticesByProperty('service-instance-id','sid')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'service-instance','generic-vnf').store('x')"
- + ".union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vnfc').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pnf').store('x')).cap('x').unfold().dedup()";
-
- String aaiQuery = "customer('global-customer-id', 'a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb') > service-subscription('service-subscription-id', 'Nimbus') "
- + " > service-instance('service-instance-id','sid') > generic-vnf* "
- + " [> vnfc* ,> vserver*,> pserver* ,> pnf* ]";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void vnf_Dsl() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where(builder.newInstance().union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver')"
- + ".getVerticesByProperty('hostname','hostname1'),builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').getVerticesByProperty('hostname','hostname1'))).store('x').cap('x').unfold().dedup()";
-
- String aaiQuery = "generic-vnf*('vnf-id','vnfId') ( [> pserver('hostname','hostname1'), "
- + " > vserver > pserver('hostname','hostname1')])";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void hasPropertyTest() throws AAIException {
- String aaiQuery = "cloud-region* ('cloud-owner')";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner').store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void hasPropertyValuesTest() throws AAIException {
- String aaiQuery = "cloud-region* ('cloud-owner','cloud-owner1','cloud-owner2')";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner', new ArrayList<>(Arrays.asList('cloud-owner1','cloud-owner2'))).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void hasNotPropertyValuesTest() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner','cloud-owner1','cloud-owner2')";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner', new ArrayList<>(Arrays.asList('cloud-owner1','cloud-owner2'))).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void hasNotPropertyNullValuesTest() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner',' ',' null ')";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner', new ArrayList<>(Arrays.asList(' ',' null '))).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Ignore
- @Test
- public void hasPropertyIntegerTest() throws AAIException {
- String aaiQuery = "cloud-region('cloud-owner', 'att-nc')('cloud-region-id', 'MTN61a') > vlan-range > vlan-tag*('vlan-id-inner', 20)";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','att-nc').getVerticesByProperty('cloud-region-id','MTN61a')"
- + ".createEdgeTraversal(EdgeType.TREE, 'cloud-region','vlan-range').createEdgeTraversal(EdgeType.TREE, 'vlan-range','vlan-tag').getVerticesByProperty('vlan-id-inner',20).store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void directionalityTest() throws AAIException {
- String aaiQuery = "cloud-region('cloud-region-id','abc') >> complex* >> l3-network*";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-region-id','abc').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','complex').store('x').createEdgeTraversal(EdgeType.COUSIN, 'complex','l3-network').store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void enterSelectFilterTest() throws AAIException {
- String aaiQuery = "cloud-region*('cloud-region-id','whp3a'){'cloud-region-id'}";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-region-id','whp3a').store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
- assertEquals(query, dslQuery);
- }
-
-
- @Ignore
- @Test
- public void returnSpecificPropsAndAllForDifferentVertices() throws AAIException {
- String aaiQuery = "cloud-region{'cloud-owner'}('cloud-region-id','new-r111egion-111111') > [ l3-network*, vlan-range > vlan-tag*]";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-region-id','new-r111egion-111111').store('x').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','l3-network').store('x'),builder.newInstance()"
- + ".createEdgeTraversal(EdgeType.TREE, 'cloud-region','vlan-range').createEdgeTraversal(EdgeType.TREE, 'vlan-range','vlan-tag').store('x')).cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
- assertEquals(query, dslQuery);
- }
-
- @Test
- public void groupingAttributesTestForAggregate() throws AAIException {
- String aaiQuery = "cloud-region{'cloud-owner'}('cloud-owner','att-nc')('cloud-region-id','wah2a') > vip-ipv6-address-list > [subnet{'subnet-name'}, instance-group{'id'}]";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','att-nc').getVerticesByProperty('cloud-region-id','wah2a').store('x').createEdgeTraversal(EdgeType.TREE, 'cloud-region','vip-ipv6-address-list').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vip-ipv6-address-list','subnet').store('x'),builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vip-ipv6-address-list','instance-group').store('x')).cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
- assertEquals(query, dslQuery);
- }
-
- @Test
- public void multipleEdgeRuleTest() throws AAIException {
- String aaiQuery = "vserver('vserver-id','abc') > l-interface* > lag-interface*";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'vserver').getVerticesByProperty('vserver-id','abc').createEdgeTraversal(EdgeType.TREE, 'vserver','l-interface').store('x').createEdgeTraversal( 'l-interface','lag-interface').store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void multipleEdgeRuleTestWithLabels() throws AAIException {
- String aaiQuery = "vserver('vserver-id','abc') > l-interface* > ('org.onap.relationships.inventory.BelongsTo') lag-interface*";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'vserver').getVerticesByProperty('vserver-id','abc').createEdgeTraversal(EdgeType.TREE, 'vserver','l-interface').store('x').createEdgeTraversalWithLabels( 'l-interface','lag-interface', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo'))).store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void hasNotPropertyTest() throws AAIException {
- String aaiQuery = "cloud-region* !('cloud-owner')";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner').store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void overlyNestedQueryTest() throws AAIException {
- //String aaiQuery = "generic-vnf*('vnf-id','vnfId') (> [ pserver('hostname','hostname1'), vserver (> [ pserver('hostname','hostname1'), pserver('hostname','hostname1')])]) > vserver";
- String aaiQuery = "generic-vnf*('vnf-id','vnfId') ( [> pserver('hostname','hostname1'), > vserver ( [> pserver('hostname','hostname1'), > pserver('hostname','hostname1')])]) > vserver";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where(builder.newInstance().union" +
- "(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').getVerticesByProperty('hostname','hostname1')," +
- "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').where(builder.newInstance().union(builder.newInstance()" +
- ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').getVerticesByProperty('hostname','hostname1'),builder.newInstance()." +
- "createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').getVerticesByProperty('hostname','hostname1'))))).store('x').createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void overlyNestedQueryTestWithLabels() throws AAIException {
- String aaiQuery = "generic-vnf*('vnf-id','vnfId') ( [> ('tosca.relationships.HostedOn')pserver('hostname','hostname1'),> ('tosca.relationships.HostedOn')vserver ( [> ('tosca.relationships.HostedOn')pserver('hostname','hostname1'),> ('tosca.relationships.HostedOn')pserver('hostname','hostname1')])]) > ('org.onap.relationships.inventory.PartOf')allotted-resource";
-
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where(builder.newInstance().union" +
- "(builder.newInstance().createEdgeTraversalWithLabels( 'generic-vnf','pserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).getVerticesByProperty('hostname','hostname1')," +
- "builder.newInstance().createEdgeTraversalWithLabels( 'generic-vnf','vserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).where(builder.newInstance().union(builder.newInstance()" +
- ".createEdgeTraversalWithLabels( 'vserver','pserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).getVerticesByProperty('hostname','hostname1'),builder.newInstance()." +
- "createEdgeTraversalWithLabels( 'vserver','pserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).getVerticesByProperty('hostname','hostname1'))))).store('x').createEdgeTraversalWithLabels( 'generic-vnf','allotted-resource', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.PartOf'))).cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void getPserverWithAnEdgeToComplexAndCloudRegion() throws AAIException {
- String aaiQuery = "pserver*('prov-status')(> complex)(> cloud-region)";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('prov-status').where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex')).where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','cloud-region')).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void getPserverWithAnEdgeToComplexButNotToCloudRegion() throws AAIException {
- String aaiQuery = "pserver*('prov-status')(> complex)!(> cloud-region)";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('prov-status').where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex')).where(builder.newInstance().not(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','cloud-region'))).store('x').cap('x').unfold().dedup()";
-
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void nestedUnionQueryTest() throws AAIException {
-
- String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').store('x').union("
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').store('x'))"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x')"
- + ".union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'complex','availability-zone')"
- + ".createEdgeTraversal(EdgeType.TREE, 'availability-zone','cloud-region').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'complex','ctag-pool').store('x').union("
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'ctag-pool','availability-zone').store('x')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'availability-zone','complex').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'ctag-pool','generic-vnf').store('x')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','availability-zone').store('x')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'availability-zone','complex').store('x'),"
- + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'ctag-pool','vpls-pe').store('x')"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'vpls-pe','complex').store('x'))"
- + ".createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').store('x'))"
- + ".createEdgeTraversal(EdgeType.TREE, 'cloud-region','tenant').store('x')"
- + ".cap('x').unfold().dedup()";
-
- String aaiQuery = "generic-vnf*('vnf-id','vnfId') [> pserver* , "
- + " > vserver > pserver* ] > complex* [> availability-zone > cloud-region*,> cloud-region*, " +
- " > ctag-pool* [ > availability-zone* > complex* , > generic-vnf* > availability-zone* > complex*,> vpls-pe* > complex*] > cloud-region*] > tenant* " ;
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
-
- assertEquals(builderQuery, query);
- }
-
- @Test
- public void booleanPropertyValuesTest() throws AAIException {
- String aaiQuery = "cloud-region ('cloud-owner','cloud-owner1') > zone*('in-maint',true)";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','cloud-owner1').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','zone').getVerticesByBooleanProperty('in-maint',true).store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void upperCaseBooleanPropertyValuesTest() throws AAIException {
- String aaiQuery = "cloud-region ('cloud-owner','cloud-owner1') > zone*('in-maint',TRUE)";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','cloud-owner1').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','zone').getVerticesByBooleanProperty('in-maint',true).store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test
- public void booleanPropertyTest() throws AAIException {
- String aaiQuery = "cloud-region ('cloud-owner','cloud-owner1') > zone*('in-maint')";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','cloud-owner1').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','zone').getVerticesByProperty('in-maint').store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- assertEquals(dslQuery, query);
- }
-
- @Test(expected = AAIException.class)
- public void filterOnUnion_vserverFromTentantFromCloudRegion_BadRequest() throws AAIException {
- String aaiQuery = "cloud-region('cloud-owner', 'test-aic')>[tenant*('tenant-id', 'tenant1'), tenant*('tenant-id', 'tenant2')]('tenant-name', 'tenant1')>[vserver*]";
- dslQueryProcessor.parseAaiQuery(QueryVersion.V2,aaiQuery).get("query").toString();
- }
+ @Rule
+ public ExpectedException expectedEx = ExpectedException.none();
+
+ @Test
+ public void dbAliasTest() throws AAIException {
+ String aaiQuery = "logical-link* ('model-invariant-id','invid')";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'logical-link').getVerticesByProperty('model-invariant-id-local','invid')"
+ + ".store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void apostropheTest() throws AAIException {
+ String aaiQuery = "logical-link*('link-id','dsl\\'link')";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'logical-link').getVerticesByProperty('link-id','dsl\\'link')"
+ + ".store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void cloudRegionFromVnf() throws AAIException {
+ String aaiQuery =
+ "generic-vnf*('vnf-name','xyz') [> vnfc* > vserver* [>pserver*, > tenant* > cloud-region*], "
+ + "> vserver* [> pserver*, >tenant* > cloud-region*] ]";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-name','xyz').store('x').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vnfc').store('x')."
+ + "createEdgeTraversal(EdgeType.COUSIN, 'vnfc','vserver').store('x').union(builder.newInstance().createEdgeTraversal"
+ + "(EdgeType.COUSIN, 'vserver','pserver').store('x'),builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'vserver','tenant')"
+ + ".store('x').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region').store('x')),builder.newInstance().createEdgeTraversal"
+ + "(EdgeType.COUSIN, 'generic-vnf','vserver').store('x').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vserver'"
+ + ",'pserver').store('x'),builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').store('x').createEdgeTraversal"
+ + "(EdgeType.TREE, 'tenant','cloud-region').store('x'))).cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void cloudRegionFromVnfWithDirection() throws AAIException {
+ String aaiQuery =
+ "generic-vnf*('vnf-name','xyz') [>> vnfc* >> vserver* [>>pserver*, >> tenant* >> cloud-region*], "
+ + ">> vserver* [>> pserver*, >>tenant* >> cloud-region*] ]";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-name','xyz').store('x').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vnfc').store('x')."
+ + "createEdgeTraversal(EdgeType.COUSIN, 'vnfc','vserver').store('x').union(builder.newInstance().createEdgeTraversal"
+ + "(EdgeType.COUSIN, 'vserver','pserver').store('x'),builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'vserver','tenant')"
+ + ".store('x').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region').store('x')),builder.newInstance().createEdgeTraversal"
+ + "(EdgeType.COUSIN, 'generic-vnf','vserver').store('x').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vserver'"
+ + ",'pserver').store('x'),builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').store('x').createEdgeTraversal"
+ + "(EdgeType.TREE, 'tenant','cloud-region').store('x'))).cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void cloudRegionSites() throws AAIException {
+ String aaiQuery = "cloud-region*('cloud-owner','xyz') > complex*";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner'"
+ + ",'xyz').store('x').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','complex').store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void pserverWithNoComplexTest() throws AAIException {
+ String aaiQuery = "pserver*('hostname','xyz')!(> complex)";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('hostname','xyz').where(builder.newInstance().not("
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex'))).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void pserverWhereNotTest() throws AAIException {
+ String aaiQuery = "pserver('hostname','xyz')>vserver*!(> vnfc > configuration))";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('hostname','xyz').createEdgeTraversal"
+ + "(EdgeType.COUSIN, 'pserver','vserver').where(builder.newInstance().not(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN,"
+ + " 'vserver','vnfc').createEdgeTraversal(EdgeType.COUSIN, 'vnfc','configuration'))).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void singleNode1() throws AAIException {
+ String aaiQuery = "cloud-region* !('cloud-owner','coid')";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
+ + ".store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void singleNodeLimit() throws AAIException {
+ String aaiQuery = "cloud-region* !('cloud-owner','coid') LIMIT 10";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
+ + ".store('x').cap('x').unfold().dedup().limit(10)";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void specialCharacterTest() throws AAIException {
+ String aaiQuery =
+ "cloud-region* !('cloud-owner','coidhello:?_-)(!@#$%^&*+={}[]|/.<,') LIMIT 10";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coidhello:?_-)(!@#$%^&*+={}[]|/.<,')"
+ + ".store('x').cap('x').unfold().dedup().limit(10)";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void singleNodeLimitBlah() throws AAIException {
+ String aaiQuery = "cloud-region* !('cloud-owner','coid') LIMIT blah";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
+ + ".getVerticesByProperty('cloud-region-id','cr id').store('x').cap('x').unfold().dedup().limit(10)";
+
+ expectedEx.expect(AAIException.class);
+ expectedEx.expectMessage("DSL Syntax Error while processing the query");
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ }
+
+ @Test
+ public void singleNodeLimitNull() throws AAIException {
+ String aaiQuery = "cloud-region* !('cloud-owner','coid') LIMIT ";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
+ + ".getVerticesByProperty('cloud-region-id','cr id').store('x').cap('x').unfold().dedup().limit(10)";
+
+ expectedEx.expect(AAIException.class);
+ expectedEx.expectMessage("DSL Syntax Error while processing the query");
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ }
+
+ @Test
+ public void cloudRegion1Test() throws AAIException {
+ String aaiQuery =
+ "cloud-region* !('cloud-owner','coid')('cloud-region-id','cr id') LIMIT 10";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner','coid')"
+ + ".getVerticesByProperty('cloud-region-id','cr id').store('x').cap('x').unfold().dedup().limit(10)";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void cloudRegion_entitlementTest() throws AAIException {
+
+ /*
+ * A store within a where makes no sense
+ */
+ String aaiQuery =
+ "generic-vnf('vnf-id','vnfId') ( > vserver > tenant > cloud-region('cloud-region-id','One')) > entitlement*";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where("
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region')"
+ + ".getVerticesByProperty('cloud-region-id','One'))"
+ + ".createEdgeTraversal(EdgeType.TREE, 'generic-vnf','entitlement').store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void cloudRegion_entitlementTestWithLabels() throws AAIException {
+
+ String aaiQuery =
+ "generic-vnf('vnf-id','vnfId') (> ('tosca.relationships.HostedOn') vserver > ('org.onap.relationships.inventory.BelongsTo') tenant > ('org.onap.relationships.inventory.BelongsTo') cloud-region('cloud-region-id','One')) > ('org.onap.relationships.inventory.ComposedOf')service-instance*";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where("
+ + "builder.newInstance().createEdgeTraversalWithLabels( 'generic-vnf','vserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).createEdgeTraversalWithLabels( 'vserver','tenant', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo'))).createEdgeTraversalWithLabels( 'tenant','cloud-region', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo')))"
+ + ".getVerticesByProperty('cloud-region-id','One'))"
+ + ".createEdgeTraversalWithLabels( 'generic-vnf','service-instance', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.ComposedOf'))).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void complex_az_fromComplexTest() throws AAIException {
+
+ String aaiQuery =
+ "cloud-region('cloud-owner','coid')('cloud-region-id','crid') [> availability-zone* ,> complex*]";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region')"
+ + ".getVerticesByProperty('cloud-owner','coid').getVerticesByProperty('cloud-region-id','crid')"
+ + ".union(builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'cloud-region','availability-zone').store('x')"
+ + ",builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','complex').store('x')).cap('x').unfold().dedup()";
+
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void complex_az_fromComplexTestWithLabels() throws AAIException {
+
+ String aaiQuery =
+ "cloud-region('cloud-owner','coid')('cloud-region-id','crid') [> ('org.onap.relationships.inventory.BelongsTo')availability-zone* ,> ('org.onap.relationships.inventory.LocatedIn')complex*]";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region')"
+ + ".getVerticesByProperty('cloud-owner','coid').getVerticesByProperty('cloud-region-id','crid')"
+ + ".union(builder.newInstance().createEdgeTraversalWithLabels( 'cloud-region','availability-zone', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo'))).store('x')"
+ + ",builder.newInstance().createEdgeTraversalWithLabels( 'cloud-region','complex', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.LocatedIn'))).store('x')).cap('x').unfold().dedup()";
+
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void cloudRegion_fromComplex1Test() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'complex').getVerticesByProperty('data-center-code','data-center-code-name')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').store('x').cap('x').unfold().dedup()";
+ String aaiQuery = "complex('data-center-code','data-center-code-name') > cloud-region*";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void cloudRegion_fromComplex2Test() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'complex').getVerticesByProperty('data-center-code','data-center-code-name')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').getVerticesByProperty('cloud-region-version','crv')"
+ + ".store('x').cap('x').unfold().dedup()";
+ String aaiQuery =
+ "complex('data-center-code','data-center-code-name') > cloud-region*('cloud-region-version','crv')";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void cloudRegion_fromNfTypeTest() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'image').getVerticesByProperty('application-vendor','F5')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'image','vserver')"
+ + ".where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vserver','generic-vnf').getVerticesByProperty('vnf-name','ZALL1MMSC03'))"
+ + ".createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region')"
+ + ".store('x').cap('x').unfold().dedup()";
+
+ String aaiQuery =
+ "image('application-vendor','F5') > vserver (> generic-vnf('vnf-name','ZALL1MMSC03')) > tenant > cloud-region*";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void cloudRegion_fromNfTypeVendorVersionTest() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'image').getVerticesByProperty('application-vendor','vendor')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'image','vserver').where("
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vserver','generic-vnf').getVerticesByProperty('nf-type','nfType')"
+ + ").createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region')"
+ + ".store('x').cap('x').unfold().dedup()";
+
+ String aaiQuery =
+ "image('application-vendor','vendor') > vserver(> generic-vnf('nf-type', 'nfType') ) > tenant > cloud-region*";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void cloud_region_fromVnfTest() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vnfc').store('x')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'vnfc','vserver').store('x')"
+ + ".createEdgeTraversal(EdgeType.TREE, 'vserver','tenant').store('x')"
+ + ".createEdgeTraversal(EdgeType.TREE, 'tenant','cloud-region').store('x')"
+ + ".cap('x').unfold().dedup()";
+
+ String aaiQuery =
+ "generic-vnf('vnf-id','vnfId') > vnfc* > vserver* > tenant* > cloud-region*";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void cloud_region_sitesTest() throws AAIException {
+
+ String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region')."
+ + "getVerticesByProperty('cloud-owner','co').store('x').createEdgeTraversal(EdgeType.COUSIN, "
+ + "'cloud-region','complex').store('x').cap('x').unfold().dedup()";
+
+ String aaiQuery = "cloud-region*('cloud-owner','co') > complex*";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void complex_fromVnf2Test() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').store('x').union("
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').store('x')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x')"
+ + ").cap('x').unfold().dedup()";
+
+ String aaiQuery = "generic-vnf*('vnf-id','vnfId') [ > pserver* > complex*, "
+ + " >vserver > pserver* > complex* " + "]";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void complex_fromVnfTest2() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').store('x').union("
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').store('x'))"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x')"
+ + ".cap('x').unfold().dedup()";
+
+ String aaiQuery = "generic-vnf*('vnf-id','vnfId') [> pserver* , "
+ + " > vserver > pserver* ] > complex*";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void fn_topology1Test() throws AAIException {
+
+ String builderQuery = "builder.getVerticesByProperty('aai-node-type', 'customer')"
+ + ".getVerticesByProperty('global-customer-id','a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb')"
+ + ".createEdgeTraversal(EdgeType.TREE, 'customer','service-subscription').getVerticesByProperty('service-subscription-id','Nimbus')"
+ + ".createEdgeTraversal(EdgeType.TREE, 'service-subscription','service-instance').getVerticesByProperty('service-instance-id','sid')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'service-instance','generic-vnf').store('x')"
+ + ".union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vnfc').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pnf').store('x')).cap('x').unfold().dedup()";
+
+ String aaiQuery =
+ "customer('global-customer-id', 'a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb') > service-subscription('service-subscription-id', 'Nimbus') "
+ + " > service-instance('service-instance-id','sid') > generic-vnf* "
+ + " [> vnfc* ,> vserver*,> pserver* ,> pnf* ]";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void vnf_Dsl() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where(builder.newInstance().union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver')"
+ + ".getVerticesByProperty('hostname','hostname1'),builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').getVerticesByProperty('hostname','hostname1'))).store('x').cap('x').unfold().dedup()";
+
+ String aaiQuery = "generic-vnf*('vnf-id','vnfId') ( [> pserver('hostname','hostname1'), "
+ + " > vserver > pserver('hostname','hostname1')])";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void hasPropertyTest() throws AAIException {
+ String aaiQuery = "cloud-region* ('cloud-owner')";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner').store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void hasPropertyValuesTest() throws AAIException {
+ String aaiQuery = "cloud-region* ('cloud-owner','cloud-owner1','cloud-owner2')";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner', new ArrayList<>(Arrays.asList('cloud-owner1','cloud-owner2'))).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void hasNotPropertyValuesTest() throws AAIException {
+ String aaiQuery = "cloud-region* !('cloud-owner','cloud-owner1','cloud-owner2')";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner', new ArrayList<>(Arrays.asList('cloud-owner1','cloud-owner2'))).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void hasNotPropertyNullValuesTest() throws AAIException {
+ String aaiQuery = "cloud-region* !('cloud-owner',' ',' null ')";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner', new ArrayList<>(Arrays.asList(' ',' null '))).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Ignore
+ @Test
+ public void hasPropertyIntegerTest() throws AAIException {
+ String aaiQuery =
+ "cloud-region('cloud-owner', 'att-nc')('cloud-region-id', 'MTN61a') > vlan-range > vlan-tag*('vlan-id-inner', 20)";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','att-nc').getVerticesByProperty('cloud-region-id','MTN61a')"
+ + ".createEdgeTraversal(EdgeType.TREE, 'cloud-region','vlan-range').createEdgeTraversal(EdgeType.TREE, 'vlan-range','vlan-tag').getVerticesByProperty('vlan-id-inner',20).store('x').cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void directionalityTest() throws AAIException {
+ String aaiQuery = "cloud-region('cloud-region-id','abc') >> complex* >> l3-network*";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-region-id','abc').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','complex').store('x').createEdgeTraversal(EdgeType.COUSIN, 'complex','l3-network').store('x').cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void enterSelectFilterTest() throws AAIException {
+ String aaiQuery = "cloud-region*('cloud-region-id','whp3a'){'cloud-region-id'}";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-region-id','whp3a').store('x').cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(query, dslQuery);
+ }
+
+ @Ignore
+ @Test
+ public void returnSpecificPropsAndAllForDifferentVertices() throws AAIException {
+ String aaiQuery =
+ "cloud-region{'cloud-owner'}('cloud-region-id','new-r111egion-111111') > [ l3-network*, vlan-range > vlan-tag*]";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-region-id','new-r111egion-111111').store('x').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','l3-network').store('x'),builder.newInstance()"
+ + ".createEdgeTraversal(EdgeType.TREE, 'cloud-region','vlan-range').createEdgeTraversal(EdgeType.TREE, 'vlan-range','vlan-tag').store('x')).cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(query, dslQuery);
+ }
+
+ @Test
+ public void groupingAttributesTestForAggregate() throws AAIException {
+ String aaiQuery =
+ "cloud-region{'cloud-owner'}('cloud-owner','att-nc')('cloud-region-id','wah2a') > vip-ipv6-address-list > [subnet{'subnet-name'}, instance-group{'id'}]";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','att-nc').getVerticesByProperty('cloud-region-id','wah2a').store('x').createEdgeTraversal(EdgeType.TREE, 'cloud-region','vip-ipv6-address-list').union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vip-ipv6-address-list','subnet').store('x'),builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'vip-ipv6-address-list','instance-group').store('x')).cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(query, dslQuery);
+ }
+
+ @Test
+ public void multipleEdgeRuleTest() throws AAIException {
+ String aaiQuery = "vserver('vserver-id','abc') > l-interface* > lag-interface*";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'vserver').getVerticesByProperty('vserver-id','abc').createEdgeTraversal(EdgeType.TREE, 'vserver','l-interface').store('x').createEdgeTraversal( 'l-interface','lag-interface').store('x').cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void multipleEdgeRuleTestWithLabels() throws AAIException {
+ String aaiQuery =
+ "vserver('vserver-id','abc') > l-interface* > ('org.onap.relationships.inventory.BelongsTo') lag-interface*";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'vserver').getVerticesByProperty('vserver-id','abc').createEdgeTraversal(EdgeType.TREE, 'vserver','l-interface').store('x').createEdgeTraversalWithLabels( 'l-interface','lag-interface', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.BelongsTo'))).store('x').cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void hasNotPropertyTest() throws AAIException {
+ String aaiQuery = "cloud-region* !('cloud-owner')";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesExcludeByProperty('cloud-owner').store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void overlyNestedQueryTest() throws AAIException {
+ // String aaiQuery = "generic-vnf*('vnf-id','vnfId') (> [ pserver('hostname','hostname1'),
+ // vserver (> [ pserver('hostname','hostname1'), pserver('hostname','hostname1')])]) >
+ // vserver";
+ String aaiQuery =
+ "generic-vnf*('vnf-id','vnfId') ( [> pserver('hostname','hostname1'), > vserver ( [> pserver('hostname','hostname1'), > pserver('hostname','hostname1')])]) > vserver";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where(builder.newInstance().union"
+ + "(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').getVerticesByProperty('hostname','hostname1'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').where(builder.newInstance().union(builder.newInstance()"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').getVerticesByProperty('hostname','hostname1'),builder.newInstance()."
+ + "createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').getVerticesByProperty('hostname','hostname1'))))).store('x').createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void overlyNestedQueryTestWithLabels() throws AAIException {
+ String aaiQuery =
+ "generic-vnf*('vnf-id','vnfId') ( [> ('tosca.relationships.HostedOn')pserver('hostname','hostname1'),> ('tosca.relationships.HostedOn')vserver ( [> ('tosca.relationships.HostedOn')pserver('hostname','hostname1'),> ('tosca.relationships.HostedOn')pserver('hostname','hostname1')])]) > ('org.onap.relationships.inventory.PartOf')allotted-resource";
+
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').where(builder.newInstance().union"
+ + "(builder.newInstance().createEdgeTraversalWithLabels( 'generic-vnf','pserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).getVerticesByProperty('hostname','hostname1'),"
+ + "builder.newInstance().createEdgeTraversalWithLabels( 'generic-vnf','vserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).where(builder.newInstance().union(builder.newInstance()"
+ + ".createEdgeTraversalWithLabels( 'vserver','pserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).getVerticesByProperty('hostname','hostname1'),builder.newInstance()."
+ + "createEdgeTraversalWithLabels( 'vserver','pserver', new ArrayList<>(Arrays.asList('tosca.relationships.HostedOn'))).getVerticesByProperty('hostname','hostname1'))))).store('x').createEdgeTraversalWithLabels( 'generic-vnf','allotted-resource', new ArrayList<>(Arrays.asList('org.onap.relationships.inventory.PartOf'))).cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void getPserverWithAnEdgeToComplexAndCloudRegion() throws AAIException {
+ String aaiQuery = "pserver*('prov-status')(> complex)(> cloud-region)";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('prov-status').where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex')).where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','cloud-region')).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void getPserverWithAnEdgeToComplexButNotToCloudRegion() throws AAIException {
+ String aaiQuery = "pserver*('prov-status')(> complex)!(> cloud-region)";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('prov-status').where(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex')).where(builder.newInstance().not(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'pserver','cloud-region'))).store('x').cap('x').unfold().dedup()";
+
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void nestedUnionQueryTest() throws AAIException {
+
+ String builderQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'generic-vnf').getVerticesByProperty('vnf-id','vnfId').store('x').union("
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','pserver').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','vserver')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'vserver','pserver').store('x'))"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','complex').store('x')"
+ + ".union(builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'complex','availability-zone')"
+ + ".createEdgeTraversal(EdgeType.TREE, 'availability-zone','cloud-region').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.TREE, 'complex','ctag-pool').store('x').union("
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'ctag-pool','availability-zone').store('x')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'availability-zone','complex').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'ctag-pool','generic-vnf').store('x')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'generic-vnf','availability-zone').store('x')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'availability-zone','complex').store('x'),"
+ + "builder.newInstance().createEdgeTraversal(EdgeType.COUSIN, 'ctag-pool','vpls-pe').store('x')"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'vpls-pe','complex').store('x'))"
+ + ".createEdgeTraversal(EdgeType.COUSIN, 'complex','cloud-region').store('x'))"
+ + ".createEdgeTraversal(EdgeType.TREE, 'cloud-region','tenant').store('x')"
+ + ".cap('x').unfold().dedup()";
+
+ String aaiQuery = "generic-vnf*('vnf-id','vnfId') [> pserver* , "
+ + " > vserver > pserver* ] > complex* [> availability-zone > cloud-region*,> cloud-region*, "
+ + " > ctag-pool* [ > availability-zone* > complex* , > generic-vnf* > availability-zone* > complex*,> vpls-pe* > complex*] > cloud-region*] > tenant* ";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+
+ assertEquals(builderQuery, query);
+ }
+
+ @Test
+ public void booleanPropertyValuesTest() throws AAIException {
+ String aaiQuery = "cloud-region ('cloud-owner','cloud-owner1') > zone*('in-maint',true)";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','cloud-owner1').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','zone').getVerticesByBooleanProperty('in-maint',true).store('x').cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void upperCaseBooleanPropertyValuesTest() throws AAIException {
+ String aaiQuery = "cloud-region ('cloud-owner','cloud-owner1') > zone*('in-maint',TRUE)";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','cloud-owner1').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','zone').getVerticesByBooleanProperty('in-maint',true).store('x').cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test
+ public void booleanPropertyTest() throws AAIException {
+ String aaiQuery = "cloud-region ('cloud-owner','cloud-owner1') > zone*('in-maint')";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','cloud-owner1').createEdgeTraversal(EdgeType.COUSIN, 'cloud-region','zone').getVerticesByProperty('in-maint').store('x').cap('x').unfold().dedup()";
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ assertEquals(dslQuery, query);
+ }
+
+ @Test(expected = AAIException.class)
+ public void filterOnUnion_vserverFromTentantFromCloudRegion_BadRequest() throws AAIException {
+ String aaiQuery =
+ "cloud-region('cloud-owner', 'test-aic')>[tenant*('tenant-id', 'tenant1'), tenant*('tenant-id', 'tenant2')]('tenant-name', 'tenant1')>[vserver*]";
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V2, aaiQuery).get("query").toString();
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/dsl/EdgeLabelTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/dsl/EdgeLabelTest.java
index 9664342..808d56b 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/dsl/EdgeLabelTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/dsl/EdgeLabelTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,12 +19,12 @@
*/
package org.onap.aai.rest.dsl;
+import static org.junit.Assert.*;
+
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
-import static org.junit.Assert.*;
-
public class EdgeLabelTest {
private static EdgeLabel edgeLabel;
@@ -32,7 +32,7 @@ public class EdgeLabelTest {
@Before
public void setUp() throws Exception {
- edgeLabel = new EdgeLabel("label", true);
+ edgeLabel = new EdgeLabel("label", true);
edgeLabel1 = new EdgeLabel("org.onap.relationships.inventory.Uses", false);
}
@@ -59,4 +59,4 @@ public class EdgeLabelTest {
public void setExactMatch() {
edgeLabel1.setExactMatch(false);
}
-} \ No newline at end of file
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/dsl/EdgeTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/dsl/EdgeTest.java
index 4378085..77f5c55 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/dsl/EdgeTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/dsl/EdgeTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,20 +19,21 @@
*/
package org.onap.aai.rest.dsl;
-import org.junit.After;
-import org.junit.Before;
-import org.junit.Test;
-import org.onap.aai.rest.enums.EdgeDirection;
+import static org.junit.Assert.*;
import java.util.ArrayList;
import java.util.List;
-import static org.junit.Assert.*;
+import org.junit.After;
+import org.junit.Before;
+import org.junit.Test;
+import org.onap.aai.rest.enums.EdgeDirection;
public class EdgeTest {
Edge edge;
Edge edge2;
+
@Before
public void setUp() throws Exception {
EdgeDirection dir = EdgeDirection.OUT;
@@ -76,4 +77,4 @@ public class EdgeTest {
assertNotNull(edge.getDirection().toString());
assertNotNull(edge.toString());
}
-} \ No newline at end of file
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/dsl/ProdDslTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/dsl/ProdDslTest.java
index 8c52a31..a78bcde 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/dsl/ProdDslTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/dsl/ProdDslTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,40 +19,46 @@
*/
package org.onap.aai.rest.dsl;
-import org.junit.Test;
+import static org.junit.Assert.assertEquals;
+
import org.junit.Ignore;
+import org.junit.Test;
import org.onap.aai.AAISetup;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.rest.enums.QueryVersion;
-import static org.junit.Assert.assertEquals;
-
-//TODO: Change this to read queries and their builder equivalent from a file
-//TODO: Add queries run by SEs
+// TODO: Change this to read queries and their builder equivalent from a file
+// TODO: Add queries run by SEs
public class ProdDslTest extends AAISetup {
@Ignore
@Test
public void msoQueryTest1() throws AAIException {
- String aaiQuery = "cloud-region('cloud-owner', 'value')('cloud-region-id', 'value') > vlan-range > vlan-tag*('vlan-id-outer', '123')";
+ String aaiQuery =
+ "cloud-region('cloud-owner', 'value')('cloud-region-id', 'value') > vlan-range > vlan-tag*('vlan-id-outer', '123')";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','value')"
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'cloud-region').getVerticesByProperty('cloud-owner','value')"
+ ".getVerticesByProperty('cloud-region-id','value').createEdgeTraversal(EdgeType.TREE, 'cloud-region','vlan-range').createEdgeTraversal(EdgeType.TREE, 'vlan-range','vlan-tag')"
+ ".getVerticesByProperty('vlan-id-outer',123).store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
assertEquals(dslQuery, query);
}
@Test
public void msoQueryTest2() throws AAIException {
- String aaiQuery = "pserver('hostname', 'pserver-1') > p-interface > sriov-pf*('pf-pci-id', '0000:ee:00.0')";
+ String aaiQuery =
+ "pserver('hostname', 'pserver-1') > p-interface > sriov-pf*('pf-pci-id', '0000:ee:00.0')";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('hostname','pserver-1')"
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('hostname','pserver-1')"
+ ".createEdgeTraversal(EdgeType.TREE, 'pserver','p-interface')"
+ ".createEdgeTraversal(EdgeType.TREE, 'p-interface','sriov-pf').getVerticesByProperty('pf-pci-id','0000:ee:00.0').store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
assertEquals(dslQuery, query);
}
@@ -60,39 +66,49 @@ public class ProdDslTest extends AAISetup {
public void msoQueryTest3() throws AAIException {
String aaiQuery = "l-interface ('interface-id', 'value') > sriov-vf > sriov-pf*";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'l-interface').getVerticesByProperty('interface-id','value')"
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'l-interface').getVerticesByProperty('interface-id','value')"
+ ".createEdgeTraversal(EdgeType.TREE, 'l-interface','sriov-vf')"
+ ".createEdgeTraversal(EdgeType.COUSIN, 'sriov-vf','sriov-pf').store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
assertEquals(dslQuery, query);
}
- //TODO : Get this from schema
+ // TODO : Get this from schema
@Test
public void msoQueryTest4() throws AAIException {
- //String aaiQuery = "l-interface ('interface-id', 'value') > lag-interface('interface-name', 'bond1') > sriov-pf*";
- String aaiQuery = "l-interface ('interface-id', 'value') > lag-interface('interface-name', 'bond1') > p-interface > sriov-pf*";
+ // String aaiQuery = "l-interface ('interface-id', 'value') >
+ // lag-interface('interface-name', 'bond1') > sriov-pf*";
+ String aaiQuery =
+ "l-interface ('interface-id', 'value') > lag-interface('interface-name', 'bond1') > p-interface > sriov-pf*";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'l-interface').getVerticesByProperty('interface-id','value')"
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'l-interface').getVerticesByProperty('interface-id','value')"
+ ".createEdgeTraversal( 'l-interface','lag-interface').getVerticesByProperty('interface-name','bond1')"
+ ".createEdgeTraversal(EdgeType.COUSIN, 'lag-interface','p-interface').createEdgeTraversal(EdgeType.TREE, 'p-interface','sriov-pf').store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
assertEquals(dslQuery, query);
}
- //TODO : Get this from schema
+ // TODO : Get this from schema
@Test
public void msoQueryTest5() throws AAIException {
- //String aaiQuery = "pserver ('hostname', 'value') > vserver ('vserver-name', 'value') > l-interface > vlan-tag*";
- String aaiQuery = "pserver ('hostname', 'value') > vserver ('vserver-name', 'value') > l-interface > cp > vlan-tag*";
- String dslQuery = "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('hostname','value')"
+ // String aaiQuery = "pserver ('hostname', 'value') > vserver ('vserver-name', 'value') >
+ // l-interface > vlan-tag*";
+ String aaiQuery =
+ "pserver ('hostname', 'value') > vserver ('vserver-name', 'value') > l-interface > cp > vlan-tag*";
+ String dslQuery =
+ "builder.getVerticesByProperty('aai-node-type', 'pserver').getVerticesByProperty('hostname','value')"
+ ".createEdgeTraversal(EdgeType.COUSIN, 'pserver','vserver').getVerticesByProperty('vserver-name','value')"
+ ".createEdgeTraversal(EdgeType.TREE, 'vserver','l-interface').createEdgeTraversal(EdgeType.COUSIN, 'l-interface','cp').createEdgeTraversal(EdgeType.COUSIN, 'cp','vlan-tag').store('x').cap('x').unfold().dedup()";
- String query = dslQueryProcessor.parseAaiQuery(QueryVersion.V1,aaiQuery).get("query").toString();
+ String query =
+ dslQueryProcessor.parseAaiQuery(QueryVersion.V1, aaiQuery).get("query").toString();
assertEquals(dslQuery, query);
}
-} \ No newline at end of file
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/history/AbstractSpringHistoryRestTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/history/AbstractSpringHistoryRestTest.java
index 1d2eac1..5e397dd 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/history/AbstractSpringHistoryRestTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/history/AbstractSpringHistoryRestTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,10 @@
*/
package org.onap.aai.rest.history;
+import java.io.UnsupportedEncodingException;
+import java.util.Base64;
+import java.util.Collections;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.JanusGraph;
@@ -32,8 +36,8 @@ 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.web.server.LocalServerPort;
import org.springframework.boot.test.context.SpringBootTest;
+import org.springframework.boot.web.server.LocalServerPort;
import org.springframework.context.annotation.Import;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
@@ -44,18 +48,12 @@ 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 = TraversalApp.class)
+@SpringBootTest(
+ webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT,
+ classes = TraversalApp.class)
@TestPropertySource(
- locations = "classpath:application-test.properties",
- properties = {
- "history.enabled=true",
- "history.truncate.window.days = " + Integer.MAX_VALUE
- }
-)
+ locations = "classpath:application-test.properties",
+ properties = {"history.enabled=true", "history.truncate.window.days = " + Integer.MAX_VALUE})
@ContextConfiguration(initializers = PropertyPasswordConfiguration.class)
@Import(TraversalTestConfiguration.class)
public abstract class AbstractSpringHistoryRestTest {
@@ -71,14 +69,14 @@ public abstract class AbstractSpringHistoryRestTest {
@Autowired
protected NodeIngestor nodeIngestor;
-
+
@LocalServerPort
protected int randomPort;
protected HttpEntity httpEntity;
protected String baseUrl;
- protected HttpHeaders headers ;
+ protected HttpHeaders headers;
@BeforeClass
public static void setupConfig() throws AAIException {
@@ -109,12 +107,12 @@ public abstract class AbstractSpringHistoryRestTest {
/*
* Inheritors please override this one
*/
- public void createTestGraph(){
-
+ public void createTestGraph() {
+
}
@After
- public void tearDown(){
+ public void tearDown() {
JanusGraph janusGraph = AAIGraph.getInstance().getGraph();
JanusGraphTransaction transaction = janusGraph.newTransaction();
@@ -123,12 +121,11 @@ public abstract class AbstractSpringHistoryRestTest {
try {
GraphTraversalSource g = transaction.traversal();
- g.V().toList()
- .forEach(Vertex::remove);
- } catch(Exception ex){
+ g.V().toList().forEach(Vertex::remove);
+ } catch (Exception ex) {
success = false;
} finally {
- if(success){
+ if (success) {
transaction.commit();
} else {
transaction.rollback();
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/history/CQAllChildernFromPnfStateTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/history/CQAllChildernFromPnfStateTest.java
index 7cf8138..472cffb 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/history/CQAllChildernFromPnfStateTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/history/CQAllChildernFromPnfStateTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,10 +19,18 @@
*/
package org.onap.aai.rest.history;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.*;
+
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+
+import java.util.Arrays;
+import java.util.HashSet;
+import java.util.Set;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.JanusGraphTransaction;
@@ -37,210 +45,149 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
-import java.util.Arrays;
-import java.util.HashSet;
-import java.util.Set;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.*;
-
-@Ignore("The state format requires the history schema to be loaded. " +
- "Because aaigraph is a singleton its very complicated to have 2 different schemas loaded for testing. " +
- "This needs to be addressed.")
+@Ignore("The state format requires the history schema to be loaded. "
+ + "Because aaigraph is a singleton its very complicated to have 2 different schemas loaded for testing. "
+ + "This needs to be addressed.")
public class CQAllChildernFromPnfStateTest extends AbstractSpringHistoryRestTest {
- private static final Logger LOGGER = LoggerFactory.getLogger(CQAllChildernFromPnfStateTest.class);
-
- @Override
- public void createTestGraph() {
- JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
- boolean success = true;
- try {
- GraphTraversalSource g = transaction.traversal();
-
- Vertex pnf1 = g.addV()
- .property(AAIProperties.NODE_TYPE, "pnf",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.AAI_URI, "/network/pnfs/pnf/pnf-1",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.RESOURCE_VERSION, "100",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.START_TS, 100L,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property("pnf-name", "pnf-1",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property("in-maint", false,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property("pnf-id", "pnf-1-id",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .next();
-
- Vertex pint1 = g.addV()
- .property(AAIProperties.NODE_TYPE, "p-interface",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.AAI_URI, "/network/pnfs/pnf/pnf-1/p-interfaces/p-interface/pint-1",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.RESOURCE_VERSION, "100",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.START_TS, 100L,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property("interface-name", "pint-1",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .next();
-
- Vertex lint1 = g.addV()
- .property(AAIProperties.NODE_TYPE, "l-interface",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.AAI_URI, "/network/pnfs/pnf/pnf-1/p-interfaces/p-interface/pint-1/l-interfaces/l-interface/lint-1",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.RESOURCE_VERSION, "100",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.START_TS, 100L,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property("interface-name", "lint-1",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .next();
-
- pint1.addEdge("tosca.relationships.network.BindsTo", pnf1,
- "start-ts", 100L,
- "private", false,
- "aai-uuid", "e713ce2c-62d5-4555-a481-95619cb158aa",
- "prevent-delete", "NONE",
- "delete-other-v", "IN",
- "source-of-truth", "JUNIT-EDGE-C",
- "start-tx-id", "JUNIT-EDGE-C",
- "contains-other-v", "IN");
-
- lint1.addEdge("tosca.relationships.network.BindsTo", pint1,
- "start-ts", 100L,
- "private", false,
- "aai-uuid", "e713ce2c-62d5-4555-a481-95619cb158ab",
- "prevent-delete", "NONE",
- "delete-other-v", "IN",
- "source-of-truth", "JUNIT-EDGE-C",
- "start-tx-id", "JUNIT-EDGE-C",
- "contains-other-v", "IN");
-
- } catch (Exception ex) {
- success = false;
- } finally {
- if (success) {
- transaction.commit();
- } else {
- transaction.rollback();
- fail("Unable to setup the graph");
- }
- }
- }
-
- private JsonArray executeCustomQuery(String endpoint, String queryName, String... startUris) throws Exception {
- JsonObject payload = new JsonObject();
- JsonArray start = new JsonArray();
- Arrays.stream(startUris).forEach(start::add);
- payload.add("start", start);
- payload.addProperty("query", "query/" + queryName);
- httpEntity = new HttpEntity(payload.toString(), headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- JsonArray results = new JsonParser().parse(responseEntity.getBody().toString()).getAsJsonObject().getAsJsonArray("results");
- LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint, responseEntity.getBody());
-
- assertEquals("Expected the response to be 200", HttpStatus.OK, responseEntity.getStatusCode());
- return results;
- }
-
- private JsonArray executeGremlin(String endpoint, String query) throws Exception {
- JsonObject payload = new JsonObject();
- payload.addProperty("gremlin", query);
- httpEntity = new HttpEntity(payload.toString(), headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- JsonArray results = new JsonParser().parse(responseEntity.getBody().toString()).getAsJsonObject().getAsJsonArray("results");
- LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint, responseEntity.getBody());
-
- assertEquals("Expected the response to be 200", HttpStatus.OK, responseEntity.getStatusCode());
- return results;
- }
-
- private void verifyResultUris(JsonArray results, String... uris) {
- Set<String> expected = new HashSet<>(Arrays.asList(uris));
- final Set<String> actualEquipType = new HashSet<>();
- for (JsonElement result : results) {
- actualEquipType.add(result.getAsJsonObject().get("uri").getAsString());
- }
- assertThat("Verify results uri's", actualEquipType, is(expected));
- }
-
-
- @Test
- public void pnfChildrenQueryTest() throws Exception {
- JsonArray results = executeCustomQuery("/aai/v14/query?format=state", "allchildren-fromPnf", "/network/pnfs/pnf/pnf-1");
- verifyResultUris(results, "/network/pnfs/pnf/pnf-1", "/network/pnfs/pnf/pnf-1/p-interfaces/p-interface/pint-1", "/network/pnfs/pnf/pnf-1/p-interfaces/p-interface/pint-1/l-interfaces/l-interface/lint-1");
- }
-
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(CQAllChildernFromPnfStateTest.class);
+
+ @Override
+ public void createTestGraph() {
+ JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
+ boolean success = true;
+ try {
+ GraphTraversalSource g = transaction.traversal();
+
+ Vertex pnf1 = g.addV()
+ .property(AAIProperties.NODE_TYPE, "pnf", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.AAI_URI, "/network/pnfs/pnf/pnf-1",
+ AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C",
+ AAIProperties.START_TS, 100L)
+ .property(AAIProperties.RESOURCE_VERSION, "100", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.START_TS, 100L, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("pnf-name", "pnf-1", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("in-maint", false, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("pnf-id", "pnf-1-id", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .next();
+
+ Vertex pint1 = g.addV()
+ .property(AAIProperties.NODE_TYPE, "p-interface", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.AAI_URI,
+ "/network/pnfs/pnf/pnf-1/p-interfaces/p-interface/pint-1",
+ AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C",
+ AAIProperties.START_TS, 100L)
+ .property(AAIProperties.RESOURCE_VERSION, "100", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.START_TS, 100L, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("interface-name", "pint-1", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .next();
+
+ Vertex lint1 = g.addV()
+ .property(AAIProperties.NODE_TYPE, "l-interface", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.AAI_URI,
+ "/network/pnfs/pnf/pnf-1/p-interfaces/p-interface/pint-1/l-interfaces/l-interface/lint-1",
+ AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C",
+ AAIProperties.START_TS, 100L)
+ .property(AAIProperties.RESOURCE_VERSION, "100", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.START_TS, 100L, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("interface-name", "lint-1", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .next();
+
+ pint1.addEdge("tosca.relationships.network.BindsTo", pnf1, "start-ts", 100L, "private",
+ false, "aai-uuid", "e713ce2c-62d5-4555-a481-95619cb158aa", "prevent-delete", "NONE",
+ "delete-other-v", "IN", "source-of-truth", "JUNIT-EDGE-C", "start-tx-id",
+ "JUNIT-EDGE-C", "contains-other-v", "IN");
+
+ lint1.addEdge("tosca.relationships.network.BindsTo", pint1, "start-ts", 100L, "private",
+ false, "aai-uuid", "e713ce2c-62d5-4555-a481-95619cb158ab", "prevent-delete", "NONE",
+ "delete-other-v", "IN", "source-of-truth", "JUNIT-EDGE-C", "start-tx-id",
+ "JUNIT-EDGE-C", "contains-other-v", "IN");
+
+ } catch (Exception ex) {
+ success = false;
+ } finally {
+ if (success) {
+ transaction.commit();
+ } else {
+ transaction.rollback();
+ fail("Unable to setup the graph");
+ }
+ }
+ }
+
+ private JsonArray executeCustomQuery(String endpoint, String queryName, String... startUris)
+ throws Exception {
+ JsonObject payload = new JsonObject();
+ JsonArray start = new JsonArray();
+ Arrays.stream(startUris).forEach(start::add);
+ payload.add("start", start);
+ payload.addProperty("query", "query/" + queryName);
+ httpEntity = new HttpEntity(payload.toString(), headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ JsonArray results = new JsonParser().parse(responseEntity.getBody().toString())
+ .getAsJsonObject().getAsJsonArray("results");
+ LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint,
+ responseEntity.getBody());
+
+ assertEquals("Expected the response to be 200", HttpStatus.OK,
+ responseEntity.getStatusCode());
+ return results;
+ }
+
+ private JsonArray executeGremlin(String endpoint, String query) throws Exception {
+ JsonObject payload = new JsonObject();
+ payload.addProperty("gremlin", query);
+ httpEntity = new HttpEntity(payload.toString(), headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ JsonArray results = new JsonParser().parse(responseEntity.getBody().toString())
+ .getAsJsonObject().getAsJsonArray("results");
+ LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint,
+ responseEntity.getBody());
+
+ assertEquals("Expected the response to be 200", HttpStatus.OK,
+ responseEntity.getStatusCode());
+ return results;
+ }
+
+ private void verifyResultUris(JsonArray results, String... uris) {
+ Set<String> expected = new HashSet<>(Arrays.asList(uris));
+ final Set<String> actualEquipType = new HashSet<>();
+ for (JsonElement result : results) {
+ actualEquipType.add(result.getAsJsonObject().get("uri").getAsString());
+ }
+ assertThat("Verify results uri's", actualEquipType, is(expected));
+ }
+
+ @Test
+ public void pnfChildrenQueryTest() throws Exception {
+ JsonArray results = executeCustomQuery("/aai/v14/query?format=state", "allchildren-fromPnf",
+ "/network/pnfs/pnf/pnf-1");
+ verifyResultUris(results, "/network/pnfs/pnf/pnf-1",
+ "/network/pnfs/pnf/pnf-1/p-interfaces/p-interface/pint-1",
+ "/network/pnfs/pnf/pnf-1/p-interfaces/p-interface/pint-1/l-interfaces/l-interface/lint-1");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryLifecycleEdgeTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryLifecycleEdgeTest.java
index 5b2c8da..d26eff2 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryLifecycleEdgeTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryLifecycleEdgeTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,10 +19,16 @@
*/
package org.onap.aai.rest.history;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.*;
+
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+
+import java.util.*;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.JanusGraphTransaction;
@@ -38,439 +44,370 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
-import java.util.*;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.*;
-
-@Ignore("The lifecycle format requires the history schema to be loaded. " +
- "Because aaigraph is a singleton its very complicated to have 2 different schemas loaded for testing. " +
- "This needs to be addressed.")
+@Ignore("The lifecycle format requires the history schema to be loaded. "
+ + "Because aaigraph is a singleton its very complicated to have 2 different schemas loaded for testing. "
+ + "This needs to be addressed.")
public class DslConsumerHistoryLifecycleEdgeTest extends AbstractSpringHistoryRestTest {
- private static final Logger LOGGER = LoggerFactory.getLogger(DslConsumerHistoryLifecycleEdgeTest.class);
-
- @Override
- public void createTestGraph() {
- JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
- boolean success = true;
- try {
- GraphTraversalSource g = transaction.traversal();
-
- Vertex pserver = g.addV().property(AAIProperties.NODE_TYPE, "pserver",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/test-pserver-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.RESOURCE_VERSION, "100",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property("hostname", "test-pserver-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property("in-maint", false,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property("equip-type", "ps-type",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.START_TS, 100L,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .next();
- Vertex complex = g.addV().property(AAIProperties.NODE_TYPE, "complex",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/complexes/complex/test-complex-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.RESOURCE_VERSION, "100",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property("physical-location-id", "test-complex-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property("street", "200 S. Laurel Ave",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property("city", "Middletown",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property("state", "NJ",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property("zip", "11111",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.START_TS, 100L,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C" ,
- AAIProperties.START_TS, 100L
- )
- .next();
-
- pserver.addEdge("org.onap.relationships.inventory.LocatedIn",
- complex,
- "start-ts", 100,
- "private", false,
- "aai-uuid", "edge1",
- "end-source-of-truth", "JUNIT-E-D-1",
- "end-tx-id", "JUNIT-E-D-1",
- "end-ts", 300,
- "prevent-delete", "IN",
- "delete-other-v", "NONE",
- "source-of-truth", "JUNIT-E-C-1",
- "start-tx-id", "JUNIT-E-C-1",
- "contains-other-v", "NONE"
- );
- pserver.addEdge("org.onap.relationships.inventory.LocatedIn",
- complex,
- "start-ts", 500,
- "private", false,
- "aai-uuid", "edge2",
- "end-source-of-truth", "JUNIT-E-D-2",
- "end-tx-id", "JUNIT-E-D-2",
- "end-ts", 700,
- "prevent-delete", "IN",
- "delete-other-v", "NONE",
- "source-of-truth", "JUNIT-E-C-2",
- "start-tx-id", "JUNIT-E-C-2",
- "contains-other-v", "NONE"
- );
- pserver.addEdge("org.onap.relationships.inventory.LocatedIn",
- complex,
- "start-ts", 900,
- "private", false,
- "aai-uuid", "edge3",
- "end-source-of-truth", "JUNIT-E-D-3",
- "end-tx-id", "JUNIT-E-D-3",
- "end-ts", 1100,
- "prevent-delete", "IN",
- "delete-other-v", "NONE",
- "source-of-truth", "JUNIT-E-C-3",
- "start-tx-id", "JUNIT-E-C-3",
- "contains-other-v", "NONE"
- );
- pserver.addEdge("org.onap.relationships.inventory.LocatedIn",
- complex,
- "start-ts", 1300,
- "private", false,
- "aai-uuid", "edge3",
- "prevent-delete", "IN",
- "delete-other-v", "NONE",
- "source-of-truth", "JUNIT-E-C-3",
- "start-tx-id", "JUNIT-E-C-3",
- "contains-other-v", "NONE"
- );
- } catch (Exception ex) {
- success = false;
- } finally {
- if (success) {
- transaction.commit();
- } else {
- transaction.rollback();
- fail("Unable to setup the graph");
- }
- }
- }
-
- private JsonArray getResultsForPserverLookupByHostname(String endpoint) throws Exception {
- return getResultsForPserverLookupByHostnameAndAnother(endpoint, "");
- }
-
- private JsonArray getResultsForPserverLookupByHostnameAndAnother(String endpoint, String additionalFilterInParen) throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver*('hostname','test-pserver-dsl')" + additionalFilterInParen);
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- JsonArray results = new JsonParser().parse(responseEntity.getBody().toString()).getAsJsonObject().getAsJsonArray("results");
- LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint, responseEntity.getBody());
-
- assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
- assertEquals("Expected the response to be 200", HttpStatus.OK, responseEntity.getStatusCode());
- return results;
- }
-
-
- private void verifyEquipTypeValues(JsonArray results, String... expectedEquipTypes) {
- List<String> expected = Arrays.asList(expectedEquipTypes);
- final List<String> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- if (property.getAsJsonObject().has("value") && !property.getAsJsonObject().get("value").isJsonNull()) {
- actualEquipType.add(property.getAsJsonObject().get("value").getAsString());
- } else {
- actualEquipType.add(null);
- }
- }
- }
- }
- assertThat("Verify equip-type in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyEquipTypeSoTs(JsonArray results, String... expectedSTOs) {
- List<String> expected = Arrays.asList(expectedSTOs);
- final List<String> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- if (property.getAsJsonObject().has("sot") && !property.getAsJsonObject().get("sot").isJsonNull()) {
- actualEquipType.add(property.getAsJsonObject().get("sot").getAsString());
- } else {
- actualEquipType.add(null);
- }
- }
- }
- }
- assertThat("Verify equip-type SoTs in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyEquipTypeTxId(JsonArray results, String... expectedSTOs) {
- List<String> expected = Arrays.asList(expectedSTOs);
- final List<String> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- if (property.getAsJsonObject().has("tx-id") && !property.getAsJsonObject().get("tx-id").isJsonNull()) {
- actualEquipType.add(property.getAsJsonObject().get("tx-id").getAsString());
- } else {
- actualEquipType.add(null);
- }
- }
- }
- }
- assertThat("Verify equip-type tx-ids in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyEquipTypeTimestamps(JsonArray results, Long... expectedSTOs) {
- List<Long> expected = Arrays.asList(expectedSTOs);
- final List<Long> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- if (property.getAsJsonObject().has("timestamp") && !property.getAsJsonObject().get("timestamp").isJsonNull()) {
- actualEquipType.add(property.getAsJsonObject().get("timestamp").getAsLong());
- } else {
- actualEquipType.add(null);
- }
- }
- }
- }
- assertThat("Verify equip-type timestamps in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyNodeTimestamps(JsonArray results, Long... nodeTimestamps) {
- List<Long> expected = Arrays.asList(nodeTimestamps);
- final List<Long> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- result.getAsJsonObject().get("node-actions").getAsJsonArray().forEach(jsonElement ->
- actualEquipType.add(jsonElement.getAsJsonObject().get("timestamp").getAsLong()));
- }
- assertThat("Verify node-changes timestamps in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyRelatedToCreatedTimestamps(JsonArray results, Long... edgeCreatedTimestamps) {
- List<Long> expected = Arrays.asList(edgeCreatedTimestamps);
- final List<Long> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- result.getAsJsonObject().get("related-to").getAsJsonArray().forEach(jsonElement -> {
- if (jsonElement.getAsJsonObject().has("timestamp")) {
- actualEquipType.add(jsonElement.getAsJsonObject().get("timestamp").getAsLong());
- }
- });
- }
- assertThat("Verify related-to createdtimestamps in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyRelatedToCreatedDeletedTimestamps(JsonArray results, Long... edgeDeletedTimestamps) {
- List<Long> expected = Arrays.asList(edgeDeletedTimestamps);
- final List<Long> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- result.getAsJsonObject().get("related-to").getAsJsonArray().forEach(jsonElement -> {
- if (jsonElement.getAsJsonObject().has("end-timestamp")) {
- actualEquipType.add(jsonElement.getAsJsonObject().get("end-timestamp").getAsLong());
- }
- });
- }
- assertThat("Verify related-to createdtimestamps in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyRelatedToCount(JsonArray results, int expectedSize) {
- int actualSize = 0;
- for (JsonElement result : results) {
- actualSize += result.getAsJsonObject().get("related-to").getAsJsonArray().size();
- }
- assertEquals("Verify related-to count", actualSize, expectedSize);
- }
-
- private void verifyRelatedToTxId(JsonArray results) {
- final Set<JsonObject> withTxId = new HashSet<>();
- int count = 0;
- for (JsonElement result : results) {
- count += result.getAsJsonObject().get("related-to").getAsJsonArray().size();
- result.getAsJsonObject().get("related-to").getAsJsonArray().forEach(jsonElement -> {
- if (jsonElement.getAsJsonObject().has("tx-id")) {
- withTxId.add(jsonElement.getAsJsonObject());
- }
- if (jsonElement.getAsJsonObject().has("end-tx-id")) {
- withTxId.add(jsonElement.getAsJsonObject());
- }
- });
- }
- assertEquals("Verify no related-to has end-tx-id in state", count, withTxId.size());
- }
-
-
- @Test
- public void lifecycleQueryStartTsBeforeCreationTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=50";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, "ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-C");
- verifyEquipTypeTimestamps(results, 100L);
- verifyNodeTimestamps(results, 100L);
- verifyRelatedToCreatedTimestamps(results, 100L, 500L, 900L, 1300L);
- verifyRelatedToCreatedDeletedTimestamps(results, 300L, 700L, 1100L);
- verifyRelatedToCount(results, 4);
- verifyRelatedToTxId(results);
- }
-
-
-
- @Test
- public void lifecycleQueryStartTsBeforeSecondEdgeCreationTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=400";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results);
- verifyEquipTypeSoTs(results);
- verifyEquipTypeTxId(results);
- verifyEquipTypeTimestamps(results);
- verifyNodeTimestamps(results);
- verifyRelatedToCreatedTimestamps(results, 500L, 900L, 1300L);
- verifyRelatedToCreatedDeletedTimestamps(results, 700L, 1100L);
- verifyRelatedToCount(results, 3);
- verifyRelatedToTxId(results);
- }
-
- @Test
- public void lifecycleQueryStartTsAtSecondEdgeDeletionTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=700";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results);
- verifyEquipTypeSoTs(results);
- verifyEquipTypeTxId(results);
- verifyEquipTypeTimestamps(results);
- verifyNodeTimestamps(results);
- verifyRelatedToCreatedTimestamps(results, 900L, 1300L);
- verifyRelatedToCreatedDeletedTimestamps(results, 700L, 1100L);
- verifyRelatedToCount(results, 3);
- verifyRelatedToTxId(results);
- }
-
- @Test
- public void lifecycleQueryStartTsAfterSecondEdgeDeletionTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=800";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results);
- verifyEquipTypeSoTs(results);
- verifyEquipTypeTxId(results);
- verifyEquipTypeTimestamps(results);
- verifyNodeTimestamps(results);
- verifyRelatedToCreatedTimestamps(results, 900L, 1300L);
- verifyRelatedToCreatedDeletedTimestamps(results, 1100L);
- verifyRelatedToCount(results, 2);
- verifyRelatedToTxId(results);
- }
-
- @Test
- public void lifecycleQueryStartTsAtLastEdgeActionTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=1300";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results);
- verifyEquipTypeSoTs(results);
- verifyEquipTypeTxId(results);
- verifyEquipTypeTimestamps(results);
- verifyNodeTimestamps(results);
- verifyRelatedToCreatedTimestamps(results, 1300L);
- verifyRelatedToCreatedDeletedTimestamps(results);
- verifyRelatedToCount(results, 1);
- verifyRelatedToTxId(results);
- }
-
- @Test
- public void lifecycleQueryStartTsAfterLastEdgeActionTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=1400";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 0, results.size());
-
- verifyEquipTypeValues(results);
- verifyEquipTypeSoTs(results);
- verifyEquipTypeTxId(results);
- verifyEquipTypeTimestamps(results);
- verifyNodeTimestamps(results);
- verifyRelatedToCreatedTimestamps(results);
- verifyRelatedToCreatedDeletedTimestamps(results);
- verifyRelatedToCount(results, 0);
- verifyRelatedToTxId(results);
- }
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(DslConsumerHistoryLifecycleEdgeTest.class);
+
+ @Override
+ public void createTestGraph() {
+ JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
+ boolean success = true;
+ try {
+ GraphTraversalSource g = transaction.traversal();
+
+ Vertex pserver = g.addV()
+ .property(AAIProperties.NODE_TYPE, "pserver", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.AAI_URI,
+ "/cloud-infrastructure/pservers/pserver/test-pserver-dsl",
+ AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C",
+ AAIProperties.START_TS, 100L)
+ .property(AAIProperties.RESOURCE_VERSION, "100", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("hostname", "test-pserver-dsl", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("in-maint", false, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("equip-type", "ps-type", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.START_TS, 100L, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .next();
+ Vertex complex = g.addV()
+ .property(AAIProperties.NODE_TYPE, "complex", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.AAI_URI,
+ "/cloud-infrastructure/complexes/complex/test-complex-dsl",
+ AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C",
+ AAIProperties.START_TS, 100L)
+ .property(AAIProperties.RESOURCE_VERSION, "100", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("physical-location-id", "test-complex-dsl", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("street", "200 S. Laurel Ave", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("city", "Middletown", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("state", "NJ", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("zip", "11111", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.START_TS, 100L, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .next();
+
+ pserver.addEdge("org.onap.relationships.inventory.LocatedIn", complex, "start-ts", 100,
+ "private", false, "aai-uuid", "edge1", "end-source-of-truth", "JUNIT-E-D-1",
+ "end-tx-id", "JUNIT-E-D-1", "end-ts", 300, "prevent-delete", "IN", "delete-other-v",
+ "NONE", "source-of-truth", "JUNIT-E-C-1", "start-tx-id", "JUNIT-E-C-1",
+ "contains-other-v", "NONE");
+ pserver.addEdge("org.onap.relationships.inventory.LocatedIn", complex, "start-ts", 500,
+ "private", false, "aai-uuid", "edge2", "end-source-of-truth", "JUNIT-E-D-2",
+ "end-tx-id", "JUNIT-E-D-2", "end-ts", 700, "prevent-delete", "IN", "delete-other-v",
+ "NONE", "source-of-truth", "JUNIT-E-C-2", "start-tx-id", "JUNIT-E-C-2",
+ "contains-other-v", "NONE");
+ pserver.addEdge("org.onap.relationships.inventory.LocatedIn", complex, "start-ts", 900,
+ "private", false, "aai-uuid", "edge3", "end-source-of-truth", "JUNIT-E-D-3",
+ "end-tx-id", "JUNIT-E-D-3", "end-ts", 1100, "prevent-delete", "IN",
+ "delete-other-v", "NONE", "source-of-truth", "JUNIT-E-C-3", "start-tx-id",
+ "JUNIT-E-C-3", "contains-other-v", "NONE");
+ pserver.addEdge("org.onap.relationships.inventory.LocatedIn", complex, "start-ts", 1300,
+ "private", false, "aai-uuid", "edge3", "prevent-delete", "IN", "delete-other-v",
+ "NONE", "source-of-truth", "JUNIT-E-C-3", "start-tx-id", "JUNIT-E-C-3",
+ "contains-other-v", "NONE");
+ } catch (Exception ex) {
+ success = false;
+ } finally {
+ if (success) {
+ transaction.commit();
+ } else {
+ transaction.rollback();
+ fail("Unable to setup the graph");
+ }
+ }
+ }
+
+ private JsonArray getResultsForPserverLookupByHostname(String endpoint) throws Exception {
+ return getResultsForPserverLookupByHostnameAndAnother(endpoint, "");
+ }
+
+ private JsonArray getResultsForPserverLookupByHostnameAndAnother(String endpoint,
+ String additionalFilterInParen) throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "pserver*('hostname','test-pserver-dsl')" + additionalFilterInParen);
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ JsonArray results = new JsonParser().parse(responseEntity.getBody().toString())
+ .getAsJsonObject().getAsJsonArray("results");
+ LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint,
+ responseEntity.getBody());
+
+ assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
+ assertEquals("Expected the response to be 200", HttpStatus.OK,
+ responseEntity.getStatusCode());
+ return results;
+ }
+
+ private void verifyEquipTypeValues(JsonArray results, String... expectedEquipTypes) {
+ List<String> expected = Arrays.asList(expectedEquipTypes);
+ final List<String> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ if (property.getAsJsonObject().has("value")
+ && !property.getAsJsonObject().get("value").isJsonNull()) {
+ actualEquipType.add(property.getAsJsonObject().get("value").getAsString());
+ } else {
+ actualEquipType.add(null);
+ }
+ }
+ }
+ }
+ assertThat("Verify equip-type in lifecycle", actualEquipType, is(expected));
+ }
+
+ private void verifyEquipTypeSoTs(JsonArray results, String... expectedSTOs) {
+ List<String> expected = Arrays.asList(expectedSTOs);
+ final List<String> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ if (property.getAsJsonObject().has("sot")
+ && !property.getAsJsonObject().get("sot").isJsonNull()) {
+ actualEquipType.add(property.getAsJsonObject().get("sot").getAsString());
+ } else {
+ actualEquipType.add(null);
+ }
+ }
+ }
+ }
+ assertThat("Verify equip-type SoTs in lifecycle", actualEquipType, is(expected));
+ }
+
+ private void verifyEquipTypeTxId(JsonArray results, String... expectedSTOs) {
+ List<String> expected = Arrays.asList(expectedSTOs);
+ final List<String> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ if (property.getAsJsonObject().has("tx-id")
+ && !property.getAsJsonObject().get("tx-id").isJsonNull()) {
+ actualEquipType.add(property.getAsJsonObject().get("tx-id").getAsString());
+ } else {
+ actualEquipType.add(null);
+ }
+ }
+ }
+ }
+ assertThat("Verify equip-type tx-ids in lifecycle", actualEquipType, is(expected));
+ }
+
+ private void verifyEquipTypeTimestamps(JsonArray results, Long... expectedSTOs) {
+ List<Long> expected = Arrays.asList(expectedSTOs);
+ final List<Long> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ if (property.getAsJsonObject().has("timestamp")
+ && !property.getAsJsonObject().get("timestamp").isJsonNull()) {
+ actualEquipType
+ .add(property.getAsJsonObject().get("timestamp").getAsLong());
+ } else {
+ actualEquipType.add(null);
+ }
+ }
+ }
+ }
+ assertThat("Verify equip-type timestamps in lifecycle", actualEquipType, is(expected));
+ }
+
+ private void verifyNodeTimestamps(JsonArray results, Long... nodeTimestamps) {
+ List<Long> expected = Arrays.asList(nodeTimestamps);
+ final List<Long> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ result.getAsJsonObject().get("node-actions").getAsJsonArray()
+ .forEach(jsonElement -> actualEquipType
+ .add(jsonElement.getAsJsonObject().get("timestamp").getAsLong()));
+ }
+ assertThat("Verify node-changes timestamps in lifecycle", actualEquipType, is(expected));
+ }
+
+ private void verifyRelatedToCreatedTimestamps(JsonArray results,
+ Long... edgeCreatedTimestamps) {
+ List<Long> expected = Arrays.asList(edgeCreatedTimestamps);
+ final List<Long> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ result.getAsJsonObject().get("related-to").getAsJsonArray().forEach(jsonElement -> {
+ if (jsonElement.getAsJsonObject().has("timestamp")) {
+ actualEquipType.add(jsonElement.getAsJsonObject().get("timestamp").getAsLong());
+ }
+ });
+ }
+ assertThat("Verify related-to createdtimestamps in lifecycle", actualEquipType,
+ is(expected));
+ }
+
+ private void verifyRelatedToCreatedDeletedTimestamps(JsonArray results,
+ Long... edgeDeletedTimestamps) {
+ List<Long> expected = Arrays.asList(edgeDeletedTimestamps);
+ final List<Long> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ result.getAsJsonObject().get("related-to").getAsJsonArray().forEach(jsonElement -> {
+ if (jsonElement.getAsJsonObject().has("end-timestamp")) {
+ actualEquipType
+ .add(jsonElement.getAsJsonObject().get("end-timestamp").getAsLong());
+ }
+ });
+ }
+ assertThat("Verify related-to createdtimestamps in lifecycle", actualEquipType,
+ is(expected));
+ }
+
+ private void verifyRelatedToCount(JsonArray results, int expectedSize) {
+ int actualSize = 0;
+ for (JsonElement result : results) {
+ actualSize += result.getAsJsonObject().get("related-to").getAsJsonArray().size();
+ }
+ assertEquals("Verify related-to count", actualSize, expectedSize);
+ }
+
+ private void verifyRelatedToTxId(JsonArray results) {
+ final Set<JsonObject> withTxId = new HashSet<>();
+ int count = 0;
+ for (JsonElement result : results) {
+ count += result.getAsJsonObject().get("related-to").getAsJsonArray().size();
+ result.getAsJsonObject().get("related-to").getAsJsonArray().forEach(jsonElement -> {
+ if (jsonElement.getAsJsonObject().has("tx-id")) {
+ withTxId.add(jsonElement.getAsJsonObject());
+ }
+ if (jsonElement.getAsJsonObject().has("end-tx-id")) {
+ withTxId.add(jsonElement.getAsJsonObject());
+ }
+ });
+ }
+ assertEquals("Verify no related-to has end-tx-id in state", count, withTxId.size());
+ }
+
+ @Test
+ public void lifecycleQueryStartTsBeforeCreationTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=50";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, "ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 100L);
+ verifyNodeTimestamps(results, 100L);
+ verifyRelatedToCreatedTimestamps(results, 100L, 500L, 900L, 1300L);
+ verifyRelatedToCreatedDeletedTimestamps(results, 300L, 700L, 1100L);
+ verifyRelatedToCount(results, 4);
+ verifyRelatedToTxId(results);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsBeforeSecondEdgeCreationTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=400";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results);
+ verifyEquipTypeSoTs(results);
+ verifyEquipTypeTxId(results);
+ verifyEquipTypeTimestamps(results);
+ verifyNodeTimestamps(results);
+ verifyRelatedToCreatedTimestamps(results, 500L, 900L, 1300L);
+ verifyRelatedToCreatedDeletedTimestamps(results, 700L, 1100L);
+ verifyRelatedToCount(results, 3);
+ verifyRelatedToTxId(results);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAtSecondEdgeDeletionTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=700";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results);
+ verifyEquipTypeSoTs(results);
+ verifyEquipTypeTxId(results);
+ verifyEquipTypeTimestamps(results);
+ verifyNodeTimestamps(results);
+ verifyRelatedToCreatedTimestamps(results, 900L, 1300L);
+ verifyRelatedToCreatedDeletedTimestamps(results, 700L, 1100L);
+ verifyRelatedToCount(results, 3);
+ verifyRelatedToTxId(results);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAfterSecondEdgeDeletionTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=800";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results);
+ verifyEquipTypeSoTs(results);
+ verifyEquipTypeTxId(results);
+ verifyEquipTypeTimestamps(results);
+ verifyNodeTimestamps(results);
+ verifyRelatedToCreatedTimestamps(results, 900L, 1300L);
+ verifyRelatedToCreatedDeletedTimestamps(results, 1100L);
+ verifyRelatedToCount(results, 2);
+ verifyRelatedToTxId(results);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAtLastEdgeActionTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=1300";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results);
+ verifyEquipTypeSoTs(results);
+ verifyEquipTypeTxId(results);
+ verifyEquipTypeTimestamps(results);
+ verifyNodeTimestamps(results);
+ verifyRelatedToCreatedTimestamps(results, 1300L);
+ verifyRelatedToCreatedDeletedTimestamps(results);
+ verifyRelatedToCount(results, 1);
+ verifyRelatedToTxId(results);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAfterLastEdgeActionTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=1400";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 0, results.size());
+
+ verifyEquipTypeValues(results);
+ verifyEquipTypeSoTs(results);
+ verifyEquipTypeTxId(results);
+ verifyEquipTypeTimestamps(results);
+ verifyNodeTimestamps(results);
+ verifyRelatedToCreatedTimestamps(results);
+ verifyRelatedToCreatedDeletedTimestamps(results);
+ verifyRelatedToCount(results, 0);
+ verifyRelatedToTxId(results);
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryLifecycleNodeDeletedThenRecreatedTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryLifecycleNodeDeletedThenRecreatedTest.java
index 25e9e84..dc794b8 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryLifecycleNodeDeletedThenRecreatedTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryLifecycleNodeDeletedThenRecreatedTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,9 +19,15 @@
*/
package org.onap.aai.rest.history;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.*;
+
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
+
+import java.util.*;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.janusgraph.core.JanusGraphTransaction;
import org.junit.Ignore;
@@ -36,709 +42,668 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
-import java.util.*;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.*;
-
-@Ignore("The lifecycle format requires the history schema to be loaded. " +
- "Because aaigraph is a singleton its very complicated to have 2 different schemas loaded for testing. " +
- "This needs to be addressed.")
-public class DslConsumerHistoryLifecycleNodeDeletedThenRecreatedTest extends AbstractSpringHistoryRestTest {
-
- private static final Logger LOGGER = LoggerFactory.getLogger(DslConsumerHistoryLifecycleNodeDeletedThenRecreatedTest.class);
-
- @Override
- public void createTestGraph() {
- JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
- boolean success = true;
- try {
- GraphTraversalSource g = transaction.traversal();
- /*
- Pserver
- - created pserver @ time 100
- - equip-type = first-ps-type
- - update equip-type @ 500
- - equip-type = first-ps-type-update
- - deleted pserver @ time 1000
- */
- g.addV().property(AAIProperties.NODE_TYPE, "pserver",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/test-pserver-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.RESOURCE_VERSION, "100",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-U",
- AAIProperties.END_TX_ID, "JUNIT-U",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 500L
- )
- .property(AAIProperties.RESOURCE_VERSION, "500",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U",
- AAIProperties.START_TX_ID, "JUNIT-U",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 500L,
- AAIProperties.END_TS, 1000L
- )
- .property("hostname", "test-pserver-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property("in-maint", false,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property("equip-type", "first-ps-type",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-U",
- AAIProperties.END_TX_ID, "JUNIT-U",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 500L
- )
- .property("equip-type", "first-ps-type-update",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U",
- AAIProperties.START_TX_ID, "JUNIT-U",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 500L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-D",
- AAIProperties.START_TX_ID, "JUNIT-D",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.START_TS, 100L,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.END_TS, 1000L,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-D",
- AAIProperties.START_TX_ID, "JUNIT-D",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 1000L,
- AAIProperties.END_TS, 1000L
- )
- .next();
-
- /*
- Pserver
- - created pserver @ time 10000
- - equip-type = second-ps-type
- - delete equip-type @ 13000
- - recreate equip-type @ 15000
- - equip-type = second-ps-type-recreated
- - update equip-type @ 17000
- - equip-type = second-ps-type-update
- - delete equip-type @ 20000
- */
- g.addV().property(AAIProperties.NODE_TYPE, "pserver",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 10000L
- )
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/test-pserver-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 10000L
- )
- .property(AAIProperties.RESOURCE_VERSION, "10000",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-U-1",
- AAIProperties.END_TX_ID, "JUNIT-U-1",
- AAIProperties.START_TS, 10000L,
- AAIProperties.END_TS, 13000L
- )
- .property(AAIProperties.RESOURCE_VERSION, "13000",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U-1",
- AAIProperties.START_TX_ID, "JUNIT-U-1",
- AAIProperties.END_SOT, "JUNIT-U-2",
- AAIProperties.END_TX_ID, "JUNIT-U-2",
- AAIProperties.START_TS, 13000L,
- AAIProperties.END_TS, 15000L
- )
- .property(AAIProperties.RESOURCE_VERSION, "15000",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U-2",
- AAIProperties.START_TX_ID, "JUNIT-U-2",
- AAIProperties.END_SOT, "JUNIT-U-3",
- AAIProperties.END_TX_ID, "JUNIT-U-3",
- AAIProperties.START_TS, 15000L,
- AAIProperties.END_TS, 17000L
- )
- .property(AAIProperties.RESOURCE_VERSION, "17000",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U-3",
- AAIProperties.START_TX_ID, "JUNIT-U-3",
- AAIProperties.END_SOT, "JUNIT-U-4",
- AAIProperties.END_TX_ID, "JUNIT-U-4",
- AAIProperties.START_TS, 17000L,
- AAIProperties.END_TS, 20000L
- )
- .property(AAIProperties.RESOURCE_VERSION, "20000",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U-4",
- AAIProperties.START_TX_ID, "JUNIT-U-4",
- AAIProperties.START_TS, 20000L
- )
- .property("hostname", "test-pserver-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 10000L
- )
- .property("in-maint", true,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 10000L
- )
- .property("equip-type", "second-ps-type",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-U-1",
- AAIProperties.END_TX_ID, "JUNIT-U-1",
- AAIProperties.START_TS, 10000L,
- AAIProperties.END_TS, 13000L
- )
- .property("equip-type", "second-ps-type-recreated",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U-2",
- AAIProperties.START_TX_ID, "JUNIT-U-2",
- AAIProperties.END_SOT, "JUNIT-U-3",
- AAIProperties.END_TX_ID, "JUNIT-U-3",
- AAIProperties.START_TS, 15000L,
- AAIProperties.END_TS, 17000L
- )
- .property("equip-type", "second-ps-type-update",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U-3",
- AAIProperties.START_TX_ID, "JUNIT-U-3",
- AAIProperties.START_TS, 17000L,
- AAIProperties.END_SOT, "JUNIT-U-4",
- AAIProperties.END_TX_ID, "JUNIT-U-4",
- AAIProperties.END_TS, 20000L
- )
- .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 10000L
- )
- .property(AAIProperties.START_TS, 10000L,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 10000L
- )
- .next();
- } catch (Exception ex) {
- success = false;
- } finally {
- if (success) {
- transaction.commit();
- } else {
- transaction.rollback();
- fail("Unable to setup the graph");
- }
- }
- }
-
- private JsonArray getResultsForPserverLookupByHostname(String endpoint) throws Exception {
- return getResultsForPserverLookupByHostnameAndAnother(endpoint, "");
- }
-
- private JsonArray getResultsForPserverLookupByHostnameAndAnother(String endpoint, String additionalFilterInParen) throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver*('hostname','test-pserver-dsl')" + additionalFilterInParen);
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- JsonArray results = new JsonParser().parse(responseEntity.getBody().toString()).getAsJsonObject().getAsJsonArray("results");
- LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint, responseEntity.getBody());
-
- assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
- assertEquals("Expected the response to be 200", HttpStatus.OK, responseEntity.getStatusCode());
- return results;
- }
-
-
- private void verifyEquipTypeValues(JsonArray results, String... expectedEquipTypes) {
- List<String> expected = Arrays.asList(expectedEquipTypes);
- final List<String> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- if (property.getAsJsonObject().has("value") && !property.getAsJsonObject().get("value").isJsonNull()) {
- actualEquipType.add(property.getAsJsonObject().get("value").getAsString());
- } else {
- actualEquipType.add(null);
- }
- }
- }
- }
- assertThat("Verify equip-type in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyEquipTypeSoTs(JsonArray results, String... expectedSTOs) {
- List<String> expected = Arrays.asList(expectedSTOs);
- final List<String> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- if (property.getAsJsonObject().has("sot") && !property.getAsJsonObject().get("sot").isJsonNull()) {
- actualEquipType.add(property.getAsJsonObject().get("sot").getAsString());
- } else {
- actualEquipType.add(null);
- }
- }
- }
- }
- assertThat("Verify equip-type SoTs in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyEquipTypeTxId(JsonArray results, String... expectedSTOs) {
- List<String> expected = Arrays.asList(expectedSTOs);
- final List<String> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- if (property.getAsJsonObject().has("tx-id") && !property.getAsJsonObject().get("tx-id").isJsonNull()) {
- actualEquipType.add(property.getAsJsonObject().get("tx-id").getAsString());
- } else {
- actualEquipType.add(null);
- }
- }
- }
- }
- assertThat("Verify equip-type tx-ids in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyEquipTypeTimestamps(JsonArray results, Long... expectedSTOs) {
- List<Long> expected = Arrays.asList(expectedSTOs);
- final List<Long> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- if (property.getAsJsonObject().has("timestamp") && !property.getAsJsonObject().get("timestamp").isJsonNull()) {
- actualEquipType.add(property.getAsJsonObject().get("timestamp").getAsLong());
- } else {
- actualEquipType.add(null);
- }
- }
- }
- }
- assertThat("Verify equip-type timestamps in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyNodeTimestamps(JsonArray results, Long... nodeTimestamps) {
- List<Long> expected = Arrays.asList(nodeTimestamps);
- final List<Long> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- result.getAsJsonObject().get("node-actions").getAsJsonArray().forEach(jsonElement ->
- actualEquipType.add(jsonElement.getAsJsonObject().get("timestamp").getAsLong()));
- }
- assertThat("Verify node-changes timestamps in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyNodeSot(JsonArray results, String... nodeSots) {
- List<String> expected = Arrays.asList(nodeSots);
- final List<String> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- result.getAsJsonObject().get("node-actions").getAsJsonArray().forEach(jsonElement ->
- actualEquipType.add(jsonElement.getAsJsonObject().get("sot").getAsString()));
- }
- assertThat("Verify node-changes sot in lifecycle", actualEquipType, is(expected));
- }
-
-
- @Test
- public void lifecycleQueryNoStartOrEndTsTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated", null, "second-ps-type", "first-ps-type-update", "first-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L, 500L, 100L);
- verifyNodeTimestamps(results, 10000L, 1000L, 100L);
-
-
- String equipType = "first-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 500L, 100L);
- verifyNodeTimestamps(results, 1000L, 100L);
-
- equipType = "second-ps-type-recreated";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated", null, "second-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L);
- verifyNodeTimestamps(results, 10000L);
- }
-
-
-
- @Test
- public void lifecycleQueryStartTsBeforeCreationTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=50";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated", null, "second-ps-type", "first-ps-type-update", "first-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L, 500L, 100L);
- verifyNodeTimestamps(results, 10000L, 1000L, 100L);
-
-
- String equipType = "first-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 500L, 100L);
- verifyNodeTimestamps(results, 1000L, 100L);
-
- equipType = "second-ps-type-recreated";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated", null, "second-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L);
- verifyNodeTimestamps(results, 10000L);
- }
-
- @Test
- public void lifecycleQueryStartTsAtCreationTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=100";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated", null, "second-ps-type", "first-ps-type-update", "first-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L, 500L, 100L);
- verifyNodeTimestamps(results, 10000L, 1000L, 100L);
- }
-
- @Test
- public void lifecycleQueryStartTsAfterCreationTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=300";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated", null, "second-ps-type", "first-ps-type-update");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L, 500L);
- verifyNodeTimestamps(results, 10000L, 1000L);
- }
-
- @Test
- public void lifecycleQueryStartTsAtFirstUpdateTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=500";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated", null, "second-ps-type", "first-ps-type-update");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L, 500L);
- verifyNodeTimestamps(results, 10000L, 1000L);
- }
-
- @Test
- public void lifecycleQueryStartTsAfterFirstUpdateTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=700";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated", null, "second-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L);
- verifyNodeTimestamps(results, 10000L, 1000L);
- }
-
- @Test
- public void lifecycleQueryStartTsAtFirstDeleteTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=1000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated", null, "second-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L);
- verifyNodeTimestamps(results, 10000L, 1000L);
- }
-
- @Test
- public void lifecycleQueryStartTsAfterFirstDeleteTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=5000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated", null, "second-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L);
- verifyNodeTimestamps(results, 10000L);
- }
-
- @Test
- public void lifecycleQueryStartTsAtSecondCreateTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=10000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated", null, "second-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L);
- verifyNodeTimestamps(results, 10000L);
- }
-
- @Test
- public void lifecycleQueryStartTsAfterSecondCreateTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=12000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated", null);
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L);
- verifyNodeTimestamps(results);
- }
-
- @Test
- public void lifecycleQueryStartTsAtEquipTypeFirstDeleteOnSecondPsTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=13000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated", null);
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L);
- verifyNodeTimestamps(results);
- }
-
- @Test
- public void lifecycleQueryStartTsAfterEquipTypeFirstDeleteOnSecondPsTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=14000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L);
- verifyNodeTimestamps(results);
- }
-
- @Test
- public void lifecycleQueryStartTsAtEquipTypeRecreateOnSecondPsTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=15000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L);
- verifyNodeTimestamps(results);
- }
-
- @Test
- public void lifecycleQueryStartTsAfterEquipTypeRecreateOnSecondPsTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=16000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3");
- verifyEquipTypeTimestamps(results, 20000L, 17000L);
- verifyNodeTimestamps(results);
- }
-
- @Test
- public void lifecycleQueryStartTsAtEquipTypeUpdateOnSecondPsTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=17000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3");
- verifyEquipTypeTimestamps(results, 20000L, 17000L);
- verifyNodeTimestamps(results);
- }
-
- @Test
- public void lifecycleQueryStartTsAfterEquipTypeUpdateOnSecondPsTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=19000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, new String[] {null});
- verifyEquipTypeSoTs(results, "JUNIT-U-4");
- verifyEquipTypeTxId(results, "JUNIT-U-4");
- verifyEquipTypeTimestamps(results, 20000L);
- verifyNodeTimestamps(results);
- }
-
- @Test
- public void lifecycleQueryStartTsOnEquipTypeSecondDeleteOnSecondPsTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=20000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, new String[] {null});
- verifyEquipTypeSoTs(results, "JUNIT-U-4");
- verifyEquipTypeTxId(results, "JUNIT-U-4");
- verifyEquipTypeTimestamps(results, 20000L);
- verifyNodeTimestamps(results);
- }
-
- @Test
- public void lifecycleQueryStartTsAfterEquipTypeSecondDeleteOnSecondPsTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=22000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 0, results.size());
-
- verifyEquipTypeValues(results);
- verifyEquipTypeSoTs(results);
- verifyEquipTypeTxId(results);
- verifyEquipTypeTimestamps(results);
- verifyNodeTimestamps(results);
- }
-
- @Test
- public void lifecycleQueryStartTsBeforeCreationEndTimeAfterEquipTypeSecondDeleteOnSecondPsTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=50&endTs=22000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated", null, "second-ps-type", "first-ps-type-update", "first-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L, 500L, 100L);
- verifyNodeTimestamps(results, 10000L, 1000L, 100L);
- }
-
- @Test
- public void lifecycleQueryStartTsBeforeCreationEndTimeAtEquipTypeSecondDeleteOnSecondPsTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=50&endTs=20000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated", null, "second-ps-type", "first-ps-type-update", "first-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L, 500L, 100L);
- verifyNodeTimestamps(results, 10000L, 1000L, 100L);
- }
-
- @Test
- public void lifecycleQueryStartTsBeforeCreationEndTimeBeforeEquipTypeSecondDeleteOnSecondPsTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=50&endTs=19000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, "second-ps-type-update", "second-ps-type-recreated", null, "second-ps-type", "first-ps-type-update", "first-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 17000L, 15000L, 13000L, 10000L, 500L, 100L);
- verifyNodeTimestamps(results, 10000L, 1000L, 100L);
- }
-
- @Test
- public void lifecycleQueryStartTsBeforeCreationEndTimeBeforeSecondPsCreateTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=50&endTs=9000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 500L, 100L);
- verifyNodeTimestamps(results, 1000L, 100L);
- }
-
- @Test
- public void verifyNodeActionsWithNoTimeRangeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
- verifyNodeTimestamps(results, 10000L, 1000L, 100L);
- verifyNodeSot(results, "JUNIT-C", "JUNIT-D", "JUNIT-C");
- }
+@Ignore("The lifecycle format requires the history schema to be loaded. "
+ + "Because aaigraph is a singleton its very complicated to have 2 different schemas loaded for testing. "
+ + "This needs to be addressed.")
+public class DslConsumerHistoryLifecycleNodeDeletedThenRecreatedTest
+ extends AbstractSpringHistoryRestTest {
+
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(DslConsumerHistoryLifecycleNodeDeletedThenRecreatedTest.class);
+
+ @Override
+ public void createTestGraph() {
+ JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
+ boolean success = true;
+ try {
+ GraphTraversalSource g = transaction.traversal();
+ /*
+ * Pserver
+ * - created pserver @ time 100
+ * - equip-type = first-ps-type
+ * - update equip-type @ 500
+ * - equip-type = first-ps-type-update
+ * - deleted pserver @ time 1000
+ */
+ g.addV()
+ .property(AAIProperties.NODE_TYPE, "pserver", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT,
+ "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.AAI_URI,
+ "/cloud-infrastructure/pservers/pserver/test-pserver-dsl",
+ AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C",
+ AAIProperties.END_SOT, "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D",
+ AAIProperties.START_TS, 100L, AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.RESOURCE_VERSION, "100", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT,
+ "JUNIT-U", AAIProperties.END_TX_ID, "JUNIT-U", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 500L)
+ .property(AAIProperties.RESOURCE_VERSION, "500", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-U", AAIProperties.START_TX_ID, "JUNIT-U", AAIProperties.END_SOT,
+ "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 500L,
+ AAIProperties.END_TS, 1000L)
+ .property("hostname", "test-pserver-dsl", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT, "JUNIT-D",
+ AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property("in-maint", false, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT, "JUNIT-D",
+ AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property("equip-type", "first-ps-type", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT, "JUNIT-U",
+ AAIProperties.END_TX_ID, "JUNIT-U", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 500L)
+ .property("equip-type", "first-ps-type-update", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-U", AAIProperties.START_TX_ID, "JUNIT-U", AAIProperties.END_SOT,
+ "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 500L,
+ AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT,
+ "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.END_SOT, "JUNIT-D", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-D", AAIProperties.START_TX_ID, "JUNIT-D", AAIProperties.END_SOT,
+ "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.START_TS, 100L, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT, "JUNIT-D",
+ AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.END_TS, 1000L, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-D",
+ AAIProperties.START_TX_ID, "JUNIT-D", AAIProperties.END_SOT, "JUNIT-D",
+ AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 1000L,
+ AAIProperties.END_TS, 1000L)
+ .next();
+
+ /*
+ * Pserver
+ * - created pserver @ time 10000
+ * - equip-type = second-ps-type
+ * - delete equip-type @ 13000
+ * - recreate equip-type @ 15000
+ * - equip-type = second-ps-type-recreated
+ * - update equip-type @ 17000
+ * - equip-type = second-ps-type-update
+ * - delete equip-type @ 20000
+ */
+ g.addV()
+ .property(AAIProperties.NODE_TYPE, "pserver", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 10000L)
+ .property(AAIProperties.AAI_URI,
+ "/cloud-infrastructure/pservers/pserver/test-pserver-dsl",
+ AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C",
+ AAIProperties.START_TS, 10000L)
+ .property(AAIProperties.RESOURCE_VERSION, "10000", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT,
+ "JUNIT-U-1", AAIProperties.END_TX_ID, "JUNIT-U-1", AAIProperties.START_TS,
+ 10000L, AAIProperties.END_TS, 13000L)
+ .property(AAIProperties.RESOURCE_VERSION, "13000", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-U-1", AAIProperties.START_TX_ID, "JUNIT-U-1", AAIProperties.END_SOT,
+ "JUNIT-U-2", AAIProperties.END_TX_ID, "JUNIT-U-2", AAIProperties.START_TS,
+ 13000L, AAIProperties.END_TS, 15000L)
+ .property(AAIProperties.RESOURCE_VERSION, "15000", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-U-2", AAIProperties.START_TX_ID, "JUNIT-U-2", AAIProperties.END_SOT,
+ "JUNIT-U-3", AAIProperties.END_TX_ID, "JUNIT-U-3", AAIProperties.START_TS,
+ 15000L, AAIProperties.END_TS, 17000L)
+ .property(AAIProperties.RESOURCE_VERSION, "17000", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-U-3", AAIProperties.START_TX_ID, "JUNIT-U-3", AAIProperties.END_SOT,
+ "JUNIT-U-4", AAIProperties.END_TX_ID, "JUNIT-U-4", AAIProperties.START_TS,
+ 17000L, AAIProperties.END_TS, 20000L)
+ .property(AAIProperties.RESOURCE_VERSION, "20000", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-U-4", AAIProperties.START_TX_ID, "JUNIT-U-4", AAIProperties.START_TS,
+ 20000L)
+ .property("hostname", "test-pserver-dsl", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 10000L)
+ .property("in-maint", true, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 10000L)
+ .property("equip-type", "second-ps-type", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT, "JUNIT-U-1",
+ AAIProperties.END_TX_ID, "JUNIT-U-1", AAIProperties.START_TS, 10000L,
+ AAIProperties.END_TS, 13000L)
+ .property("equip-type", "second-ps-type-recreated", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-U-2", AAIProperties.START_TX_ID, "JUNIT-U-2", AAIProperties.END_SOT,
+ "JUNIT-U-3", AAIProperties.END_TX_ID, "JUNIT-U-3", AAIProperties.START_TS,
+ 15000L, AAIProperties.END_TS, 17000L)
+ .property("equip-type", "second-ps-type-update", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-U-3", AAIProperties.START_TX_ID, "JUNIT-U-3", AAIProperties.START_TS,
+ 17000L, AAIProperties.END_SOT, "JUNIT-U-4", AAIProperties.END_TX_ID,
+ "JUNIT-U-4", AAIProperties.END_TS, 20000L)
+ .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 10000L)
+ .property(AAIProperties.START_TS, 10000L, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 10000L)
+ .next();
+ } catch (Exception ex) {
+ success = false;
+ } finally {
+ if (success) {
+ transaction.commit();
+ } else {
+ transaction.rollback();
+ fail("Unable to setup the graph");
+ }
+ }
+ }
+
+ private JsonArray getResultsForPserverLookupByHostname(String endpoint) throws Exception {
+ return getResultsForPserverLookupByHostnameAndAnother(endpoint, "");
+ }
+
+ private JsonArray getResultsForPserverLookupByHostnameAndAnother(String endpoint,
+ String additionalFilterInParen) throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "pserver*('hostname','test-pserver-dsl')" + additionalFilterInParen);
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ JsonArray results = new JsonParser().parse(responseEntity.getBody().toString())
+ .getAsJsonObject().getAsJsonArray("results");
+ LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint,
+ responseEntity.getBody());
+
+ assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
+ assertEquals("Expected the response to be 200", HttpStatus.OK,
+ responseEntity.getStatusCode());
+ return results;
+ }
+
+ private void verifyEquipTypeValues(JsonArray results, String... expectedEquipTypes) {
+ List<String> expected = Arrays.asList(expectedEquipTypes);
+ final List<String> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ if (property.getAsJsonObject().has("value")
+ && !property.getAsJsonObject().get("value").isJsonNull()) {
+ actualEquipType.add(property.getAsJsonObject().get("value").getAsString());
+ } else {
+ actualEquipType.add(null);
+ }
+ }
+ }
+ }
+ assertThat("Verify equip-type in lifecycle", actualEquipType, is(expected));
+ }
+
+ private void verifyEquipTypeSoTs(JsonArray results, String... expectedSTOs) {
+ List<String> expected = Arrays.asList(expectedSTOs);
+ final List<String> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ if (property.getAsJsonObject().has("sot")
+ && !property.getAsJsonObject().get("sot").isJsonNull()) {
+ actualEquipType.add(property.getAsJsonObject().get("sot").getAsString());
+ } else {
+ actualEquipType.add(null);
+ }
+ }
+ }
+ }
+ assertThat("Verify equip-type SoTs in lifecycle", actualEquipType, is(expected));
+ }
+
+ private void verifyEquipTypeTxId(JsonArray results, String... expectedSTOs) {
+ List<String> expected = Arrays.asList(expectedSTOs);
+ final List<String> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ if (property.getAsJsonObject().has("tx-id")
+ && !property.getAsJsonObject().get("tx-id").isJsonNull()) {
+ actualEquipType.add(property.getAsJsonObject().get("tx-id").getAsString());
+ } else {
+ actualEquipType.add(null);
+ }
+ }
+ }
+ }
+ assertThat("Verify equip-type tx-ids in lifecycle", actualEquipType, is(expected));
+ }
+
+ private void verifyEquipTypeTimestamps(JsonArray results, Long... expectedSTOs) {
+ List<Long> expected = Arrays.asList(expectedSTOs);
+ final List<Long> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ if (property.getAsJsonObject().has("timestamp")
+ && !property.getAsJsonObject().get("timestamp").isJsonNull()) {
+ actualEquipType
+ .add(property.getAsJsonObject().get("timestamp").getAsLong());
+ } else {
+ actualEquipType.add(null);
+ }
+ }
+ }
+ }
+ assertThat("Verify equip-type timestamps in lifecycle", actualEquipType, is(expected));
+ }
+
+ private void verifyNodeTimestamps(JsonArray results, Long... nodeTimestamps) {
+ List<Long> expected = Arrays.asList(nodeTimestamps);
+ final List<Long> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ result.getAsJsonObject().get("node-actions").getAsJsonArray()
+ .forEach(jsonElement -> actualEquipType
+ .add(jsonElement.getAsJsonObject().get("timestamp").getAsLong()));
+ }
+ assertThat("Verify node-changes timestamps in lifecycle", actualEquipType, is(expected));
+ }
+
+ private void verifyNodeSot(JsonArray results, String... nodeSots) {
+ List<String> expected = Arrays.asList(nodeSots);
+ final List<String> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ result.getAsJsonObject().get("node-actions").getAsJsonArray()
+ .forEach(jsonElement -> actualEquipType
+ .add(jsonElement.getAsJsonObject().get("sot").getAsString()));
+ }
+ assertThat("Verify node-changes sot in lifecycle", actualEquipType, is(expected));
+ }
+
+ @Test
+ public void lifecycleQueryNoStartOrEndTsTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated",
+ null, "second-ps-type", "first-ps-type-update", "first-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C",
+ "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C",
+ "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L, 500L, 100L);
+ verifyNodeTimestamps(results, 10000L, 1000L, 100L);
+
+ String equipType = "first-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 500L, 100L);
+ verifyNodeTimestamps(results, 1000L, 100L);
+
+ equipType = "second-ps-type-recreated";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated",
+ null, "second-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L);
+ verifyNodeTimestamps(results, 10000L);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsBeforeCreationTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=50";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated",
+ null, "second-ps-type", "first-ps-type-update", "first-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C",
+ "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C",
+ "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L, 500L, 100L);
+ verifyNodeTimestamps(results, 10000L, 1000L, 100L);
+
+ String equipType = "first-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 500L, 100L);
+ verifyNodeTimestamps(results, 1000L, 100L);
+
+ equipType = "second-ps-type-recreated";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated",
+ null, "second-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L);
+ verifyNodeTimestamps(results, 10000L);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAtCreationTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=100";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated",
+ null, "second-ps-type", "first-ps-type-update", "first-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C",
+ "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C",
+ "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L, 500L, 100L);
+ verifyNodeTimestamps(results, 10000L, 1000L, 100L);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAfterCreationTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=300";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated",
+ null, "second-ps-type", "first-ps-type-update");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C",
+ "JUNIT-U");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C",
+ "JUNIT-U");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L, 500L);
+ verifyNodeTimestamps(results, 10000L, 1000L);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAtFirstUpdateTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=500";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated",
+ null, "second-ps-type", "first-ps-type-update");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C",
+ "JUNIT-U");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C",
+ "JUNIT-U");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L, 500L);
+ verifyNodeTimestamps(results, 10000L, 1000L);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAfterFirstUpdateTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=700";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated",
+ null, "second-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L);
+ verifyNodeTimestamps(results, 10000L, 1000L);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAtFirstDeleteTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=1000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated",
+ null, "second-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L);
+ verifyNodeTimestamps(results, 10000L, 1000L);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAfterFirstDeleteTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=5000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated",
+ null, "second-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L);
+ verifyNodeTimestamps(results, 10000L);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAtSecondCreateTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=10000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated",
+ null, "second-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L);
+ verifyNodeTimestamps(results, 10000L);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAfterSecondCreateTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=12000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated",
+ null);
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L);
+ verifyNodeTimestamps(results);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAtEquipTypeFirstDeleteOnSecondPsTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=13000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated",
+ null);
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L);
+ verifyNodeTimestamps(results);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAfterEquipTypeFirstDeleteOnSecondPsTimeTest()
+ throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=14000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L);
+ verifyNodeTimestamps(results);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAtEquipTypeRecreateOnSecondPsTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=15000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L);
+ verifyNodeTimestamps(results);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAfterEquipTypeRecreateOnSecondPsTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=16000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L);
+ verifyNodeTimestamps(results);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAtEquipTypeUpdateOnSecondPsTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=17000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L);
+ verifyNodeTimestamps(results);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAfterEquipTypeUpdateOnSecondPsTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=19000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, new String[] {null});
+ verifyEquipTypeSoTs(results, "JUNIT-U-4");
+ verifyEquipTypeTxId(results, "JUNIT-U-4");
+ verifyEquipTypeTimestamps(results, 20000L);
+ verifyNodeTimestamps(results);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsOnEquipTypeSecondDeleteOnSecondPsTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=20000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, new String[] {null});
+ verifyEquipTypeSoTs(results, "JUNIT-U-4");
+ verifyEquipTypeTxId(results, "JUNIT-U-4");
+ verifyEquipTypeTimestamps(results, 20000L);
+ verifyNodeTimestamps(results);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAfterEquipTypeSecondDeleteOnSecondPsTimeTest()
+ throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=22000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 0, results.size());
+
+ verifyEquipTypeValues(results);
+ verifyEquipTypeSoTs(results);
+ verifyEquipTypeTxId(results);
+ verifyEquipTypeTimestamps(results);
+ verifyNodeTimestamps(results);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsBeforeCreationEndTimeAfterEquipTypeSecondDeleteOnSecondPsTimeTest()
+ throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=50&endTs=22000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated",
+ null, "second-ps-type", "first-ps-type-update", "first-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C",
+ "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C",
+ "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L, 500L, 100L);
+ verifyNodeTimestamps(results, 10000L, 1000L, 100L);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsBeforeCreationEndTimeAtEquipTypeSecondDeleteOnSecondPsTimeTest()
+ throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=50&endTs=20000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, null, "second-ps-type-update", "second-ps-type-recreated",
+ null, "second-ps-type", "first-ps-type-update", "first-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C",
+ "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U-4", "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C",
+ "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 20000L, 17000L, 15000L, 13000L, 10000L, 500L, 100L);
+ verifyNodeTimestamps(results, 10000L, 1000L, 100L);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsBeforeCreationEndTimeBeforeEquipTypeSecondDeleteOnSecondPsTimeTest()
+ throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=50&endTs=19000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, "second-ps-type-update", "second-ps-type-recreated", null,
+ "second-ps-type", "first-ps-type-update", "first-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U",
+ "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U-3", "JUNIT-U-2", "JUNIT-U-1", "JUNIT-C", "JUNIT-U",
+ "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 17000L, 15000L, 13000L, 10000L, 500L, 100L);
+ verifyNodeTimestamps(results, 10000L, 1000L, 100L);
+ }
+
+ @Test
+ public void lifecycleQueryStartTsBeforeCreationEndTimeBeforeSecondPsCreateTimeTest()
+ throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=50&endTs=9000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 500L, 100L);
+ verifyNodeTimestamps(results, 1000L, 100L);
+ }
+
+ @Test
+ public void verifyNodeActionsWithNoTimeRangeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+ verifyNodeTimestamps(results, 10000L, 1000L, 100L);
+ verifyNodeSot(results, "JUNIT-C", "JUNIT-D", "JUNIT-C");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryLifecycleSingleNodeTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryLifecycleSingleNodeTest.java
index e59573d..6d1a36c 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryLifecycleSingleNodeTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryLifecycleSingleNodeTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,9 +19,15 @@
*/
package org.onap.aai.rest.history;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.*;
+
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
+
+import java.util.*;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.janusgraph.core.JanusGraphTransaction;
import org.junit.Ignore;
@@ -36,432 +42,404 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
-import java.util.*;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.*;
-
-@Ignore("The lifecycle format requires the history schema to be loaded. " +
- "Because aaigraph is a singleton its very complicated to have 2 different schemas loaded for testing. " +
- "This needs to be addressed.")
+@Ignore("The lifecycle format requires the history schema to be loaded. "
+ + "Because aaigraph is a singleton its very complicated to have 2 different schemas loaded for testing. "
+ + "This needs to be addressed.")
public class DslConsumerHistoryLifecycleSingleNodeTest extends AbstractSpringHistoryRestTest {
- private static final Logger LOGGER = LoggerFactory.getLogger(DslConsumerHistoryLifecycleSingleNodeTest.class);
-
- @Override
- public void createTestGraph() {
- JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
- boolean success = true;
- try {
- GraphTraversalSource g = transaction.traversal();
- /*
- Pserver
- - created pserver @ time 100
- - equip-type = first-ps-type
- - update equip-type @ 500
- - equip-type = first-ps-type-update
- - deleted pserver @ time 1000
- */
- g.addV().property(AAIProperties.NODE_TYPE, "pserver",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/test-pserver-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.RESOURCE_VERSION, "100",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-U",
- AAIProperties.END_TX_ID, "JUNIT-U",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 500L
- )
- .property(AAIProperties.RESOURCE_VERSION, "500",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U",
- AAIProperties.START_TX_ID, "JUNIT-U",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 500L,
- AAIProperties.END_TS, 1000L
- )
- .property("hostname", "test-pserver-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property("in-maint", false,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property("equip-type", "first-ps-type",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-U",
- AAIProperties.END_TX_ID, "JUNIT-U",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 500L
- )
- .property("equip-type", "first-ps-type-update",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U",
- AAIProperties.START_TX_ID, "JUNIT-U",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 500L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-D",
- AAIProperties.START_TX_ID, "JUNIT-D",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.START_TS, 100L,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.END_TS, 1000L,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-D",
- AAIProperties.START_TX_ID, "JUNIT-D",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 1000L,
- AAIProperties.END_TS, 1000L
- )
- .next();
-
- } catch (Exception ex) {
- success = false;
- } finally {
- if (success) {
- transaction.commit();
- } else {
- transaction.rollback();
- fail("Unable to setup the graph");
- }
- }
- }
-
- private JsonArray getResultsForPserverLookupByHostname(String endpoint) throws Exception {
- return getResultsForPserverLookupByHostnameAndAnother(endpoint, "");
- }
-
- private JsonArray getResultsForPserverLookupByHostnameAndAnother(String endpoint, String additionalFilterInParen) throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver*('hostname','test-pserver-dsl')" + additionalFilterInParen);
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- JsonArray results = new JsonParser().parse(responseEntity.getBody().toString()).getAsJsonObject().getAsJsonArray("results");
- LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint, responseEntity.getBody());
-
- assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
- assertEquals("Expected the response to be 200", HttpStatus.OK, responseEntity.getStatusCode());
- return results;
- }
-
-
- private void verifyEquipTypeValues(JsonArray results, String... expectedEquipTypes) {
- List<String> expected = Arrays.asList(expectedEquipTypes);
- final List<String> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- if (property.getAsJsonObject().has("value") && !property.getAsJsonObject().get("value").isJsonNull()) {
- actualEquipType.add(property.getAsJsonObject().get("value").getAsString());
- } else {
- actualEquipType.add(null);
- }
- }
- }
- }
- assertThat("Verify equip-type in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyEquipTypeSoTs(JsonArray results, String... expectedSTOs) {
- List<String> expected = Arrays.asList(expectedSTOs);
- final List<String> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- if (property.getAsJsonObject().has("sot") && !property.getAsJsonObject().get("sot").isJsonNull()) {
- actualEquipType.add(property.getAsJsonObject().get("sot").getAsString());
- } else {
- actualEquipType.add(null);
- }
- }
- }
- }
- assertThat("Verify equip-type SoTs in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyEquipTypeTxId(JsonArray results, String... expectedSTOs) {
- List<String> expected = Arrays.asList(expectedSTOs);
- final List<String> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- if (property.getAsJsonObject().has("tx-id") && !property.getAsJsonObject().get("tx-id").isJsonNull()) {
- actualEquipType.add(property.getAsJsonObject().get("tx-id").getAsString());
- } else {
- actualEquipType.add(null);
- }
- }
- }
- }
- assertThat("Verify equip-type tx-ids in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyEquipTypeTimestamps(JsonArray results, Long... expectedSTOs) {
- List<Long> expected = Arrays.asList(expectedSTOs);
- final List<Long> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- if (property.getAsJsonObject().has("timestamp") && !property.getAsJsonObject().get("timestamp").isJsonNull()) {
- actualEquipType.add(property.getAsJsonObject().get("timestamp").getAsLong());
- } else {
- actualEquipType.add(null);
- }
- }
- }
- }
- assertThat("Verify equip-type timestamps in lifecycle", actualEquipType, is(expected));
- }
-
- private void verifyNodeTimestamps(JsonArray results, Long... nodeTimestamps) {
- List<Long> expected = Arrays.asList(nodeTimestamps);
- final List<Long> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- result.getAsJsonObject().get("node-actions").getAsJsonArray().forEach(jsonElement ->
- actualEquipType.add(jsonElement.getAsJsonObject().get("timestamp").getAsLong()));
- }
- assertThat("Verify node-changes timestamps in lifecycle", actualEquipType, is(expected));
- }
-
-
- @Test
- public void lifecycleQueryNoStartOrEndTsTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 500L, 100L);
- verifyNodeTimestamps(results, 1000L, 100L);
-
-
- String equipType = "first-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 500L, 100L);
- verifyNodeTimestamps(results, 1000L, 100L);
-
- equipType = "other-ps-type-recreated";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
- }
-
-
-
- @Test
- public void lifecycleQueryStartTsBeforeCreationTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=50";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 500L, 100L);
- verifyNodeTimestamps(results, 1000L, 100L);
-
-
- String equipType = "first-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 500L, 100L);
- verifyNodeTimestamps(results, 1000L, 100L);
-
- equipType = "other-ps-type-recreated";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
- }
-
- @Test
- public void lifecycleQueryStartTsAtCreationTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=100";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 500L, 100L);
- verifyNodeTimestamps(results, 1000L, 100L);
-
-
- String equipType = "first-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
- verifyEquipTypeTimestamps(results, 500L, 100L);
- verifyNodeTimestamps(results, 1000L, 100L);
-
- equipType = "other-ps-type-recreated";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
- }
-
- @Test
- public void lifecycleQueryStartTsAfterCreationTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=300";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, "first-ps-type-update");
- verifyEquipTypeSoTs(results, "JUNIT-U");
- verifyEquipTypeTxId(results, "JUNIT-U");
- verifyEquipTypeTimestamps(results, 500L);
- verifyNodeTimestamps(results, 1000L);
-
-
- String equipType = "first-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, "first-ps-type-update");
- verifyEquipTypeSoTs(results, "JUNIT-U");
- verifyEquipTypeTxId(results, "JUNIT-U");
- verifyEquipTypeTimestamps(results, 500L);
- verifyNodeTimestamps(results, 1000L);
-
- equipType = "other-ps-type-recreated";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
- }
-
- @Test
- public void lifecycleQueryStartTsAtUpdateTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=500";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, "first-ps-type-update");
- verifyEquipTypeSoTs(results, "JUNIT-U");
- verifyEquipTypeTxId(results, "JUNIT-U");
- verifyEquipTypeTimestamps(results, 500L);
- verifyNodeTimestamps(results, 1000L);
-
-
- String equipType = "first-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, "first-ps-type-update");
- verifyEquipTypeSoTs(results, "JUNIT-U");
- verifyEquipTypeTxId(results, "JUNIT-U");
- verifyEquipTypeTimestamps(results, 500L);
- verifyNodeTimestamps(results, 1000L);
-
- equipType = "other-ps-type-recreated";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
- }
-
- @Test
- public void lifecycleQueryStartTsAfterUpdateTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=700";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results);
- verifyEquipTypeSoTs(results);
- verifyEquipTypeTxId(results);
- verifyEquipTypeTimestamps(results);
- verifyNodeTimestamps(results, 1000L);
-
-
- String equipType = "first-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
-
- equipType = "other-ps-type-recreated";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
- }
-
- @Test
- public void lifecycleQueryStartTsAtDeleteTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=1000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
- assertEquals("properties size should be 0", results.get(0).getAsJsonObject().get("properties").getAsJsonArray().size(), 0);
-
- String equipType = "first-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
- }
-
- @Test
- public void lifecycleQueryStartTsAfterDeleteTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=5000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 0, results.size());
-
- String equipType = "first-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
-
- equipType = "other-ps-type-recreated";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
- }
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(DslConsumerHistoryLifecycleSingleNodeTest.class);
+
+ @Override
+ public void createTestGraph() {
+ JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
+ boolean success = true;
+ try {
+ GraphTraversalSource g = transaction.traversal();
+ /*
+ * Pserver
+ * - created pserver @ time 100
+ * - equip-type = first-ps-type
+ * - update equip-type @ 500
+ * - equip-type = first-ps-type-update
+ * - deleted pserver @ time 1000
+ */
+ g.addV()
+ .property(AAIProperties.NODE_TYPE, "pserver", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT,
+ "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.AAI_URI,
+ "/cloud-infrastructure/pservers/pserver/test-pserver-dsl",
+ AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C",
+ AAIProperties.END_SOT, "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D",
+ AAIProperties.START_TS, 100L, AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.RESOURCE_VERSION, "100", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT,
+ "JUNIT-U", AAIProperties.END_TX_ID, "JUNIT-U", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 500L)
+ .property(AAIProperties.RESOURCE_VERSION, "500", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-U", AAIProperties.START_TX_ID, "JUNIT-U", AAIProperties.END_SOT,
+ "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 500L,
+ AAIProperties.END_TS, 1000L)
+ .property("hostname", "test-pserver-dsl", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT, "JUNIT-D",
+ AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property("in-maint", false, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT, "JUNIT-D",
+ AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property("equip-type", "first-ps-type", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT, "JUNIT-U",
+ AAIProperties.END_TX_ID, "JUNIT-U", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 500L)
+ .property("equip-type", "first-ps-type-update", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-U", AAIProperties.START_TX_ID, "JUNIT-U", AAIProperties.END_SOT,
+ "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 500L,
+ AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT,
+ "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.END_SOT, "JUNIT-D", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-D", AAIProperties.START_TX_ID, "JUNIT-D", AAIProperties.END_SOT,
+ "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.START_TS, 100L, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT, "JUNIT-D",
+ AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.END_TS, 1000L, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-D",
+ AAIProperties.START_TX_ID, "JUNIT-D", AAIProperties.END_SOT, "JUNIT-D",
+ AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 1000L,
+ AAIProperties.END_TS, 1000L)
+ .next();
+
+ } catch (Exception ex) {
+ success = false;
+ } finally {
+ if (success) {
+ transaction.commit();
+ } else {
+ transaction.rollback();
+ fail("Unable to setup the graph");
+ }
+ }
+ }
+
+ private JsonArray getResultsForPserverLookupByHostname(String endpoint) throws Exception {
+ return getResultsForPserverLookupByHostnameAndAnother(endpoint, "");
+ }
+
+ private JsonArray getResultsForPserverLookupByHostnameAndAnother(String endpoint,
+ String additionalFilterInParen) throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "pserver*('hostname','test-pserver-dsl')" + additionalFilterInParen);
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ JsonArray results = new JsonParser().parse(responseEntity.getBody().toString())
+ .getAsJsonObject().getAsJsonArray("results");
+ LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint,
+ responseEntity.getBody());
+
+ assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
+ assertEquals("Expected the response to be 200", HttpStatus.OK,
+ responseEntity.getStatusCode());
+ return results;
+ }
+
+ private void verifyEquipTypeValues(JsonArray results, String... expectedEquipTypes) {
+ List<String> expected = Arrays.asList(expectedEquipTypes);
+ final List<String> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ if (property.getAsJsonObject().has("value")
+ && !property.getAsJsonObject().get("value").isJsonNull()) {
+ actualEquipType.add(property.getAsJsonObject().get("value").getAsString());
+ } else {
+ actualEquipType.add(null);
+ }
+ }
+ }
+ }
+ assertThat("Verify equip-type in lifecycle", actualEquipType, is(expected));
+ }
+
+ private void verifyEquipTypeSoTs(JsonArray results, String... expectedSTOs) {
+ List<String> expected = Arrays.asList(expectedSTOs);
+ final List<String> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ if (property.getAsJsonObject().has("sot")
+ && !property.getAsJsonObject().get("sot").isJsonNull()) {
+ actualEquipType.add(property.getAsJsonObject().get("sot").getAsString());
+ } else {
+ actualEquipType.add(null);
+ }
+ }
+ }
+ }
+ assertThat("Verify equip-type SoTs in lifecycle", actualEquipType, is(expected));
+ }
+
+ private void verifyEquipTypeTxId(JsonArray results, String... expectedSTOs) {
+ List<String> expected = Arrays.asList(expectedSTOs);
+ final List<String> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ if (property.getAsJsonObject().has("tx-id")
+ && !property.getAsJsonObject().get("tx-id").isJsonNull()) {
+ actualEquipType.add(property.getAsJsonObject().get("tx-id").getAsString());
+ } else {
+ actualEquipType.add(null);
+ }
+ }
+ }
+ }
+ assertThat("Verify equip-type tx-ids in lifecycle", actualEquipType, is(expected));
+ }
+
+ private void verifyEquipTypeTimestamps(JsonArray results, Long... expectedSTOs) {
+ List<Long> expected = Arrays.asList(expectedSTOs);
+ final List<Long> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ if (property.getAsJsonObject().has("timestamp")
+ && !property.getAsJsonObject().get("timestamp").isJsonNull()) {
+ actualEquipType
+ .add(property.getAsJsonObject().get("timestamp").getAsLong());
+ } else {
+ actualEquipType.add(null);
+ }
+ }
+ }
+ }
+ assertThat("Verify equip-type timestamps in lifecycle", actualEquipType, is(expected));
+ }
+
+ private void verifyNodeTimestamps(JsonArray results, Long... nodeTimestamps) {
+ List<Long> expected = Arrays.asList(nodeTimestamps);
+ final List<Long> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ result.getAsJsonObject().get("node-actions").getAsJsonArray()
+ .forEach(jsonElement -> actualEquipType
+ .add(jsonElement.getAsJsonObject().get("timestamp").getAsLong()));
+ }
+ assertThat("Verify node-changes timestamps in lifecycle", actualEquipType, is(expected));
+ }
+
+ @Test
+ public void lifecycleQueryNoStartOrEndTsTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 500L, 100L);
+ verifyNodeTimestamps(results, 1000L, 100L);
+
+ String equipType = "first-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 500L, 100L);
+ verifyNodeTimestamps(results, 1000L, 100L);
+
+ equipType = "other-ps-type-recreated";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ }
+
+ @Test
+ public void lifecycleQueryStartTsBeforeCreationTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=50";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 500L, 100L);
+ verifyNodeTimestamps(results, 1000L, 100L);
+
+ String equipType = "first-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 500L, 100L);
+ verifyNodeTimestamps(results, 1000L, 100L);
+
+ equipType = "other-ps-type-recreated";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAtCreationTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=100";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 500L, 100L);
+ verifyNodeTimestamps(results, 1000L, 100L);
+
+ String equipType = "first-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ verifyEquipTypeValues(results, "first-ps-type-update", "first-ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTxId(results, "JUNIT-U", "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 500L, 100L);
+ verifyNodeTimestamps(results, 1000L, 100L);
+
+ equipType = "other-ps-type-recreated";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAfterCreationTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=300";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, "first-ps-type-update");
+ verifyEquipTypeSoTs(results, "JUNIT-U");
+ verifyEquipTypeTxId(results, "JUNIT-U");
+ verifyEquipTypeTimestamps(results, 500L);
+ verifyNodeTimestamps(results, 1000L);
+
+ String equipType = "first-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ verifyEquipTypeValues(results, "first-ps-type-update");
+ verifyEquipTypeSoTs(results, "JUNIT-U");
+ verifyEquipTypeTxId(results, "JUNIT-U");
+ verifyEquipTypeTimestamps(results, 500L);
+ verifyNodeTimestamps(results, 1000L);
+
+ equipType = "other-ps-type-recreated";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAtUpdateTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=500";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, "first-ps-type-update");
+ verifyEquipTypeSoTs(results, "JUNIT-U");
+ verifyEquipTypeTxId(results, "JUNIT-U");
+ verifyEquipTypeTimestamps(results, 500L);
+ verifyNodeTimestamps(results, 1000L);
+
+ String equipType = "first-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ verifyEquipTypeValues(results, "first-ps-type-update");
+ verifyEquipTypeSoTs(results, "JUNIT-U");
+ verifyEquipTypeTxId(results, "JUNIT-U");
+ verifyEquipTypeTimestamps(results, 500L);
+ verifyNodeTimestamps(results, 1000L);
+
+ equipType = "other-ps-type-recreated";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAfterUpdateTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=700";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results);
+ verifyEquipTypeSoTs(results);
+ verifyEquipTypeTxId(results);
+ verifyEquipTypeTimestamps(results);
+ verifyNodeTimestamps(results, 1000L);
+
+ String equipType = "first-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+
+ equipType = "other-ps-type-recreated";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAtDeleteTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=1000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+ assertEquals("properties size should be 0",
+ results.get(0).getAsJsonObject().get("properties").getAsJsonArray().size(), 0);
+
+ String equipType = "first-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ }
+
+ @Test
+ public void lifecycleQueryStartTsAfterDeleteTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=lifecycle&startTs=5000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 0, results.size());
+
+ String equipType = "first-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+
+ equipType = "other-ps-type-recreated";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryStateEdgeTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryStateEdgeTest.java
index 4e122dc..6b9815c 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryStateEdgeTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryStateEdgeTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,10 +19,16 @@
*/
package org.onap.aai.rest.history;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.*;
+
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonObject;
import com.google.gson.JsonParser;
+
+import java.util.*;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.janusgraph.core.JanusGraphTransaction;
@@ -38,439 +44,372 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
-import java.util.*;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.*;
-
-@Ignore("The state format requires the history schema to be loaded. " +
- "Because aaigraph is a singleton its very complicated to have 2 different schemas loaded for testing. " +
- "This needs to be addressed.")
+@Ignore("The state format requires the history schema to be loaded. "
+ + "Because aaigraph is a singleton its very complicated to have 2 different schemas loaded for testing. "
+ + "This needs to be addressed.")
public class DslConsumerHistoryStateEdgeTest extends AbstractSpringHistoryRestTest {
- private static final Logger LOGGER = LoggerFactory.getLogger(DslConsumerHistoryStateEdgeTest.class);
-
- @Override
- public void createTestGraph() {
- JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
- boolean success = true;
- try {
- GraphTraversalSource g = transaction.traversal();
-
- Vertex pserver = g.addV().property(AAIProperties.NODE_TYPE, "pserver",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/test-pserver-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.RESOURCE_VERSION, "100",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property("hostname", "test-pserver-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property("in-maint", false,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property("equip-type", "ps-type",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.START_TS, 100L,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .next();
- Vertex complex = g.addV().property(AAIProperties.NODE_TYPE, "complex",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/complexes/complex/test-complex-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.RESOURCE_VERSION, "100",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property("physical-location-id", "test-complex-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property("street", "200 S. Laurel Ave",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property("city", "Middletown",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property("state", "NJ",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property("zip", "11111",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .property(AAIProperties.START_TS, 100L,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 100L
- )
- .next();
-
- pserver.addEdge("org.onap.relationships.inventory.LocatedIn",
- complex,
- "start-ts", 100,
- "private", false,
- "aai-uuid", "edge1",
- "end-source-of-truth", "JUNIT-E-D-1",
- "end-tx-id", "JUNIT-E-D-1",
- "end-ts", 300,
- "prevent-delete", "IN",
- "delete-other-v", "NONE",
- "source-of-truth", "JUNIT-E-C-1",
- "start-tx-id", "JUNIT-E-C-1",
- "contains-other-v", "NONE"
- );
- pserver.addEdge("org.onap.relationships.inventory.LocatedIn",
- complex,
- "start-ts", 500,
- "private", false,
- "aai-uuid", "edge2",
- "end-source-of-truth", "JUNIT-E-D-2",
- "end-tx-id", "JUNIT-E-D-2",
- "end-ts", 700,
- "prevent-delete", "IN",
- "delete-other-v", "NONE",
- "source-of-truth", "JUNIT-E-C-2",
- "start-tx-id", "JUNIT-E-C-2",
- "contains-other-v", "NONE"
- );
- pserver.addEdge("org.onap.relationships.inventory.LocatedIn",
- complex,
- "start-ts", 900,
- "private", false,
- "aai-uuid", "edge3",
- "end-source-of-truth", "JUNIT-E-D-3",
- "end-tx-id", "JUNIT-E-D-3",
- "end-ts", 1100,
- "prevent-delete", "IN",
- "delete-other-v", "NONE",
- "source-of-truth", "JUNIT-E-C-3",
- "start-tx-id", "JUNIT-E-C-3",
- "contains-other-v", "NONE"
- );
- pserver.addEdge("org.onap.relationships.inventory.LocatedIn",
- complex,
- "start-ts", 1300,
- "private", false,
- "aai-uuid", "edge3",
- "prevent-delete", "IN",
- "delete-other-v", "NONE",
- "source-of-truth", "JUNIT-E-C-3",
- "start-tx-id", "JUNIT-E-C-3",
- "contains-other-v", "NONE"
- );
- } catch (Exception ex) {
- success = false;
- } finally {
- if (success) {
- transaction.commit();
- } else {
- transaction.rollback();
- fail("Unable to setup the graph");
- }
- }
- }
-
- private JsonArray getResultsForPserverLookupByHostname(String endpoint) throws Exception {
- return getResultsForPserverLookupByHostnameAndAnother(endpoint, "");
- }
-
- private JsonArray getResultsForPserverLookupByHostnameAndAnother(String endpoint, String additionalFilterInParen) throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver*('hostname','test-pserver-dsl')" + additionalFilterInParen);
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- JsonArray results = new JsonParser().parse(responseEntity.getBody().toString()).getAsJsonObject().getAsJsonArray("results");
- LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint, responseEntity.getBody());
-
- assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
- assertEquals("Expected the response to be 200", HttpStatus.OK, responseEntity.getStatusCode());
- return results;
- }
-
-
- private void verifyEquipTypeValues(JsonArray results, String... expectedEquipTypes) {
- List<String> expected = Arrays.asList(expectedEquipTypes);
- final List<String> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- assertFalse("State format properties should not have end timestamps",
- property.getAsJsonObject().has("end-timestamp"));
- if (property.getAsJsonObject().has("value") && !property.getAsJsonObject().get("value").isJsonNull()) {
- actualEquipType.add(property.getAsJsonObject().get("value").getAsString());
- } else {
- actualEquipType.add(null);
- }
- }
- }
- }
- assertThat("Verify equip-type in state", actualEquipType, is(expected));
- }
-
- private void verifyEquipTypeSoTs(JsonArray results, String... expectedSTOs) {
- List<String> expected = Arrays.asList(expectedSTOs);
- final List<String> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- if (property.getAsJsonObject().has("sot") && !property.getAsJsonObject().get("sot").isJsonNull()) {
- actualEquipType.add(property.getAsJsonObject().get("sot").getAsString());
- } else {
- actualEquipType.add(null);
- }
- }
- }
- }
- assertThat("Verify equip-type SoTs in state", actualEquipType, is(expected));
- }
-
- private void verifyEquipTypeTimestamps(JsonArray results, Long... expectedSTOs) {
- List<Long> expected = Arrays.asList(expectedSTOs);
- final List<Long> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- if (property.getAsJsonObject().has("timestamp") && !property.getAsJsonObject().get("timestamp").isJsonNull()) {
- actualEquipType.add(property.getAsJsonObject().get("timestamp").getAsLong());
- } else {
- actualEquipType.add(null);
- }
- }
- }
- }
- assertThat("Verify equip-type timestamps in state", actualEquipType, is(expected));
- }
-
- private void verifyRelatedToCreatedTimestamps(JsonArray results, Long... edgeCreatedTimestamps) {
- List<Long> expected = Arrays.asList(edgeCreatedTimestamps);
- final List<Long> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- result.getAsJsonObject().get("related-to").getAsJsonArray().forEach(jsonElement ->
- actualEquipType.add(jsonElement.getAsJsonObject().get("timestamp").getAsLong()));
- }
- assertThat("Verify related-to createdtimestamps in state", actualEquipType, is(expected));
- }
-
- private void verifyRelatedToCreatedDeletedTimestamps(JsonArray results, Long... edgeDeletedTimestamps) {
- List<Long> expected = Arrays.asList(edgeDeletedTimestamps);
- final List<Long> actualEquipType = new ArrayList<>();
- for (JsonElement result : results) {
- result.getAsJsonObject().get("related-to").getAsJsonArray().forEach(jsonElement -> {
- if (jsonElement.getAsJsonObject().has("end-timestamp")) {
- actualEquipType.add(jsonElement.getAsJsonObject().get("end-timestamp").getAsLong());
- }
- });
- }
- assertThat("Verify related-to created timestamps in state", actualEquipType, is(expected));
- }
-
- private void verifyRelatedToCount(JsonArray results, int expectedSize) {
- int actualSize = 0;
- for (JsonElement result : results) {
- actualSize += result.getAsJsonObject().get("related-to").getAsJsonArray().size();
- }
- assertEquals("Verify related-to count", actualSize, expectedSize);
- }
-
- private void verifyAllPropsTxIds(JsonArray results) {
- final Set<String> propMissingCreatedTxId = new HashSet<>();
- final Set<String> propContainingEndTxId = new HashSet<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (!property.getAsJsonObject().has("tx-id")) {
- propMissingCreatedTxId.add(property.getAsJsonObject().get("key").getAsString());
- }
- if (property.getAsJsonObject().has("end-tx-id")) {
- propContainingEndTxId.add(property.getAsJsonObject().get("key").getAsString());
- }
- }
- }
-
- assertThat("Verify no prop is missing tx-id in state", propMissingCreatedTxId, is(Collections.EMPTY_SET));
- assertThat("Verify no prop has end-tx-id in state", propContainingEndTxId, is(Collections.EMPTY_SET));
- }
-
- private void verifyRelatedToCreatedTxId(JsonArray results) {
- final Set<JsonObject> edgeMissingCreatedTxId = new HashSet<>();
- final Set<JsonObject> edgeContainingEndTxId = new HashSet<>();
- for (JsonElement result : results) {
- result.getAsJsonObject().get("related-to").getAsJsonArray().forEach(jsonElement -> {
- if (!jsonElement.getAsJsonObject().has("tx-id")) {
- edgeMissingCreatedTxId.add(jsonElement.getAsJsonObject());
- }
- if (jsonElement.getAsJsonObject().has("end-tx-id")) {
- edgeContainingEndTxId.add(jsonElement.getAsJsonObject());
- }
- });
- }
- assertThat("Verify no related-to is missing tx-id in state", edgeMissingCreatedTxId, is(Collections.EMPTY_SET));
- assertThat("Verify no related-to has end-tx-id in state", edgeContainingEndTxId, is(Collections.EMPTY_SET));
- }
-
- @Test
- public void stateQueryStartTsBeforeCreationTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=state&startTs=50";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 0, results.size());
-
- verifyEquipTypeValues(results);
- verifyEquipTypeSoTs(results);
- verifyEquipTypeTimestamps(results);
- verifyRelatedToCreatedTimestamps(results);
- verifyRelatedToCreatedDeletedTimestamps(results);
- verifyRelatedToCount(results, 0);
- verifyAllPropsTxIds(results);
- verifyRelatedToCreatedTxId(results);
- }
-
-
-
- @Test
- public void stateQueryStartTsBeforeSecondEdgeCreationTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=state&startTs=400";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, "ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-C");
- verifyEquipTypeTimestamps(results, 100L);
- verifyRelatedToCreatedTimestamps(results);
- verifyRelatedToCreatedDeletedTimestamps(results);
- verifyRelatedToCount(results, 0);
- verifyAllPropsTxIds(results);
- verifyRelatedToCreatedTxId(results);
- }
-
- @Test
- public void stateQueryStartTsAfterSecondEdgeCreationTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=state&startTs=600";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, "ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-C");
- verifyEquipTypeTimestamps(results, 100L);
- verifyRelatedToCreatedTimestamps(results, 500L);
- verifyRelatedToCreatedDeletedTimestamps(results);
- verifyRelatedToCount(results, 1);
- verifyAllPropsTxIds(results);
- verifyRelatedToCreatedTxId(results);
- }
-
- @Test
- public void stateQueryStartTsAtSecondEdgeDeletionTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=state&startTs=700";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, "ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-C");
- verifyEquipTypeTimestamps(results, 100L);
- verifyRelatedToCreatedTimestamps(results);
- verifyRelatedToCreatedDeletedTimestamps(results);
- verifyRelatedToCount(results, 0);
- verifyAllPropsTxIds(results);
- verifyRelatedToCreatedTxId(results);
- }
-
- @Test
- public void stateQueryStartTsAfterSecondEdgeDeletionTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=state&startTs=800";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, "ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-C");
- verifyEquipTypeTimestamps(results, 100L);
- verifyRelatedToCreatedTimestamps(results);
- verifyRelatedToCreatedDeletedTimestamps(results);
- verifyRelatedToCount(results, 0);
- verifyAllPropsTxIds(results);
- verifyRelatedToCreatedTxId(results);
- }
-
- @Test
- public void stateQueryStartTsAtLastEdgeActionTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=state&startTs=1300";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, "ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-C");
- verifyEquipTypeTimestamps(results, 100L);
- verifyRelatedToCreatedTimestamps(results, 1300L);
- verifyRelatedToCreatedDeletedTimestamps(results);
- verifyRelatedToCount(results, 1);
- verifyAllPropsTxIds(results);
- verifyRelatedToCreatedTxId(results);
- }
-
- @Test
- public void stateQueryStartTsAfterLastEdgeActionTimeTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=state&startTs=1400";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals("Result size", 1, results.size());
-
- verifyEquipTypeValues(results, "ps-type");
- verifyEquipTypeSoTs(results, "JUNIT-C");
- verifyEquipTypeTimestamps(results, 100L);
- verifyRelatedToCreatedTimestamps(results, 1300L);
- verifyRelatedToCreatedDeletedTimestamps(results);
- verifyRelatedToCount(results, 1);
- verifyAllPropsTxIds(results);
- verifyRelatedToCreatedTxId(results);
- }
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(DslConsumerHistoryStateEdgeTest.class);
+
+ @Override
+ public void createTestGraph() {
+ JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
+ boolean success = true;
+ try {
+ GraphTraversalSource g = transaction.traversal();
+
+ Vertex pserver = g.addV()
+ .property(AAIProperties.NODE_TYPE, "pserver", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.AAI_URI,
+ "/cloud-infrastructure/pservers/pserver/test-pserver-dsl",
+ AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C",
+ AAIProperties.START_TS, 100L)
+ .property(AAIProperties.RESOURCE_VERSION, "100", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("hostname", "test-pserver-dsl", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("in-maint", false, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("equip-type", "ps-type", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.START_TS, 100L, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .next();
+ Vertex complex = g.addV()
+ .property(AAIProperties.NODE_TYPE, "complex", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.AAI_URI,
+ "/cloud-infrastructure/complexes/complex/test-complex-dsl",
+ AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C",
+ AAIProperties.START_TS, 100L)
+ .property(AAIProperties.RESOURCE_VERSION, "100", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("physical-location-id", "test-complex-dsl", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("street", "200 S. Laurel Ave", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("city", "Middletown", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("state", "NJ", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property("zip", "11111", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .property(AAIProperties.START_TS, 100L, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 100L)
+ .next();
+
+ pserver.addEdge("org.onap.relationships.inventory.LocatedIn", complex, "start-ts", 100,
+ "private", false, "aai-uuid", "edge1", "end-source-of-truth", "JUNIT-E-D-1",
+ "end-tx-id", "JUNIT-E-D-1", "end-ts", 300, "prevent-delete", "IN", "delete-other-v",
+ "NONE", "source-of-truth", "JUNIT-E-C-1", "start-tx-id", "JUNIT-E-C-1",
+ "contains-other-v", "NONE");
+ pserver.addEdge("org.onap.relationships.inventory.LocatedIn", complex, "start-ts", 500,
+ "private", false, "aai-uuid", "edge2", "end-source-of-truth", "JUNIT-E-D-2",
+ "end-tx-id", "JUNIT-E-D-2", "end-ts", 700, "prevent-delete", "IN", "delete-other-v",
+ "NONE", "source-of-truth", "JUNIT-E-C-2", "start-tx-id", "JUNIT-E-C-2",
+ "contains-other-v", "NONE");
+ pserver.addEdge("org.onap.relationships.inventory.LocatedIn", complex, "start-ts", 900,
+ "private", false, "aai-uuid", "edge3", "end-source-of-truth", "JUNIT-E-D-3",
+ "end-tx-id", "JUNIT-E-D-3", "end-ts", 1100, "prevent-delete", "IN",
+ "delete-other-v", "NONE", "source-of-truth", "JUNIT-E-C-3", "start-tx-id",
+ "JUNIT-E-C-3", "contains-other-v", "NONE");
+ pserver.addEdge("org.onap.relationships.inventory.LocatedIn", complex, "start-ts", 1300,
+ "private", false, "aai-uuid", "edge3", "prevent-delete", "IN", "delete-other-v",
+ "NONE", "source-of-truth", "JUNIT-E-C-3", "start-tx-id", "JUNIT-E-C-3",
+ "contains-other-v", "NONE");
+ } catch (Exception ex) {
+ success = false;
+ } finally {
+ if (success) {
+ transaction.commit();
+ } else {
+ transaction.rollback();
+ fail("Unable to setup the graph");
+ }
+ }
+ }
+
+ private JsonArray getResultsForPserverLookupByHostname(String endpoint) throws Exception {
+ return getResultsForPserverLookupByHostnameAndAnother(endpoint, "");
+ }
+
+ private JsonArray getResultsForPserverLookupByHostnameAndAnother(String endpoint,
+ String additionalFilterInParen) throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "pserver*('hostname','test-pserver-dsl')" + additionalFilterInParen);
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ JsonArray results = new JsonParser().parse(responseEntity.getBody().toString())
+ .getAsJsonObject().getAsJsonArray("results");
+ LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint,
+ responseEntity.getBody());
+
+ assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
+ assertEquals("Expected the response to be 200", HttpStatus.OK,
+ responseEntity.getStatusCode());
+ return results;
+ }
+
+ private void verifyEquipTypeValues(JsonArray results, String... expectedEquipTypes) {
+ List<String> expected = Arrays.asList(expectedEquipTypes);
+ final List<String> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ assertFalse("State format properties should not have end timestamps",
+ property.getAsJsonObject().has("end-timestamp"));
+ if (property.getAsJsonObject().has("value")
+ && !property.getAsJsonObject().get("value").isJsonNull()) {
+ actualEquipType.add(property.getAsJsonObject().get("value").getAsString());
+ } else {
+ actualEquipType.add(null);
+ }
+ }
+ }
+ }
+ assertThat("Verify equip-type in state", actualEquipType, is(expected));
+ }
+
+ private void verifyEquipTypeSoTs(JsonArray results, String... expectedSTOs) {
+ List<String> expected = Arrays.asList(expectedSTOs);
+ final List<String> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ if (property.getAsJsonObject().has("sot")
+ && !property.getAsJsonObject().get("sot").isJsonNull()) {
+ actualEquipType.add(property.getAsJsonObject().get("sot").getAsString());
+ } else {
+ actualEquipType.add(null);
+ }
+ }
+ }
+ }
+ assertThat("Verify equip-type SoTs in state", actualEquipType, is(expected));
+ }
+
+ private void verifyEquipTypeTimestamps(JsonArray results, Long... expectedSTOs) {
+ List<Long> expected = Arrays.asList(expectedSTOs);
+ final List<Long> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ if (property.getAsJsonObject().has("timestamp")
+ && !property.getAsJsonObject().get("timestamp").isJsonNull()) {
+ actualEquipType
+ .add(property.getAsJsonObject().get("timestamp").getAsLong());
+ } else {
+ actualEquipType.add(null);
+ }
+ }
+ }
+ }
+ assertThat("Verify equip-type timestamps in state", actualEquipType, is(expected));
+ }
+
+ private void verifyRelatedToCreatedTimestamps(JsonArray results,
+ Long... edgeCreatedTimestamps) {
+ List<Long> expected = Arrays.asList(edgeCreatedTimestamps);
+ final List<Long> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ result.getAsJsonObject().get("related-to").getAsJsonArray()
+ .forEach(jsonElement -> actualEquipType
+ .add(jsonElement.getAsJsonObject().get("timestamp").getAsLong()));
+ }
+ assertThat("Verify related-to createdtimestamps in state", actualEquipType, is(expected));
+ }
+
+ private void verifyRelatedToCreatedDeletedTimestamps(JsonArray results,
+ Long... edgeDeletedTimestamps) {
+ List<Long> expected = Arrays.asList(edgeDeletedTimestamps);
+ final List<Long> actualEquipType = new ArrayList<>();
+ for (JsonElement result : results) {
+ result.getAsJsonObject().get("related-to").getAsJsonArray().forEach(jsonElement -> {
+ if (jsonElement.getAsJsonObject().has("end-timestamp")) {
+ actualEquipType
+ .add(jsonElement.getAsJsonObject().get("end-timestamp").getAsLong());
+ }
+ });
+ }
+ assertThat("Verify related-to created timestamps in state", actualEquipType, is(expected));
+ }
+
+ private void verifyRelatedToCount(JsonArray results, int expectedSize) {
+ int actualSize = 0;
+ for (JsonElement result : results) {
+ actualSize += result.getAsJsonObject().get("related-to").getAsJsonArray().size();
+ }
+ assertEquals("Verify related-to count", actualSize, expectedSize);
+ }
+
+ private void verifyAllPropsTxIds(JsonArray results) {
+ final Set<String> propMissingCreatedTxId = new HashSet<>();
+ final Set<String> propContainingEndTxId = new HashSet<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (!property.getAsJsonObject().has("tx-id")) {
+ propMissingCreatedTxId.add(property.getAsJsonObject().get("key").getAsString());
+ }
+ if (property.getAsJsonObject().has("end-tx-id")) {
+ propContainingEndTxId.add(property.getAsJsonObject().get("key").getAsString());
+ }
+ }
+ }
+
+ assertThat("Verify no prop is missing tx-id in state", propMissingCreatedTxId,
+ is(Collections.EMPTY_SET));
+ assertThat("Verify no prop has end-tx-id in state", propContainingEndTxId,
+ is(Collections.EMPTY_SET));
+ }
+
+ private void verifyRelatedToCreatedTxId(JsonArray results) {
+ final Set<JsonObject> edgeMissingCreatedTxId = new HashSet<>();
+ final Set<JsonObject> edgeContainingEndTxId = new HashSet<>();
+ for (JsonElement result : results) {
+ result.getAsJsonObject().get("related-to").getAsJsonArray().forEach(jsonElement -> {
+ if (!jsonElement.getAsJsonObject().has("tx-id")) {
+ edgeMissingCreatedTxId.add(jsonElement.getAsJsonObject());
+ }
+ if (jsonElement.getAsJsonObject().has("end-tx-id")) {
+ edgeContainingEndTxId.add(jsonElement.getAsJsonObject());
+ }
+ });
+ }
+ assertThat("Verify no related-to is missing tx-id in state", edgeMissingCreatedTxId,
+ is(Collections.EMPTY_SET));
+ assertThat("Verify no related-to has end-tx-id in state", edgeContainingEndTxId,
+ is(Collections.EMPTY_SET));
+ }
+
+ @Test
+ public void stateQueryStartTsBeforeCreationTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=state&startTs=50";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 0, results.size());
+
+ verifyEquipTypeValues(results);
+ verifyEquipTypeSoTs(results);
+ verifyEquipTypeTimestamps(results);
+ verifyRelatedToCreatedTimestamps(results);
+ verifyRelatedToCreatedDeletedTimestamps(results);
+ verifyRelatedToCount(results, 0);
+ verifyAllPropsTxIds(results);
+ verifyRelatedToCreatedTxId(results);
+ }
+
+ @Test
+ public void stateQueryStartTsBeforeSecondEdgeCreationTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=state&startTs=400";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, "ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 100L);
+ verifyRelatedToCreatedTimestamps(results);
+ verifyRelatedToCreatedDeletedTimestamps(results);
+ verifyRelatedToCount(results, 0);
+ verifyAllPropsTxIds(results);
+ verifyRelatedToCreatedTxId(results);
+ }
+
+ @Test
+ public void stateQueryStartTsAfterSecondEdgeCreationTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=state&startTs=600";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, "ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 100L);
+ verifyRelatedToCreatedTimestamps(results, 500L);
+ verifyRelatedToCreatedDeletedTimestamps(results);
+ verifyRelatedToCount(results, 1);
+ verifyAllPropsTxIds(results);
+ verifyRelatedToCreatedTxId(results);
+ }
+
+ @Test
+ public void stateQueryStartTsAtSecondEdgeDeletionTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=state&startTs=700";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, "ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 100L);
+ verifyRelatedToCreatedTimestamps(results);
+ verifyRelatedToCreatedDeletedTimestamps(results);
+ verifyRelatedToCount(results, 0);
+ verifyAllPropsTxIds(results);
+ verifyRelatedToCreatedTxId(results);
+ }
+
+ @Test
+ public void stateQueryStartTsAfterSecondEdgeDeletionTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=state&startTs=800";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, "ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 100L);
+ verifyRelatedToCreatedTimestamps(results);
+ verifyRelatedToCreatedDeletedTimestamps(results);
+ verifyRelatedToCount(results, 0);
+ verifyAllPropsTxIds(results);
+ verifyRelatedToCreatedTxId(results);
+ }
+
+ @Test
+ public void stateQueryStartTsAtLastEdgeActionTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=state&startTs=1300";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, "ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 100L);
+ verifyRelatedToCreatedTimestamps(results, 1300L);
+ verifyRelatedToCreatedDeletedTimestamps(results);
+ verifyRelatedToCount(results, 1);
+ verifyAllPropsTxIds(results);
+ verifyRelatedToCreatedTxId(results);
+ }
+
+ @Test
+ public void stateQueryStartTsAfterLastEdgeActionTimeTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=state&startTs=1400";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals("Result size", 1, results.size());
+
+ verifyEquipTypeValues(results, "ps-type");
+ verifyEquipTypeSoTs(results, "JUNIT-C");
+ verifyEquipTypeTimestamps(results, 100L);
+ verifyRelatedToCreatedTimestamps(results, 1300L);
+ verifyRelatedToCreatedDeletedTimestamps(results);
+ verifyRelatedToCount(results, 1);
+ verifyAllPropsTxIds(results);
+ verifyRelatedToCreatedTxId(results);
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryStateTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryStateTest.java
index bb9584e..5b08d83 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryStateTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/history/DslConsumerHistoryStateTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,9 +19,15 @@
*/
package org.onap.aai.rest.history;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.*;
+
import com.google.gson.JsonArray;
import com.google.gson.JsonElement;
import com.google.gson.JsonParser;
+
+import java.util.*;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
import org.janusgraph.core.JanusGraphTransaction;
import org.junit.Ignore;
@@ -36,735 +42,704 @@ import org.springframework.http.HttpMethod;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
-import java.util.*;
-
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.*;
-
-@Ignore("The state format requires the history schema to be loaded. " +
- "Because aaigraph is a singleton its very complicated to have 2 different schemas loaded for testing. " +
- "This needs to be addressed.")
+@Ignore("The state format requires the history schema to be loaded. "
+ + "Because aaigraph is a singleton its very complicated to have 2 different schemas loaded for testing. "
+ + "This needs to be addressed.")
public class DslConsumerHistoryStateTest extends AbstractSpringHistoryRestTest {
- private static final Logger LOGGER = LoggerFactory.getLogger(DslConsumerHistoryStateTest.class);
-
- @Override
- public void createTestGraph() {
- JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
- boolean success = true;
- try {
- GraphTraversalSource g = transaction.traversal();
- /*
- Pserver
- - created @ time 100
- - update in-maint/equip-type @ 500
- - deleted @ time 1000
- */
- g.addV().property(AAIProperties.NODE_TYPE, "pserver",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/test-pserver-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.RESOURCE_VERSION, "100",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-U",
- AAIProperties.END_TX_ID, "JUNIT-U",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 500L
- )
- .property(AAIProperties.RESOURCE_VERSION, "500",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U",
- AAIProperties.START_TX_ID, "JUNIT-U",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 500L,
- AAIProperties.END_TS, 1000L
- )
- .property("hostname", "test-pserver-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property("in-maint", false,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-U",
- AAIProperties.END_TX_ID, "JUNIT-U",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 500L
- )
- .property("in-maint", true,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U",
- AAIProperties.START_TX_ID, "JUNIT-U",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 500L,
- AAIProperties.END_TS, 1000L
- )
- .property("equip-type", "first-ps-type",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-U",
- AAIProperties.END_TX_ID, "JUNIT-U",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 500L
- )
- .property("equip-type", "first-ps-type-update",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U",
- AAIProperties.START_TX_ID, "JUNIT-U",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 500L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-D",
- AAIProperties.START_TX_ID, "JUNIT-D",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.START_TS, 100L,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 100L,
- AAIProperties.END_TS, 1000L
- )
- .property(AAIProperties.END_TS, 1000L,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-D",
- AAIProperties.START_TX_ID, "JUNIT-D",
- AAIProperties.END_SOT, "JUNIT-D",
- AAIProperties.END_TX_ID, "JUNIT-D",
- AAIProperties.START_TS, 1000L,
- AAIProperties.END_TS, 1000L
- )
- .next();
-
- /*
- Pserver
- - created @ time 10000
- - update in-maint/equip-type @ 15000
- */
- g.addV().property(AAIProperties.NODE_TYPE, "pserver",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 10000L
- )
- .property(AAIProperties.AAI_URI, "/cloud-infrastructure/pservers/pserver/test-pserver-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 10000L
- )
- .property(AAIProperties.RESOURCE_VERSION, "10000",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-U",
- AAIProperties.END_TX_ID, "JUNIT-U",
- AAIProperties.START_TS, 10000L,
- AAIProperties.END_TS, 15000L
- )
- .property(AAIProperties.RESOURCE_VERSION, "15000",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U",
- AAIProperties.START_TX_ID, "JUNIT-U",
- AAIProperties.START_TS, 15000
- )
- .property("hostname", "test-pserver-dsl",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 10000L
- )
- .property("in-maint", true,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-U",
- AAIProperties.END_TX_ID, "JUNIT-U",
- AAIProperties.START_TS, 10000L,
- AAIProperties.END_TS, 15000L
- )
- .property("in-maint", false,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U",
- AAIProperties.START_TX_ID, "JUNIT-U",
- AAIProperties.START_TS, 15000L
- )
- .property("equip-type", "second-ps-type",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.END_SOT, "JUNIT-U",
- AAIProperties.END_TX_ID, "JUNIT-U",
- AAIProperties.START_TS, 10000L,
- AAIProperties.END_TS, 15000L
- )
- .property("equip-type", "second-ps-type-update",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U",
- AAIProperties.START_TX_ID, "JUNIT-U",
- AAIProperties.START_TS, 15000L
- )
- .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 10000L
- )
- .property(AAIProperties.START_TS, 10000L,
- AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
- AAIProperties.START_TX_ID, "JUNIT-C",
- AAIProperties.START_TS, 10000L
- )
- .next();
- } catch (Exception ex) {
- success = false;
- } finally {
- if (success) {
- transaction.commit();
- } else {
- transaction.rollback();
- fail("Unable to setup the graph");
- }
- }
- }
-
- private JsonArray getResultsForPserverLookupByHostname(String endpoint) throws Exception {
- return getResultsForPserverLookupByHostnameAndAnother(endpoint, "");
- }
-
- private JsonArray getResultsForPserverLookupByHostnameAndAnother(String endpoint, String additionalFilterInParen) throws Exception {
- Map<String, String> dslQueryMap = new HashMap<>();
- dslQueryMap.put("dsl-query", "pserver*('hostname','test-pserver-dsl')" + additionalFilterInParen);
- String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
- httpEntity = new HttpEntity(payload, headers);
- ResponseEntity responseEntity = restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
- JsonArray results = new JsonParser().parse(responseEntity.getBody().toString()).getAsJsonObject().getAsJsonArray("results");
- LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint, responseEntity.getBody());
-
- assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
- assertEquals("Expected the response to be 200", HttpStatus.OK, responseEntity.getStatusCode());
- return results;
- }
-
- private void verifyEquipTypeValues(JsonArray results, String... equipType) {
- Set<String> expectedEquipTypes = new HashSet<>(Arrays.asList(equipType));
- final Set<String> actualEquipType = new HashSet<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- assertFalse("State format properties should not have end timestamps",
- property.getAsJsonObject().has("end-timestamp"));
- if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
- actualEquipType.add(property.getAsJsonObject().get("value").getAsString());
- }
- }
- }
- assertThat("Verify equip-type in state", actualEquipType, is(expectedEquipTypes));
- }
-
-
- private void verifyAllPropsTxIds(JsonArray results) {
- final Set<String> propMissingCreatedTxId = new HashSet<>();
- final Set<String> propContainingEndTxId = new HashSet<>();
- for (JsonElement result : results) {
- for (JsonElement property : result.getAsJsonObject().get("properties").getAsJsonArray()) {
- if (!property.getAsJsonObject().has("tx-id")) {
- propMissingCreatedTxId.add(property.getAsJsonObject().get("key").getAsString());
- }
- if (property.getAsJsonObject().has("end-tx-id")) {
- propContainingEndTxId.add(property.getAsJsonObject().get("key").getAsString());
- }
- }
- }
-
- assertThat("Verify no prop is missing tx-id in state", propMissingCreatedTxId, is(Collections.EMPTY_SET));
- assertThat("Verify no prop has end-tx-id in state", propContainingEndTxId, is(Collections.EMPTY_SET));
- }
-
- @Test
- public void stateQueryBeforeCreationTimeTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=50";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(0, results.size());
- }
-
- @Test
- public void stateQueryAtCreationTimeTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=100";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(1, results.size());
- verifyEquipTypeValues(results, "first-ps-type");
- verifyAllPropsTxIds(results);
- }
-
- @Test
- public void stateQueryAfterCreationTimeTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=200";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(1, results.size());
- verifyEquipTypeValues(results, "first-ps-type");
- verifyAllPropsTxIds(results);
- }
-
- @Test
- public void stateQueryAtUpdateTimeTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=500";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(1, results.size());
- verifyEquipTypeValues(results, "first-ps-type-update");
- verifyAllPropsTxIds(results);
- }
-
- @Test
- public void stateQueryAfterUpdateTimeTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=700";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(1, results.size());
- verifyEquipTypeValues(results, "first-ps-type-update");
- verifyAllPropsTxIds(results);
- }
-
- @Test
- public void stateQueryAtDeletionTimeTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=1000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(0, results.size());
- }
-
- @Test
- public void stateQueryAfterDeletionTimeTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=2000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(0, results.size());
- }
-
- // WITH endTs=startTs
- @Test
- public void stateQueryBeforeCreationWithEndTsTimeTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=50&endTs=50";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(0, results.size());
- }
-
- @Test
- public void stateQueryAtCreationTimeWithEndTsTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=100&endTs=100";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(1, results.size());
- verifyEquipTypeValues(results, "first-ps-type");
- verifyAllPropsTxIds(results);
- }
-
- @Test
- public void stateQueryAfterCreationTimeWithEndTsTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=200&endTs=200";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(1, results.size());
- verifyEquipTypeValues(results, "first-ps-type");
- verifyAllPropsTxIds(results);
- }
-
- @Test
- public void stateQueryAtUpdateTimeWithEndTsTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=500&endTs=500";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(1, results.size());
- verifyEquipTypeValues(results, "first-ps-type-update");
- verifyAllPropsTxIds(results);
- }
-
- @Test
- public void stateQueryAfterUpdateTimeWithEndTsTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=700&endTs=700";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(1, results.size());
- verifyEquipTypeValues(results, "first-ps-type-update");
- verifyAllPropsTxIds(results);
- }
-
- @Test
- public void stateQueryAtDeletionTimeWithEndTsTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=1000&endTs=1000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(0, results.size());
- }
-
- @Test
- public void stateQueryAfterDeletionTimeWithEndTsTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=2000&endTs=2000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(0, results.size());
- }
-
- // Second pserver
-
- @Test
- public void stateQueryBeforeSecondCreationTimeTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=9000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(0, results.size());
- }
-
- @Test
- public void stateQueryAtSecondCreationTimeTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=10000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(1, results.size());
- verifyEquipTypeValues(results, "second-ps-type");
- verifyAllPropsTxIds(results);
- }
-
- @Test
- public void stateQueryAfterSecondCreationTimeTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=12000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(1, results.size());
- verifyEquipTypeValues(results, "second-ps-type");
- verifyAllPropsTxIds(results);
- }
-
- @Test
- public void stateQueryAtUpdateAfterSecondCreationTimeTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=15000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(1, results.size());
- verifyEquipTypeValues(results, "second-ps-type-update");
- verifyAllPropsTxIds(results);
- }
-
- @Test
- public void stateQueryAfterUpdateAfterSecondCreationTimeTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=17000";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(1, results.size());
- verifyEquipTypeValues(results, "second-ps-type-update");
- verifyAllPropsTxIds(results);
- }
-
- @Test
- public void stateQueryNoTimestampTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state";
- JsonArray results = getResultsForPserverLookupByHostname(endpoint);
- assertEquals(1, results.size());
- verifyEquipTypeValues(results, "second-ps-type-update");
- verifyAllPropsTxIds(results);
- }
-
- @Test
- public void stateQueryNoTimestampWithEquipTypeFilterTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=state";
- String equipType = "first-ps-type";
- JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
-
- equipType = "first-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
-
- equipType = "second-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
-
- equipType = "second-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
-
- verifyEquipTypeValues(results, equipType);
-
- verifyAllPropsTxIds(results);
- }
-
- @Test
- public void stateQueryTimestampBeforeFirstCreateWithEquipTypeFilterTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=state&startTs=50";
- String equipType = "first-ps-type";
- JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
-
- equipType = "first-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
-
- equipType = "second-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
-
- equipType = "second-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
-
- }
-
- @Test
- public void stateQueryTimestampAtFirstCreateWithEquipTypeFilterTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=state&startTs=100";
- String equipType = "first-ps-type";
- JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
-
- verifyEquipTypeValues(results, equipType);
-
- verifyAllPropsTxIds(results);
-
- equipType = "first-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
-
- equipType = "second-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
-
- equipType = "second-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
-
- }
-
- @Test
- public void stateQueryTimestampAfterFirstCreateWithEquipTypeFilterTest() throws Exception {
-
- String endpoint = "/aai/v14/dsl?format=state&startTs=200";
- String equipType = "first-ps-type";
- JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ private static final Logger LOGGER = LoggerFactory.getLogger(DslConsumerHistoryStateTest.class);
+
+ @Override
+ public void createTestGraph() {
+ JanusGraphTransaction transaction = AAIGraph.getInstance().getGraph().newTransaction();
+ boolean success = true;
+ try {
+ GraphTraversalSource g = transaction.traversal();
+ /*
+ * Pserver
+ * - created @ time 100
+ * - update in-maint/equip-type @ 500
+ * - deleted @ time 1000
+ */
+ g.addV()
+ .property(AAIProperties.NODE_TYPE, "pserver", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT,
+ "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.AAI_URI,
+ "/cloud-infrastructure/pservers/pserver/test-pserver-dsl",
+ AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C",
+ AAIProperties.END_SOT, "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D",
+ AAIProperties.START_TS, 100L, AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.RESOURCE_VERSION, "100", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT,
+ "JUNIT-U", AAIProperties.END_TX_ID, "JUNIT-U", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 500L)
+ .property(AAIProperties.RESOURCE_VERSION, "500", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-U", AAIProperties.START_TX_ID, "JUNIT-U", AAIProperties.END_SOT,
+ "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 500L,
+ AAIProperties.END_TS, 1000L)
+ .property("hostname", "test-pserver-dsl", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT, "JUNIT-D",
+ AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property("in-maint", false, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT, "JUNIT-U",
+ AAIProperties.END_TX_ID, "JUNIT-U", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 500L)
+ .property("in-maint", true, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U",
+ AAIProperties.START_TX_ID, "JUNIT-U", AAIProperties.END_SOT, "JUNIT-D",
+ AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 500L,
+ AAIProperties.END_TS, 1000L)
+ .property("equip-type", "first-ps-type", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT, "JUNIT-U",
+ AAIProperties.END_TX_ID, "JUNIT-U", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 500L)
+ .property("equip-type", "first-ps-type-update", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-U", AAIProperties.START_TX_ID, "JUNIT-U", AAIProperties.END_SOT,
+ "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 500L,
+ AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT,
+ "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.END_SOT, "JUNIT-D", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-D", AAIProperties.START_TX_ID, "JUNIT-D", AAIProperties.END_SOT,
+ "JUNIT-D", AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.START_TS, 100L, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT, "JUNIT-D",
+ AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 100L,
+ AAIProperties.END_TS, 1000L)
+ .property(AAIProperties.END_TS, 1000L, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-D",
+ AAIProperties.START_TX_ID, "JUNIT-D", AAIProperties.END_SOT, "JUNIT-D",
+ AAIProperties.END_TX_ID, "JUNIT-D", AAIProperties.START_TS, 1000L,
+ AAIProperties.END_TS, 1000L)
+ .next();
+
+ /*
+ * Pserver
+ * - created @ time 10000
+ * - update in-maint/equip-type @ 15000
+ */
+ g.addV()
+ .property(AAIProperties.NODE_TYPE, "pserver", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 10000L)
+ .property(AAIProperties.AAI_URI,
+ "/cloud-infrastructure/pservers/pserver/test-pserver-dsl",
+ AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C",
+ AAIProperties.START_TS, 10000L)
+ .property(AAIProperties.RESOURCE_VERSION, "10000", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT,
+ "JUNIT-U", AAIProperties.END_TX_ID, "JUNIT-U", AAIProperties.START_TS, 10000L,
+ AAIProperties.END_TS, 15000L)
+ .property(AAIProperties.RESOURCE_VERSION, "15000", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-U", AAIProperties.START_TX_ID, "JUNIT-U", AAIProperties.START_TS, 15000)
+ .property("hostname", "test-pserver-dsl", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 10000L)
+ .property("in-maint", true, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT, "JUNIT-U",
+ AAIProperties.END_TX_ID, "JUNIT-U", AAIProperties.START_TS, 10000L,
+ AAIProperties.END_TS, 15000L)
+ .property("in-maint", false, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-U",
+ AAIProperties.START_TX_ID, "JUNIT-U", AAIProperties.START_TS, 15000L)
+ .property("equip-type", "second-ps-type", AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.END_SOT, "JUNIT-U",
+ AAIProperties.END_TX_ID, "JUNIT-U", AAIProperties.START_TS, 10000L,
+ AAIProperties.END_TS, 15000L)
+ .property("equip-type", "second-ps-type-update", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-U", AAIProperties.START_TX_ID, "JUNIT-U", AAIProperties.START_TS, 15000L)
+ .property(AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C", AAIProperties.SOURCE_OF_TRUTH,
+ "JUNIT-C", AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 10000L)
+ .property(AAIProperties.START_TS, 10000L, AAIProperties.SOURCE_OF_TRUTH, "JUNIT-C",
+ AAIProperties.START_TX_ID, "JUNIT-C", AAIProperties.START_TS, 10000L)
+ .next();
+ } catch (Exception ex) {
+ success = false;
+ } finally {
+ if (success) {
+ transaction.commit();
+ } else {
+ transaction.rollback();
+ fail("Unable to setup the graph");
+ }
+ }
+ }
+
+ private JsonArray getResultsForPserverLookupByHostname(String endpoint) throws Exception {
+ return getResultsForPserverLookupByHostnameAndAnother(endpoint, "");
+ }
+
+ private JsonArray getResultsForPserverLookupByHostnameAndAnother(String endpoint,
+ String additionalFilterInParen) throws Exception {
+ Map<String, String> dslQueryMap = new HashMap<>();
+ dslQueryMap.put("dsl-query",
+ "pserver*('hostname','test-pserver-dsl')" + additionalFilterInParen);
+ String payload = PayloadUtil.getTemplatePayload("dsl-query.json", dslQueryMap);
+ httpEntity = new HttpEntity(payload, headers);
+ ResponseEntity responseEntity =
+ restTemplate.exchange(baseUrl + endpoint, HttpMethod.PUT, httpEntity, String.class);
+ JsonArray results = new JsonParser().parse(responseEntity.getBody().toString())
+ .getAsJsonObject().getAsJsonArray("results");
+ LOGGER.debug("Response for PUT request with uri {} : {}", baseUrl + endpoint,
+ responseEntity.getBody());
+
+ assertNotNull("Response from /aai/v14/dsl is not null", responseEntity);
+ assertEquals("Expected the response to be 200", HttpStatus.OK,
+ responseEntity.getStatusCode());
+ return results;
+ }
+
+ private void verifyEquipTypeValues(JsonArray results, String... equipType) {
+ Set<String> expectedEquipTypes = new HashSet<>(Arrays.asList(equipType));
+ final Set<String> actualEquipType = new HashSet<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ assertFalse("State format properties should not have end timestamps",
+ property.getAsJsonObject().has("end-timestamp"));
+ if (property.getAsJsonObject().get("key").getAsString().equals("equip-type")) {
+ actualEquipType.add(property.getAsJsonObject().get("value").getAsString());
+ }
+ }
+ }
+ assertThat("Verify equip-type in state", actualEquipType, is(expectedEquipTypes));
+ }
+
+ private void verifyAllPropsTxIds(JsonArray results) {
+ final Set<String> propMissingCreatedTxId = new HashSet<>();
+ final Set<String> propContainingEndTxId = new HashSet<>();
+ for (JsonElement result : results) {
+ for (JsonElement property : result.getAsJsonObject().get("properties")
+ .getAsJsonArray()) {
+ if (!property.getAsJsonObject().has("tx-id")) {
+ propMissingCreatedTxId.add(property.getAsJsonObject().get("key").getAsString());
+ }
+ if (property.getAsJsonObject().has("end-tx-id")) {
+ propContainingEndTxId.add(property.getAsJsonObject().get("key").getAsString());
+ }
+ }
+ }
+
+ assertThat("Verify no prop is missing tx-id in state", propMissingCreatedTxId,
+ is(Collections.EMPTY_SET));
+ assertThat("Verify no prop has end-tx-id in state", propContainingEndTxId,
+ is(Collections.EMPTY_SET));
+ }
+
+ @Test
+ public void stateQueryBeforeCreationTimeTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=50";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(0, results.size());
+ }
+
+ @Test
+ public void stateQueryAtCreationTimeTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=100";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(1, results.size());
+ verifyEquipTypeValues(results, "first-ps-type");
+ verifyAllPropsTxIds(results);
+ }
+
+ @Test
+ public void stateQueryAfterCreationTimeTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=200";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(1, results.size());
+ verifyEquipTypeValues(results, "first-ps-type");
+ verifyAllPropsTxIds(results);
+ }
+
+ @Test
+ public void stateQueryAtUpdateTimeTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=500";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(1, results.size());
+ verifyEquipTypeValues(results, "first-ps-type-update");
+ verifyAllPropsTxIds(results);
+ }
+
+ @Test
+ public void stateQueryAfterUpdateTimeTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=700";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(1, results.size());
+ verifyEquipTypeValues(results, "first-ps-type-update");
+ verifyAllPropsTxIds(results);
+ }
+
+ @Test
+ public void stateQueryAtDeletionTimeTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=1000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(0, results.size());
+ }
+
+ @Test
+ public void stateQueryAfterDeletionTimeTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=2000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(0, results.size());
+ }
+
+ // WITH endTs=startTs
+ @Test
+ public void stateQueryBeforeCreationWithEndTsTimeTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=50&endTs=50";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(0, results.size());
+ }
+
+ @Test
+ public void stateQueryAtCreationTimeWithEndTsTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=100&endTs=100";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(1, results.size());
+ verifyEquipTypeValues(results, "first-ps-type");
+ verifyAllPropsTxIds(results);
+ }
+
+ @Test
+ public void stateQueryAfterCreationTimeWithEndTsTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=200&endTs=200";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(1, results.size());
+ verifyEquipTypeValues(results, "first-ps-type");
+ verifyAllPropsTxIds(results);
+ }
+
+ @Test
+ public void stateQueryAtUpdateTimeWithEndTsTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=500&endTs=500";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(1, results.size());
+ verifyEquipTypeValues(results, "first-ps-type-update");
+ verifyAllPropsTxIds(results);
+ }
+
+ @Test
+ public void stateQueryAfterUpdateTimeWithEndTsTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=700&endTs=700";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(1, results.size());
+ verifyEquipTypeValues(results, "first-ps-type-update");
+ verifyAllPropsTxIds(results);
+ }
+
+ @Test
+ public void stateQueryAtDeletionTimeWithEndTsTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=1000&endTs=1000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(0, results.size());
+ }
+
+ @Test
+ public void stateQueryAfterDeletionTimeWithEndTsTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=2000&endTs=2000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(0, results.size());
+ }
+
+ // Second pserver
+
+ @Test
+ public void stateQueryBeforeSecondCreationTimeTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=9000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(0, results.size());
+ }
+
+ @Test
+ public void stateQueryAtSecondCreationTimeTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=10000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(1, results.size());
+ verifyEquipTypeValues(results, "second-ps-type");
+ verifyAllPropsTxIds(results);
+ }
+
+ @Test
+ public void stateQueryAfterSecondCreationTimeTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=12000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(1, results.size());
+ verifyEquipTypeValues(results, "second-ps-type");
+ verifyAllPropsTxIds(results);
+ }
+
+ @Test
+ public void stateQueryAtUpdateAfterSecondCreationTimeTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=15000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(1, results.size());
+ verifyEquipTypeValues(results, "second-ps-type-update");
+ verifyAllPropsTxIds(results);
+ }
+
+ @Test
+ public void stateQueryAfterUpdateAfterSecondCreationTimeTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state&startTs=17000";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(1, results.size());
+ verifyEquipTypeValues(results, "second-ps-type-update");
+ verifyAllPropsTxIds(results);
+ }
+
+ @Test
+ public void stateQueryNoTimestampTest() throws Exception {
+ String endpoint = "/aai/v14/dsl?format=state";
+ JsonArray results = getResultsForPserverLookupByHostname(endpoint);
+ assertEquals(1, results.size());
+ verifyEquipTypeValues(results, "second-ps-type-update");
+ verifyAllPropsTxIds(results);
+ }
+
+ @Test
+ public void stateQueryNoTimestampWithEquipTypeFilterTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=state";
+ String equipType = "first-ps-type";
+ JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+
+ equipType = "first-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+
+ equipType = "second-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+
+ equipType = "second-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
+
+ verifyEquipTypeValues(results, equipType);
+
+ verifyAllPropsTxIds(results);
+ }
+
+ @Test
+ public void stateQueryTimestampBeforeFirstCreateWithEquipTypeFilterTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=state&startTs=50";
+ String equipType = "first-ps-type";
+ JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+
+ equipType = "first-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+
+ equipType = "second-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+
+ equipType = "second-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+
+ }
+
+ @Test
+ public void stateQueryTimestampAtFirstCreateWithEquipTypeFilterTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=state&startTs=100";
+ String equipType = "first-ps-type";
+ JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
+
+ verifyEquipTypeValues(results, equipType);
+
+ verifyAllPropsTxIds(results);
+
+ equipType = "first-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+
+ equipType = "second-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+
+ equipType = "second-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
+
+ }
+
+ @Test
+ public void stateQueryTimestampAfterFirstCreateWithEquipTypeFilterTest() throws Exception {
+
+ String endpoint = "/aai/v14/dsl?format=state&startTs=200";
+ String equipType = "first-ps-type";
+ JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, equipType);
+ verifyEquipTypeValues(results, equipType);
- verifyAllPropsTxIds(results);
+ verifyAllPropsTxIds(results);
- equipType = "first-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "first-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "second-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "second-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "second-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "second-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- }
+ }
- @Test
- public void stateQueryTimestampAtFirstUpdateWithEquipTypeFilterTest() throws Exception {
+ @Test
+ public void stateQueryTimestampAtFirstUpdateWithEquipTypeFilterTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=500";
- String equipType = "first-ps-type";
- JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ String endpoint = "/aai/v14/dsl?format=state&startTs=500";
+ String equipType = "first-ps-type";
+ JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "first-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ equipType = "first-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, equipType);
+ verifyEquipTypeValues(results, equipType);
- verifyAllPropsTxIds(results);
+ verifyAllPropsTxIds(results);
- equipType = "second-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "second-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "second-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "second-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- }
+ }
- @Test
- public void stateQueryTimestampAfterFirstUpdateWithEquipTypeFilterTest() throws Exception {
+ @Test
+ public void stateQueryTimestampAfterFirstUpdateWithEquipTypeFilterTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=700";
- String equipType = "first-ps-type";
- JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ String endpoint = "/aai/v14/dsl?format=state&startTs=700";
+ String equipType = "first-ps-type";
+ JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "first-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ equipType = "first-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, equipType);
+ verifyEquipTypeValues(results, equipType);
- verifyAllPropsTxIds(results);
+ verifyAllPropsTxIds(results);
- equipType = "second-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "second-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "second-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "second-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- }
+ }
- @Test
- public void stateQueryTimestampAtFirstDeleteWithEquipTypeFilterTest() throws Exception {
+ @Test
+ public void stateQueryTimestampAtFirstDeleteWithEquipTypeFilterTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=1000";
- String equipType = "first-ps-type";
- JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ String endpoint = "/aai/v14/dsl?format=state&startTs=1000";
+ String equipType = "first-ps-type";
+ JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "first-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "first-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "second-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "second-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "second-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "second-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- }
+ }
- @Test
- public void stateQueryTimestampAfterFirstDeleteWithEquipTypeFilterTest() throws Exception {
+ @Test
+ public void stateQueryTimestampAfterFirstDeleteWithEquipTypeFilterTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=5000";
- String equipType = "first-ps-type";
- JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ String endpoint = "/aai/v14/dsl?format=state&startTs=5000";
+ String equipType = "first-ps-type";
+ JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "first-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "first-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "second-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "second-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "second-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "second-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- }
+ }
- @Test
- public void stateQueryTimestampAtSecondCreateWithEquipTypeFilterTest() throws Exception {
+ @Test
+ public void stateQueryTimestampAtSecondCreateWithEquipTypeFilterTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=10000";
- String equipType = "first-ps-type";
- JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ String endpoint = "/aai/v14/dsl?format=state&startTs=10000";
+ String equipType = "first-ps-type";
+ JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "first-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "first-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "second-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ equipType = "second-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, equipType);
+ verifyEquipTypeValues(results, equipType);
- verifyAllPropsTxIds(results);
+ verifyAllPropsTxIds(results);
- equipType = "second-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "second-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- }
+ }
- @Test
- public void stateQueryTimestampAfterSecondCreateWithEquipTypeFilterTest() throws Exception {
+ @Test
+ public void stateQueryTimestampAfterSecondCreateWithEquipTypeFilterTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=12000";
- String equipType = "first-ps-type";
- JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ String endpoint = "/aai/v14/dsl?format=state&startTs=12000";
+ String equipType = "first-ps-type";
+ JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "first-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "first-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "second-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ equipType = "second-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, equipType);
+ verifyEquipTypeValues(results, equipType);
- verifyAllPropsTxIds(results);
+ verifyAllPropsTxIds(results);
- equipType = "second-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "second-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- }
+ }
- @Test
- public void stateQueryTimestampAtSecondUpdateWithEquipTypeFilterTest() throws Exception {
+ @Test
+ public void stateQueryTimestampAtSecondUpdateWithEquipTypeFilterTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=15000";
- String equipType = "first-ps-type";
- JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ String endpoint = "/aai/v14/dsl?format=state&startTs=15000";
+ String equipType = "first-ps-type";
+ JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "first-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "first-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "second-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "second-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "second-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ equipType = "second-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, equipType);
+ verifyEquipTypeValues(results, equipType);
- verifyAllPropsTxIds(results);
+ verifyAllPropsTxIds(results);
- }
+ }
- @Test
- public void stateQueryTimestampAfterSecondUpdateWithEquipTypeFilterTest() throws Exception {
+ @Test
+ public void stateQueryTimestampAfterSecondUpdateWithEquipTypeFilterTest() throws Exception {
- String endpoint = "/aai/v14/dsl?format=state&startTs=15000";
- String equipType = "first-ps-type";
- JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ String endpoint = "/aai/v14/dsl?format=state&startTs=15000";
+ String equipType = "first-ps-type";
+ JsonArray results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "first-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "first-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "second-ps-type";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 0, results.size());
+ equipType = "second-ps-type";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 0, results.size());
- equipType = "second-ps-type-update";
- results = getResultsForPserverLookupByHostnameAndAnother(endpoint, "('equip-type','" + equipType + "')");
- assertEquals("Filter equip-type on " + equipType, 1, results.size());
+ equipType = "second-ps-type-update";
+ results = getResultsForPserverLookupByHostnameAndAnother(endpoint,
+ "('equip-type','" + equipType + "')");
+ assertEquals("Filter equip-type on " + equipType, 1, results.size());
- verifyEquipTypeValues(results, equipType);
+ verifyEquipTypeValues(results, equipType);
- verifyAllPropsTxIds(results);
+ verifyAllPropsTxIds(results);
- }
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/retired/RetiredConsumerSpringTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/retired/RetiredConsumerSpringTest.java
index 46e4a35..bd62e71 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/retired/RetiredConsumerSpringTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/retired/RetiredConsumerSpringTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,20 +19,21 @@
*/
package org.onap.aai.rest.retired;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertEquals;
+
import com.att.eelf.configuration.EELFManager;
+
+import java.util.HashMap;
+import java.util.Map;
+
import org.junit.Test;
import org.onap.aai.rest.AbstractSpringRestTest;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
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 Logger LOGGER = LoggerFactory.getLogger(RetiredConsumerSpringTest.class);
@@ -40,7 +41,7 @@ public class RetiredConsumerSpringTest extends AbstractSpringRestTest {
private Map<String, HttpStatus> httpStatusMap;
@Test
- public void testOldVersionsEndpointReturnRetired(){
+ public void testOldVersionsEndpointReturnRetired() {
setupOldVersions();
executeRestCalls();
}
@@ -48,8 +49,10 @@ public class RetiredConsumerSpringTest extends AbstractSpringRestTest {
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());
+ 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());
});
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/AccessServiceFromServiceInstanceTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/AccessServiceFromServiceInstanceTest.java
index 8275959..81d80bf 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/AccessServiceFromServiceInstanceTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/AccessServiceFromServiceInstanceTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -33,61 +33,83 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class AccessServiceFromServiceInstanceTest extends QueryTest {
- public AccessServiceFromServiceInstanceTest() throws AAIException, NoEdgeRuleFoundException {
- super();
+ public AccessServiceFromServiceInstanceTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
}
@Test
public void test() {
- super.run();
+ super.run();
}
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name", "service-instance-name-1");
- Vertex serviceSubscription = graph.addVertex(T.label, "service-subscription", T.id, "2", "aai-node-type", "service-subscription", "service-type", "service-subcription-1");
- Vertex customer = graph.addVertex(T.label, "customer", T.id, "3", "aai-node-type", "customer", "global-customer-id", "customer-id-1", "subscriber-name", "customer-name1", "subscriber-type", "customer-type1");
- Vertex forwardingPath = graph.addVertex(T.label, "forwarding-path", T.id, "4", "aai-node-type", "forwarding-path", "forwarding-path-id", "forwarding-path-id-1", "forwarding-path-name", "forwarding-path-name-1");
- Vertex configuration = graph.addVertex(T.label, "configuration", T.id, "5", "aai-node-type", "configuration", "configuration-id", "configuration-1", "configuration-type", "configuration-type-1", "configuration-sub-type", "configuration-sub-type-1");
- Vertex evc = graph.addVertex(T.label, "evc", T.id, "6", "aai-node-type", "evc", "evc-id", "evc-1");
- Vertex forwarder = graph.addVertex(T.label, "forwarder", T.id,"7", "aai-node-type", "forwarder", "sequence", "forwarder-1");
- Vertex forwarderEvc = graph.addVertex(T.label, "forwarder-evc", T.id, "8", "aai-node-type", "forwarder-evc", "forwarder-evc-id", "forwarder-evc-1");
- Vertex pInterface = graph.addVertex(T.label, "p-interface", T.id, "9", "aai-node-type", "p-interface", "interface-name", "p-interface-1");
- Vertex pnf = graph.addVertex(T.label, "pnf", T.id, "10", "aai-node-type", "pnf", "pnf-name", "pnf1name");
- Vertex lagInterface = graph.addVertex(T.label, "lag-interface", T.id, "11", "aai-node-type", "lag-interface","interface-name", "lagint1");
- Vertex logicalLink = graph.addVertex(T.label, "logical-link", T.id, "12", "aai-node-type", "logical-link", "link-name", "logical-link-1", "link-type", "LAG");
- Vertex badLogicalLink = graph.addVertex(T.label, "logical-link", T.id, "13", "aai-node-type", "logical-link", "link-name", "logical-link-bad", "link-type", "BAD");
- Vertex wrongInterfaceOne = graph.addVertex(T.label, "l-interface", T.id, "14", "aai-node-type", "l-interface", "interface-name", "wrong-interface-1");
- Vertex wrongInterfaceTwo = graph.addVertex(T.label, "l-interface", T.id, "15", "aai-node-type", "l-interface", "interface-name", "wrong-interface-2");
- Vertex wrongInterfaceThree = graph.addVertex(T.label, "l-interface", T.id, "16", "aai-node-type", "l-interface", "interface-name", "wrong-interface-3");
- Vertex wrongInterfaceFour = graph.addVertex(T.label, "l-interface", T.id, "17", "aai-node-type", "l-interface", "interface-name", "wrong-interface-4");
- Vertex vlanMapping = graph.addVertex(T.label, "vlan-mapping", T.id, "18", "aai-node-type", "vlan-mapping", "vlan-mapping-id", "vlan-mapping-1");
-
+ // Set up the test graph
+ Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
+ Vertex serviceSubscription = graph.addVertex(T.label, "service-subscription", T.id, "2",
+ "aai-node-type", "service-subscription", "service-type", "service-subcription-1");
+ Vertex customer = graph.addVertex(T.label, "customer", T.id, "3", "aai-node-type",
+ "customer", "global-customer-id", "customer-id-1", "subscriber-name", "customer-name1",
+ "subscriber-type", "customer-type1");
+ Vertex forwardingPath = graph.addVertex(T.label, "forwarding-path", T.id, "4",
+ "aai-node-type", "forwarding-path", "forwarding-path-id", "forwarding-path-id-1",
+ "forwarding-path-name", "forwarding-path-name-1");
+ Vertex configuration = graph.addVertex(T.label, "configuration", T.id, "5", "aai-node-type",
+ "configuration", "configuration-id", "configuration-1", "configuration-type",
+ "configuration-type-1", "configuration-sub-type", "configuration-sub-type-1");
+ Vertex evc =
+ graph.addVertex(T.label, "evc", T.id, "6", "aai-node-type", "evc", "evc-id", "evc-1");
+ Vertex forwarder = graph.addVertex(T.label, "forwarder", T.id, "7", "aai-node-type",
+ "forwarder", "sequence", "forwarder-1");
+ Vertex forwarderEvc = graph.addVertex(T.label, "forwarder-evc", T.id, "8", "aai-node-type",
+ "forwarder-evc", "forwarder-evc-id", "forwarder-evc-1");
+ Vertex pInterface = graph.addVertex(T.label, "p-interface", T.id, "9", "aai-node-type",
+ "p-interface", "interface-name", "p-interface-1");
+ Vertex pnf = graph.addVertex(T.label, "pnf", T.id, "10", "aai-node-type", "pnf", "pnf-name",
+ "pnf1name");
+ Vertex lagInterface = graph.addVertex(T.label, "lag-interface", T.id, "11", "aai-node-type",
+ "lag-interface", "interface-name", "lagint1");
+ Vertex logicalLink = graph.addVertex(T.label, "logical-link", T.id, "12", "aai-node-type",
+ "logical-link", "link-name", "logical-link-1", "link-type", "LAG");
+ Vertex badLogicalLink = graph.addVertex(T.label, "logical-link", T.id, "13",
+ "aai-node-type", "logical-link", "link-name", "logical-link-bad", "link-type", "BAD");
+ Vertex wrongInterfaceOne = graph.addVertex(T.label, "l-interface", T.id, "14",
+ "aai-node-type", "l-interface", "interface-name", "wrong-interface-1");
+ Vertex wrongInterfaceTwo = graph.addVertex(T.label, "l-interface", T.id, "15",
+ "aai-node-type", "l-interface", "interface-name", "wrong-interface-2");
+ Vertex wrongInterfaceThree = graph.addVertex(T.label, "l-interface", T.id, "16",
+ "aai-node-type", "l-interface", "interface-name", "wrong-interface-3");
+ Vertex wrongInterfaceFour = graph.addVertex(T.label, "l-interface", T.id, "17",
+ "aai-node-type", "l-interface", "interface-name", "wrong-interface-4");
+ Vertex vlanMapping = graph.addVertex(T.label, "vlan-mapping", T.id, "18", "aai-node-type",
+ "vlan-mapping", "vlan-mapping-id", "vlan-mapping-1");
+
GraphTraversalSource g = graph.traversal();
-
+
rules.addTreeEdge(g, serviceInstance, serviceSubscription);
rules.addTreeEdge(g, serviceSubscription, customer);
- rules.addEdge(g, serviceInstance,forwardingPath);
+ rules.addEdge(g, serviceInstance, forwardingPath);
rules.addEdge(g, forwardingPath, configuration);
- rules.addTreeEdge(g, configuration,evc);
- rules.addTreeEdge(g, forwardingPath,forwarder);
+ rules.addTreeEdge(g, configuration, evc);
+ rules.addTreeEdge(g, forwardingPath, forwarder);
rules.addEdge(g, forwarder, configuration);
- rules.addTreeEdge(g, configuration,forwarderEvc);
- rules.addTreeEdge(g, vlanMapping,forwarderEvc);
+ rules.addTreeEdge(g, configuration, forwarderEvc);
+ rules.addTreeEdge(g, vlanMapping, forwarderEvc);
rules.addEdge(g, forwarder, pInterface);
- rules.addTreeEdge(g, pnf,pInterface);
+ rules.addTreeEdge(g, pnf, pInterface);
rules.addEdge(g, forwarder, lagInterface);
- rules.addTreeEdge(g, lagInterface,pnf);
- rules.addEdge(g, logicalLink,lagInterface);
-
- //incorrect nodes
+ rules.addTreeEdge(g, lagInterface, pnf);
+ rules.addEdge(g, logicalLink, lagInterface);
+
+ // incorrect nodes
rules.addEdge(g, badLogicalLink, lagInterface);
rules.addEdge(g, configuration, wrongInterfaceOne);
rules.addEdge(g, forwarder, wrongInterfaceTwo);
rules.addTreeEdge(g, pInterface, wrongInterfaceThree);
- rules.addTreeEdge(g, lagInterface, wrongInterfaceFour);
-
+ rules.addTreeEdge(g, lagInterface, wrongInterfaceFour);
+
expectedResult.add(serviceInstance);
expectedResult.add(serviceSubscription);
expectedResult.add(customer);
@@ -101,24 +123,28 @@ public class AccessServiceFromServiceInstanceTest extends QueryTest {
expectedResult.add(pnf);
expectedResult.add(lagInterface);
expectedResult.add(logicalLink);
-
+
}
@Override
protected String getQueryName() {
- return "access-service-fromServiceInstance";
+ return "access-service-fromServiceInstance";
}
@Override
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "customer").has("global-customer-id", "customer-id-1").in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type", "service-subscription").has("service-type", "service-subcription-1").in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type", "service-instance").has("service-instance-id", "service-instance-id-1");
+ g.has("aai-node-type", "customer").has("global-customer-id", "customer-id-1")
+ .in("org.onap.relationships.inventory.BelongsTo")
+ .has("aai-node-type", "service-subscription")
+ .has("service-type", "service-subcription-1")
+ .in("org.onap.relationships.inventory.BelongsTo")
+ .has("aai-node-type", "service-instance")
+ .has("service-instance-id", "service-instance-id-1");
}
@Override
protected void addParam(Map<String, Object> params) {
- return;
+ return;
}
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/AvailabilityZoneAndComplexfromCloudRegionQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/AvailabilityZoneAndComplexfromCloudRegionQueryTest.java
index 7ce6f9b..2f5788b 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/AvailabilityZoneAndComplexfromCloudRegionQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/AvailabilityZoneAndComplexfromCloudRegionQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,47 +30,60 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class AvailabilityZoneAndComplexfromCloudRegionQueryTest extends QueryTest {
- public AvailabilityZoneAndComplexfromCloudRegionQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public AvailabilityZoneAndComplexfromCloudRegionQueryTest()
+ throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "0", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-owner", "cloud-owner-1");
- Vertex availibityzone = graph.addVertex(T.label, "availability-zone", T.id, "1", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-1", "hypervisor-type", "hypervisortype-1");
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "2", "aai-node-type", "complex", "physical-location-id", "physical-location-id-1","country","country1");
-
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-10", "cloud-owner", "cloud-owner-10");
- Vertex availibityzone1 = graph.addVertex(T.label, "availability-zone", T.id, "4", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-10", "hypervisor-type", "hypervisortype-10");
- Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "5", "aai-node-type", "complex", "physical-location-id", "physical-location-id-20","country","country20");
-
- GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, cloudregion, availibityzone);
- rules.addEdge(g, cloudregion,complex);
-
- rules.addTreeEdge(g, cloudregion1, availibityzone1);
- rules.addEdge(g, cloudregion1,complex1);
-
- expectedResult.add(availibityzone);
- expectedResult.add(complex);
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- @Override
- protected String getQueryName() {
- return "availabilityZoneAndComplex-fromCloudRegion";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type","cloud-region").has("cloud-owner","cloud-owner-1").has("cloud-region-id","cloud-region-id-1");
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "0", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-owner", "cloud-owner-1");
+ Vertex availibityzone = graph.addVertex(T.label, "availability-zone", T.id, "1",
+ "aai-node-type", "availability-zone", "availability-zone-name", "az-name-1",
+ "hypervisor-type", "hypervisortype-1");
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "2", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-1", "country", "country1");
+
+ Vertex cloudregion1 =
+ graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloud-region-id-10", "cloud-owner", "cloud-owner-10");
+ Vertex availibityzone1 = graph.addVertex(T.label, "availability-zone", T.id, "4",
+ "aai-node-type", "availability-zone", "availability-zone-name", "az-name-10",
+ "hypervisor-type", "hypervisortype-10");
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "5", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-20", "country", "country20");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addTreeEdge(g, cloudregion, availibityzone);
+ rules.addEdge(g, cloudregion, complex);
+
+ rules.addTreeEdge(g, cloudregion1, availibityzone1);
+ rules.addEdge(g, cloudregion1, complex1);
+
+ expectedResult.add(availibityzone);
+ expectedResult.add(complex);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "availabilityZoneAndComplex-fromCloudRegion";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "cloud-region").has("cloud-owner", "cloud-owner-1")
+ .has("cloud-region-id", "cloud-region-id-1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/ClosedLoopQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/ClosedLoopQueryTest.java
index 821836a..3b610f1 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/ClosedLoopQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/ClosedLoopQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,74 +30,87 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class ClosedLoopQueryTest extends QueryTest {
- public ClosedLoopQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
-
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "1", "aai-node-type", "vserver", "vserver-id", "vserver-id-1","vserver-name","vserver-name-1");
- Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1");
-
- Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "3", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1");
- Vertex vfModule = graph.addVertex(T.label, "vf-module", T.id, "4", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-1");
-
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "5", "aai-node-type", "tenant", "tenant-id", "tenantid01", "tenant-name", "tenantName01");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "6", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1");
-
-
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver", "vserver-id", "vserver-id-2","vserver-name","vserver-name-1");
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-2");
-
- Vertex serviceInstance1 = graph.addVertex(T.label, "service-instance", T.id, "9", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2");
- Vertex vfModule1 = graph.addVertex(T.label, "vf-module", T.id, "10", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-2");
-
- Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "11", "aai-node-type", "tenant", "tenant-id", "tenantid01", "tenant-name", "tenantName02");
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "12", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-1");
-
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, vserver, gnvf);
- rules.addEdge(g, gnvf, serviceInstance);
- rules.addTreeEdge(g, gnvf, vfModule);
- rules.addTreeEdge(g, vserver,tenant);
- rules.addTreeEdge(g, tenant,cloudregion);
-
- //Not expected in result
- rules.addEdge(g, vserver1, gnvf1);
- rules.addEdge(g, gnvf1, serviceInstance1);
- rules.addTreeEdge(g, gnvf1, vfModule1);
- rules.addTreeEdge(g, vserver1,tenant1);
- rules.addTreeEdge(g, tenant1,cloudregion1);
- //Not expected in result
-
- expectedResult.add(vserver);
- expectedResult.add(gnvf);
- expectedResult.add(serviceInstance);
- expectedResult.add(vfModule);
- expectedResult.add(tenant);
- expectedResult.add(cloudregion);
-
- }
-
- @Override
- protected String getQueryName() {
- return "closed-loop";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "vserver").has("vserver-id", "vserver-id-1");
-
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ public ClosedLoopQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "1", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
+ Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1");
+
+ Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "3",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1");
+ Vertex vfModule = graph.addVertex(T.label, "vf-module", T.id, "4", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-1");
+
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "5", "aai-node-type", "tenant",
+ "tenant-id", "tenantid01", "tenant-name", "tenantName01");
+ Vertex cloudregion =
+ graph.addVertex(T.label, "cloud-region", T.id, "6", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1");
+
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-2", "vserver-name", "vserver-name-1");
+ Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-2");
+
+ Vertex serviceInstance1 = graph.addVertex(T.label, "service-instance", T.id, "9",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2");
+ Vertex vfModule1 = graph.addVertex(T.label, "vf-module", T.id, "10", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-2");
+
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "11", "aai-node-type", "tenant",
+ "tenant-id", "tenantid01", "tenant-name", "tenantName02");
+ Vertex cloudregion1 =
+ graph.addVertex(T.label, "cloud-region", T.id, "12", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-1");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, vserver, gnvf);
+ rules.addEdge(g, gnvf, serviceInstance);
+ rules.addTreeEdge(g, gnvf, vfModule);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addTreeEdge(g, tenant, cloudregion);
+
+ // Not expected in result
+ rules.addEdge(g, vserver1, gnvf1);
+ rules.addEdge(g, gnvf1, serviceInstance1);
+ rules.addTreeEdge(g, gnvf1, vfModule1);
+ rules.addTreeEdge(g, vserver1, tenant1);
+ rules.addTreeEdge(g, tenant1, cloudregion1);
+ // Not expected in result
+
+ expectedResult.add(vserver);
+ expectedResult.add(gnvf);
+ expectedResult.add(serviceInstance);
+ expectedResult.add(vfModule);
+ expectedResult.add(tenant);
+ expectedResult.add(cloudregion);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "closed-loop";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "vserver").has("vserver-id", "vserver-id-1");
+
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionAndSourceFromConfigurationQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionAndSourceFromConfigurationQueryTest.java
index 87e421d..43ddca7 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionAndSourceFromConfigurationQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionAndSourceFromConfigurationQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -31,72 +31,86 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class CloudRegionAndSourceFromConfigurationQueryTest extends QueryTest {
- public CloudRegionAndSourceFromConfigurationQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void test() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex config = graph.addVertex(T.label, "configuration", T.id, "0", "aai-node-type", "configuration", "configuration-id", "configuration");
- Vertex logicalLink = graph.addVertex(T.label, "l", T.id, "1", "aai-node-type", "logical-link", "link-name", "link-name-0");
- Vertex lInterface = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type", "l-interface", "interface-name", "interface-name-0");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserver-id-0", "vserver-name", "vserver-name-0");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "4", "aai-node-type", "tenant", "tenant-id", "tenantid01", "tenant-name", "tenantName01");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-0", "cloud-region-owner", "cloud-owner-name-0","cloud-region-version","cloud-region-version-0");
-
- Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "6", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-0", "vf-module-name", "vf-module-name0");
- Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "7", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-0", "vnf-name", "vnf-name-0");
-
-
- Vertex lInterface1 = graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type", "l-interface", "interface-name", "interface-name-1");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "13", "aai-node-type", "vserver", "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
- Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "14", "aai-node-type", "tenant", "tenant-id", "tenantid11", "tenant-name", "tenantName11");
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "15", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1","cloud-region-version","cloud-region-version-1");
-
- Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "16", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "17", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
-
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, config, logicalLink);
- rules.addEdge(g, logicalLink, lInterface,"org.onap.relationships.inventory.Source");
- rules.addTreeEdge(g, lInterface, vserver);
- rules.addTreeEdge(g, vserver, tenant);
- rules.addTreeEdge(g, tenant, cloudregion);
- rules.addEdge(g, vserver, vfmodule);
- rules.addTreeEdge(g, vfmodule, gnvf);
-
- rules.addEdge(g, logicalLink, lInterface1,"tosca.relationships.network.LinksTo");//false
- rules.addTreeEdge(g, lInterface1, vserver1);//false
- rules.addTreeEdge(g, vserver1, tenant1);//false
- rules.addTreeEdge(g, tenant1, cloudregion1);//false
- rules.addEdge(g, vserver1, vfmodule1);//false
- rules.addTreeEdge(g, vfmodule1, gnvf1);//false
-
-
- expectedResult.add(cloudregion);
- expectedResult.add(gnvf);
- }
-
- @Override
- protected String getQueryName() {
- return "cloud-region-and-source-FromConfiguration";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "configuration").has("configuration-id", "configuration");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ public CloudRegionAndSourceFromConfigurationQueryTest()
+ throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void test() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex config = graph.addVertex(T.label, "configuration", T.id, "0", "aai-node-type",
+ "configuration", "configuration-id", "configuration");
+ Vertex logicalLink = graph.addVertex(T.label, "l", T.id, "1", "aai-node-type",
+ "logical-link", "link-name", "link-name-0");
+ Vertex lInterface = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type",
+ "l-interface", "interface-name", "interface-name-0");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-0", "vserver-name", "vserver-name-0");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "4", "aai-node-type", "tenant",
+ "tenant-id", "tenantid01", "tenant-name", "tenantName01");
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region-id-0", "cloud-region-owner",
+ "cloud-owner-name-0", "cloud-region-version", "cloud-region-version-0");
+
+ Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "6", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-0", "vf-module-name", "vf-module-name0");
+ Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "7", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-0", "vnf-name", "vnf-name-0");
+
+ Vertex lInterface1 = graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type",
+ "l-interface", "interface-name", "interface-name-1");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "13", "aai-node-type",
+ "vserver", "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "14", "aai-node-type", "tenant",
+ "tenant-id", "tenantid11", "tenant-name", "tenantName11");
+ Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "15", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner",
+ "cloud-owner-name-1", "cloud-region-version", "cloud-region-version-1");
+
+ Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "16", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
+ Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "17", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, config, logicalLink);
+ rules.addEdge(g, logicalLink, lInterface, "org.onap.relationships.inventory.Source");
+ rules.addTreeEdge(g, lInterface, vserver);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addTreeEdge(g, tenant, cloudregion);
+ rules.addEdge(g, vserver, vfmodule);
+ rules.addTreeEdge(g, vfmodule, gnvf);
+
+ rules.addEdge(g, logicalLink, lInterface1, "tosca.relationships.network.LinksTo");// false
+ rules.addTreeEdge(g, lInterface1, vserver1);// false
+ rules.addTreeEdge(g, vserver1, tenant1);// false
+ rules.addTreeEdge(g, tenant1, cloudregion1);// false
+ rules.addEdge(g, vserver1, vfmodule1);// false
+ rules.addTreeEdge(g, vfmodule1, gnvf1);// false
+
+ expectedResult.add(cloudregion);
+ expectedResult.add(gnvf);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "cloud-region-and-source-FromConfiguration";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "configuration").has("configuration-id", "configuration");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromNfTypeQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromNfTypeQueryTest.java
index 1cf94ca..f3a8352 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromNfTypeQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromNfTypeQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,53 +26,67 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class CloudRegionFromNfTypeQueryTest extends QueryTest {
- public CloudRegionFromNfTypeQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //set up test graph
- Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf", "vnf-id", "vnfid01", "nf-type", "sample-nf-type");
- Vertex cloudregion0 = graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region", "cloud-region-id", "regionid00", "cloud-region-owner", "cloudOwnername00");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "4", "aai-node-type", "tenant", "tenant-id", "tenantid01", "tenant-name", "tenantName01");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "5", "aai-node-type", "vserver", "vserver-id", "vserverid01");
-
- Vertex genericvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type", "generic-vnf", "vnf-id", "vnfid02", "nf-type", "ex-nf-type");
- Vertex cloudregion3 = graph.addVertex(T.label, "cloud-region", T.id, "9", "aai-node-type", "cloud-region", "cloud-region-id", "regionid03", "cloud-region-owner", "cloudOwnername03");
- Vertex tenant2 = graph.addVertex(T.label, "tenant", T.id, "10", "aai-node-type", "tenant", "tenant-id", "tenantid02", "tenant-name", "tenantName02");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type", "vserver", "vserver-id", "vserverid02");
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addTreeEdge(g, tenant, cloudregion0);
- rules.addTreeEdge(g, vserver1, tenant);
- rules.addEdge(g, genericvnf, vserver1);
-
- rules.addTreeEdge(g, tenant2, cloudregion3);
- rules.addTreeEdge(g, vserver2, tenant2);
- rules.addEdge(g, genericvnf2, vserver2);
-
- expectedResult.add(cloudregion0);
- }
- @Override
- protected String getQueryName() {
- return "cloudRegion-fromNfType";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("nf-type", "sample-nf-type");
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ public CloudRegionFromNfTypeQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // set up test graph
+ Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid01", "nf-type", "sample-nf-type");
+ Vertex cloudregion0 =
+ graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region",
+ "cloud-region-id", "regionid00", "cloud-region-owner", "cloudOwnername00");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "4", "aai-node-type", "tenant",
+ "tenant-id", "tenantid01", "tenant-name", "tenantName01");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "5", "aai-node-type", "vserver",
+ "vserver-id", "vserverid01");
+
+ Vertex genericvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid02", "nf-type", "ex-nf-type");
+ Vertex cloudregion3 =
+ graph.addVertex(T.label, "cloud-region", T.id, "9", "aai-node-type", "cloud-region",
+ "cloud-region-id", "regionid03", "cloud-region-owner", "cloudOwnername03");
+ Vertex tenant2 = graph.addVertex(T.label, "tenant", T.id, "10", "aai-node-type", "tenant",
+ "tenant-id", "tenantid02", "tenant-name", "tenantName02");
+ Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type",
+ "vserver", "vserver-id", "vserverid02");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addTreeEdge(g, tenant, cloudregion0);
+ rules.addTreeEdge(g, vserver1, tenant);
+ rules.addEdge(g, genericvnf, vserver1);
+
+ rules.addTreeEdge(g, tenant2, cloudregion3);
+ rules.addTreeEdge(g, vserver2, tenant2);
+ rules.addEdge(g, genericvnf2, vserver2);
+
+ expectedResult.add(cloudregion0);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "cloudRegion-fromNfType";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("nf-type", "sample-nf-type");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromNfTypeVendorVersionTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromNfTypeVendorVersionTest.java
index bc4488d..cdc28b7 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromNfTypeVendorVersionTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromNfTypeVendorVersionTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -31,68 +31,87 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class CloudRegionFromNfTypeVendorVersionTest extends QueryTest {
- public CloudRegionFromNfTypeVendorVersionTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex image1 = graph.addVertex(T.label, "image", T.id, "10", "aai-node-type", "image",
- "image-id", "image1", "image-name", "imageName1", "image-os-distro", "boopOS", "image-os-version", "1.0", "image-selflink", "self/link",
- "application-vendor","vendor1");
-
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "20", "aai-node-type", "vserver", "vserver-id", "vserverid01");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "21", "aai-node-type", "vserver", "vserver-id", "vserverid02");
- Vertex vserver3 = graph.addVertex(T.label, "vserver", T.id, "22", "aai-node-type", "vserver", "vserver-id", "vserverid03");
-
- Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "30", "aai-node-type", "tenant", "tenant-id", "tenantid01", "tenant-name", "tenantName01");
- Vertex tenant2 = graph.addVertex(T.label, "tenant", T.id, "31", "aai-node-type", "tenant", "tenant-id", "tenantid02", "tenant-name", "tenantName02");
- Vertex tenant3 = graph.addVertex(T.label, "tenant", T.id, "32", "aai-node-type", "tenant", "tenant-id", "tenantid03", "tenant-name", "tenantName03");
-
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "40", "aai-node-type", "generic-vnf", "vnf-id", "genvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
- Vertex genericvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "41", "aai-node-type", "generic-vnf", "vnf-id", "genvnf2", "vnf-name", "genvnfname2", "nf-type", "wrong-nf-type");
-
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "50", "aai-node-type", "cloud-region", "cloud-region-id", "cloudreg1", "cloud-region-owner", "cloudOwnername00");
- Vertex cloudregion2 = graph.addVertex(T.label, "cloud-region", T.id, "51", "aai-node-type", "cloud-region", "cloud-region-id", "cloudreg2", "cloud-region-owner", "cloudOwnername01");
- Vertex cloudregion3 = graph.addVertex(T.label, "cloud-region", T.id, "52", "aai-node-type", "cloud-region", "cloud-region-id", "cloudreg3", "cloud-region-owner", "cloudOwnername02");
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addTreeEdge(g, cloudregion1, tenant1);
- rules.addTreeEdge(g, cloudregion2, tenant2);
- rules.addTreeEdge(g, cloudregion3, tenant3);
- rules.addTreeEdge(g, tenant1, vserver1);
- rules.addTreeEdge(g, tenant2, vserver2);
- rules.addTreeEdge(g, tenant3, vserver3);
- rules.addEdge(g, genericvnf1, vserver1);
- rules.addEdge(g, genericvnf2, vserver2);
- rules.addEdge(g, genericvnf1, vserver3);
- rules.addEdge(g, vserver1, image1);
- rules.addEdge(g, vserver2, image1);
- rules.addEdge(g, vserver3, image1);
-
- expectedResult.add(cloudregion1);
- expectedResult.add(cloudregion3);
- }
-
- @Override
- protected String getQueryName() {
- return "cloudRegion-fromNfTypeVendorVersion";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type","image").has("application-vendor","vendor1"); //TODO another test w the optional param too
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("nfType", "sample-nf-type");
- }
+ public CloudRegionFromNfTypeVendorVersionTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex image1 = graph.addVertex(T.label, "image", T.id, "10", "aai-node-type", "image",
+ "image-id", "image1", "image-name", "imageName1", "image-os-distro", "boopOS",
+ "image-os-version", "1.0", "image-selflink", "self/link", "application-vendor",
+ "vendor1");
+
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "20", "aai-node-type",
+ "vserver", "vserver-id", "vserverid01");
+ Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "21", "aai-node-type",
+ "vserver", "vserver-id", "vserverid02");
+ Vertex vserver3 = graph.addVertex(T.label, "vserver", T.id, "22", "aai-node-type",
+ "vserver", "vserver-id", "vserverid03");
+
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "30", "aai-node-type", "tenant",
+ "tenant-id", "tenantid01", "tenant-name", "tenantName01");
+ Vertex tenant2 = graph.addVertex(T.label, "tenant", T.id, "31", "aai-node-type", "tenant",
+ "tenant-id", "tenantid02", "tenant-name", "tenantName02");
+ Vertex tenant3 = graph.addVertex(T.label, "tenant", T.id, "32", "aai-node-type", "tenant",
+ "tenant-id", "tenantid03", "tenant-name", "tenantName03");
+
+ Vertex genericvnf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "40", "aai-node-type", "generic-vnf",
+ "vnf-id", "genvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
+ Vertex genericvnf2 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "41", "aai-node-type", "generic-vnf",
+ "vnf-id", "genvnf2", "vnf-name", "genvnfname2", "nf-type", "wrong-nf-type");
+
+ Vertex cloudregion1 =
+ graph.addVertex(T.label, "cloud-region", T.id, "50", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloudreg1", "cloud-region-owner", "cloudOwnername00");
+ Vertex cloudregion2 =
+ graph.addVertex(T.label, "cloud-region", T.id, "51", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloudreg2", "cloud-region-owner", "cloudOwnername01");
+ Vertex cloudregion3 =
+ graph.addVertex(T.label, "cloud-region", T.id, "52", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloudreg3", "cloud-region-owner", "cloudOwnername02");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addTreeEdge(g, cloudregion1, tenant1);
+ rules.addTreeEdge(g, cloudregion2, tenant2);
+ rules.addTreeEdge(g, cloudregion3, tenant3);
+ rules.addTreeEdge(g, tenant1, vserver1);
+ rules.addTreeEdge(g, tenant2, vserver2);
+ rules.addTreeEdge(g, tenant3, vserver3);
+ rules.addEdge(g, genericvnf1, vserver1);
+ rules.addEdge(g, genericvnf2, vserver2);
+ rules.addEdge(g, genericvnf1, vserver3);
+ rules.addEdge(g, vserver1, image1);
+ rules.addEdge(g, vserver2, image1);
+ rules.addEdge(g, vserver3, image1);
+
+ expectedResult.add(cloudregion1);
+ expectedResult.add(cloudregion3);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "cloudRegion-fromNfTypeVendorVersion";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "image").has("application-vendor", "vendor1"); // TODO another test w
+ // the optional param
+ // too
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("nfType", "sample-nf-type");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromNfTypeVendorVersion_withOptionalTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromNfTypeVendorVersion_withOptionalTest.java
index 8726a71..5944096 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromNfTypeVendorVersion_withOptionalTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromNfTypeVendorVersion_withOptionalTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -31,72 +31,91 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class CloudRegionFromNfTypeVendorVersion_withOptionalTest extends QueryTest {
- public CloudRegionFromNfTypeVendorVersion_withOptionalTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex image1 = graph.addVertex(T.label, "image", T.id, "10", "aai-node-type", "image",
- "image-id", "image1", "image-name", "imageName1", "image-os-distro", "boopOS", "image-os-version", "1.0", "image-selflink", "self/link",
- "application-vendor","vendor1","application-version","1.0");
- Vertex image2 = graph.addVertex(T.label, "image", T.id, "11", "aai-node-type", "image",
- "image-id", "image2", "image-name", "imageName2", "image-os-distro", "boopOS", "image-os-version", "1.0", "image-selflink", "self/link",
- "application-vendor","vendor1","application-version","2.1");
- Vertex image3 = graph.addVertex(T.label, "image", T.id, "12", "aai-node-type", "image",
- "image-id", "image3", "image-name", "imageName3", "image-os-distro", "boopOS", "image-os-version", "1.0", "image-selflink", "self/link",
- "application-vendor","wrongVendor","application-version","1.0");
-
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "20", "aai-node-type", "vserver", "vserver-id", "vserverid01");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "21", "aai-node-type", "vserver", "vserver-id", "vserverid02");
- Vertex vserver3 = graph.addVertex(T.label, "vserver", T.id, "22", "aai-node-type", "vserver", "vserver-id", "vserverid03");
-
- Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "30", "aai-node-type", "tenant", "tenant-id", "tenantid01", "tenant-name", "tenantName01");
- Vertex tenant2 = graph.addVertex(T.label, "tenant", T.id, "31", "aai-node-type", "tenant", "tenant-id", "tenantid02", "tenant-name", "tenantName02");
- Vertex tenant3 = graph.addVertex(T.label, "tenant", T.id, "32", "aai-node-type", "tenant", "tenant-id", "tenantid03", "tenant-name", "tenantName03");
-
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "40", "aai-node-type", "generic-vnf", "vnf-id", "genvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
-
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "50", "aai-node-type", "cloud-region", "cloud-region-id", "cloudreg1", "cloud-region-owner", "cloudOwnername00");
- Vertex cloudregion2 = graph.addVertex(T.label, "cloud-region", T.id, "51", "aai-node-type", "cloud-region", "cloud-region-id", "cloudreg2", "cloud-region-owner", "cloudOwnername01");
- Vertex cloudregion3 = graph.addVertex(T.label, "cloud-region", T.id, "52", "aai-node-type", "cloud-region", "cloud-region-id", "cloudreg3", "cloud-region-owner", "cloudOwnername02");
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addTreeEdge(g, cloudregion1, tenant1);
- rules.addTreeEdge(g, cloudregion2, tenant2);
- rules.addTreeEdge(g, cloudregion3, tenant3);
- rules.addTreeEdge(g, tenant1, vserver1);
- rules.addTreeEdge(g, tenant2, vserver2);
- rules.addTreeEdge(g, tenant3, vserver3);
- rules.addEdge(g, genericvnf1, vserver1);
- rules.addEdge(g, genericvnf1, vserver2);
- rules.addEdge(g, genericvnf1, vserver3);
- rules.addEdge(g, vserver1, image1);
- rules.addEdge(g, vserver2, image2);
- rules.addEdge(g, vserver3, image3);
-
- expectedResult.add(cloudregion1);
- }
-
- @Override
- protected String getQueryName() {
- return "cloudRegion-fromNfTypeVendorVersion";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type","image").has("application-vendor","vendor1").has("application-version","1.0");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("nfType", "sample-nf-type");
- }
+ public CloudRegionFromNfTypeVendorVersion_withOptionalTest()
+ throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex image1 = graph.addVertex(T.label, "image", T.id, "10", "aai-node-type", "image",
+ "image-id", "image1", "image-name", "imageName1", "image-os-distro", "boopOS",
+ "image-os-version", "1.0", "image-selflink", "self/link", "application-vendor",
+ "vendor1", "application-version", "1.0");
+ Vertex image2 = graph.addVertex(T.label, "image", T.id, "11", "aai-node-type", "image",
+ "image-id", "image2", "image-name", "imageName2", "image-os-distro", "boopOS",
+ "image-os-version", "1.0", "image-selflink", "self/link", "application-vendor",
+ "vendor1", "application-version", "2.1");
+ Vertex image3 = graph.addVertex(T.label, "image", T.id, "12", "aai-node-type", "image",
+ "image-id", "image3", "image-name", "imageName3", "image-os-distro", "boopOS",
+ "image-os-version", "1.0", "image-selflink", "self/link", "application-vendor",
+ "wrongVendor", "application-version", "1.0");
+
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "20", "aai-node-type",
+ "vserver", "vserver-id", "vserverid01");
+ Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "21", "aai-node-type",
+ "vserver", "vserver-id", "vserverid02");
+ Vertex vserver3 = graph.addVertex(T.label, "vserver", T.id, "22", "aai-node-type",
+ "vserver", "vserver-id", "vserverid03");
+
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "30", "aai-node-type", "tenant",
+ "tenant-id", "tenantid01", "tenant-name", "tenantName01");
+ Vertex tenant2 = graph.addVertex(T.label, "tenant", T.id, "31", "aai-node-type", "tenant",
+ "tenant-id", "tenantid02", "tenant-name", "tenantName02");
+ Vertex tenant3 = graph.addVertex(T.label, "tenant", T.id, "32", "aai-node-type", "tenant",
+ "tenant-id", "tenantid03", "tenant-name", "tenantName03");
+
+ Vertex genericvnf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "40", "aai-node-type", "generic-vnf",
+ "vnf-id", "genvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
+
+ Vertex cloudregion1 =
+ graph.addVertex(T.label, "cloud-region", T.id, "50", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloudreg1", "cloud-region-owner", "cloudOwnername00");
+ Vertex cloudregion2 =
+ graph.addVertex(T.label, "cloud-region", T.id, "51", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloudreg2", "cloud-region-owner", "cloudOwnername01");
+ Vertex cloudregion3 =
+ graph.addVertex(T.label, "cloud-region", T.id, "52", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloudreg3", "cloud-region-owner", "cloudOwnername02");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addTreeEdge(g, cloudregion1, tenant1);
+ rules.addTreeEdge(g, cloudregion2, tenant2);
+ rules.addTreeEdge(g, cloudregion3, tenant3);
+ rules.addTreeEdge(g, tenant1, vserver1);
+ rules.addTreeEdge(g, tenant2, vserver2);
+ rules.addTreeEdge(g, tenant3, vserver3);
+ rules.addEdge(g, genericvnf1, vserver1);
+ rules.addEdge(g, genericvnf1, vserver2);
+ rules.addEdge(g, genericvnf1, vserver3);
+ rules.addEdge(g, vserver1, image1);
+ rules.addEdge(g, vserver2, image2);
+ rules.addEdge(g, vserver3, image3);
+
+ expectedResult.add(cloudregion1);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "cloudRegion-fromNfTypeVendorVersion";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "image").has("application-vendor", "vendor1")
+ .has("application-version", "1.0");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("nfType", "sample-nf-type");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromVnfTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromVnfTest.java
index d364f34..087abac 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromVnfTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionFromVnfTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -33,67 +33,74 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class CloudRegionFromVnfTest extends QueryTest {
- public CloudRegionFromVnfTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public CloudRegionFromVnfTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex gv = graph.addVertex(T.id, "00", "aai-node-type", "generic-vnf", "vnf-id", "gvId", "vnf-name", "name", "vnf-type", "type");
- Vertex vnfc = graph.addVertex(T.id, "10", "aai-node-type", "vnfc",
- "vnfc-name", "vnfcName1", "nfc-naming-code", "blue", "nfc-function", "correct-function");
- Vertex vserv = graph.addVertex(T.id, "20", "aai-node-type", "vserver",
- "vserver-id", "vservId", "vserver-name", "vservName", "vserver-selflink", "me/self");
- Vertex cr = graph.addVertex(T.id, "30", "aai-node-type", "cloud-region", "cloud-owner", "some guy", "cloud-region-id", "crId");
- Vertex tenant = graph.addVertex(T.id, "40", "aai-node-type", "tenant", "tenant-id", "ten1", "tenant-name", "tenName");
- Vertex pserv = graph.addVertex(T.id, "50", "aai-node-type", "pserver", "hostname", "hostname1", "in-maint", "false");
- Vertex vserv2 = graph.addVertex(T.id, "60", "aai-node-type", "vserver",
- "vserver-id", "vservId2", "vserver-name", "vservName2", "vserver-selflink", "me/self");
- Vertex pserv2 = graph.addVertex(T.id, "70", "aai-node-type", "pserver", "hostname", "hostname2", "in-maint", "false");
- Vertex tenant2 = graph.addVertex(T.id, "80", "aai-node-type", "tenant", "tenant-id", "ten2", "tenant-name", "tenName2");
- Vertex cr2 = graph.addVertex(T.id, "90", "aai-node-type", "cloud-region", "cloud-owner", "some guy2", "cloud-region-id", "crId2");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, gv, vnfc);
- rules.addEdge(g, vnfc, vserv);
- rules.addEdge(g, vserv, pserv);
- rules.addTreeEdge(g, cr, tenant);
- rules.addTreeEdge(g, tenant, vserv);
- rules.addEdge(g, gv, vserv2);
- rules.addEdge(g, vserv2, pserv2);
- rules.addTreeEdge(g, vserv2, tenant2);
- rules.addTreeEdge(g, tenant2, cr2);
-
- expectedResult.add(gv);
- expectedResult.add(cr);
- expectedResult.add(tenant);
- expectedResult.add(vnfc);
- expectedResult.add(vserv);
- expectedResult.add(pserv);
- expectedResult.add(cr2);
- expectedResult.add(tenant2);
- expectedResult.add(vserv2);
- expectedResult.add(pserv2);
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex gv = graph.addVertex(T.id, "00", "aai-node-type", "generic-vnf", "vnf-id", "gvId",
+ "vnf-name", "name", "vnf-type", "type");
+ Vertex vnfc = graph.addVertex(T.id, "10", "aai-node-type", "vnfc", "vnfc-name", "vnfcName1",
+ "nfc-naming-code", "blue", "nfc-function", "correct-function");
+ Vertex vserv = graph.addVertex(T.id, "20", "aai-node-type", "vserver", "vserver-id",
+ "vservId", "vserver-name", "vservName", "vserver-selflink", "me/self");
+ Vertex cr = graph.addVertex(T.id, "30", "aai-node-type", "cloud-region", "cloud-owner",
+ "some guy", "cloud-region-id", "crId");
+ Vertex tenant = graph.addVertex(T.id, "40", "aai-node-type", "tenant", "tenant-id", "ten1",
+ "tenant-name", "tenName");
+ Vertex pserv = graph.addVertex(T.id, "50", "aai-node-type", "pserver", "hostname",
+ "hostname1", "in-maint", "false");
+ Vertex vserv2 = graph.addVertex(T.id, "60", "aai-node-type", "vserver", "vserver-id",
+ "vservId2", "vserver-name", "vservName2", "vserver-selflink", "me/self");
+ Vertex pserv2 = graph.addVertex(T.id, "70", "aai-node-type", "pserver", "hostname",
+ "hostname2", "in-maint", "false");
+ Vertex tenant2 = graph.addVertex(T.id, "80", "aai-node-type", "tenant", "tenant-id", "ten2",
+ "tenant-name", "tenName2");
+ Vertex cr2 = graph.addVertex(T.id, "90", "aai-node-type", "cloud-region", "cloud-owner",
+ "some guy2", "cloud-region-id", "crId2");
- @Override
- protected String getQueryName() {
- return "cloud-region-fromVnf";
- }
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, gv, vnfc);
+ rules.addEdge(g, vnfc, vserv);
+ rules.addEdge(g, vserv, pserv);
+ rules.addTreeEdge(g, cr, tenant);
+ rules.addTreeEdge(g, tenant, vserv);
+ rules.addEdge(g, gv, vserv2);
+ rules.addEdge(g, vserv2, pserv2);
+ rules.addTreeEdge(g, vserv2, tenant2);
+ rules.addTreeEdge(g, tenant2, cr2);
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "generic-vnf").has("vnf-id", "gvId");
- }
+ expectedResult.add(gv);
+ expectedResult.add(cr);
+ expectedResult.add(tenant);
+ expectedResult.add(vnfc);
+ expectedResult.add(vserv);
+ expectedResult.add(pserv);
+ expectedResult.add(cr2);
+ expectedResult.add(tenant2);
+ expectedResult.add(vserv2);
+ expectedResult.add(pserv2);
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- // N/A for this query
- }
+ @Override
+ protected String getQueryName() {
+ return "cloud-region-fromVnf";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "generic-vnf").has("vnf-id", "gvId");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ // N/A for this query
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionSitesQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionSitesQueryTest.java
index c1f3474..390ef22 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionSitesQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionSitesQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,59 +26,65 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class CloudRegionSitesQueryTest extends QueryTest {
- public CloudRegionSitesQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
+ public CloudRegionSitesQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex region1 = graph.addVertex(T.label, "cloud-region", T.id, "0", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloudOwner1");
+ Vertex region2 = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloudOwner1");
+ Vertex region3 = graph.addVertex(T.label, "cloud-region", T.id, "2", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloudOwner1");
+ Vertex region4 = graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloudOwner2");
+ Vertex complex1 =
+ graph.addVertex(T.label, "complex", T.id, "4", "aai-node-type", "complex");
+ Vertex complex2 =
+ graph.addVertex(T.label, "complex", T.id, "5", "aai-node-type", "complex");
+ Vertex complex3 =
+ graph.addVertex(T.label, "complex", T.id, "6", "aai-node-type", "complex");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, region1, complex1);
+ rules.addEdge(g, region2, complex1);
+ rules.addEdge(g, region3, complex2);
+ rules.addEdge(g, region4, complex3);
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex region1 = graph.addVertex(T.label, "cloud-region", T.id, "0", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner1");
- Vertex region2 = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner1");
- Vertex region3 = graph.addVertex(T.label, "cloud-region", T.id, "2", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner1");
- Vertex region4 = graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner2");
- Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "4", "aai-node-type", "complex");
- Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "5", "aai-node-type", "complex");
- Vertex complex3 = graph.addVertex(T.label, "complex", T.id, "6", "aai-node-type", "complex");
+ expectedResult.add(region1);
+ expectedResult.add(region2);
+ expectedResult.add(region3);
+ expectedResult.add(complex1);
+ expectedResult.add(complex2);
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, region1, complex1);
- rules.addEdge(g, region2, complex1);
- rules.addEdge(g, region3, complex2);
- rules.addEdge(g, region4, complex3);
+ }
- expectedResult.add(region1);
- expectedResult.add(region2);
- expectedResult.add(region3);
- expectedResult.add(complex1);
- expectedResult.add(complex2);
-
- }
+ @Override
+ protected String getQueryName() {
+ return "cloud-region-sites";
+ }
- @Override
- protected String getQueryName() {
- return "cloud-region-sites";
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "cloud-region");
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "cloud-region");
-
- }
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("owner", "cloudOwner1");
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("owner", "cloudOwner1");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionfromCountryCloudRegionVersionQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionfromCountryCloudRegionVersionQueryTest.java
index 1ad6663..b0c697f 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionfromCountryCloudRegionVersionQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionfromCountryCloudRegionVersionQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,50 +26,57 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class CloudRegionfromCountryCloudRegionVersionQueryTest extends QueryTest {
- public CloudRegionfromCountryCloudRegionVersionQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public CloudRegionfromCountryCloudRegionVersionQueryTest()
+ throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-1", "country", "country1");
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner",
+ "cloud-owner-name-1", "cloud-region-version", "cloud-region-version-1");
+
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "2", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-2", "country", "country2");
+ Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region-id-2", "cloud-region-owner",
+ "cloud-owner-name-2", "cloud-region-version", "cloud-region-version-2");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, complex, cloudregion);
+
+ rules.addEdge(g, complex1, cloudregion1);
+
+ expectedResult.add(cloudregion);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "cloudRegion-fromCountryCloudRegionVersion";
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "complex").has("country", "country1");
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex", "physical-location-id", "physical-location-id-1","country","country1");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1","cloud-region-version","cloud-region-version-1");
-
-
- Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "2", "aai-node-type", "complex", "physical-location-id", "physical-location-id-2","country","country2");
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-2","cloud-region-version","cloud-region-version-2");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, complex,cloudregion);
-
- rules.addEdge(g, complex1,cloudregion1);
-
- expectedResult.add(cloudregion);
-
- }
+ }
- @Override
- protected String getQueryName() {
- return "cloudRegion-fromCountryCloudRegionVersion";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "complex").has("country", "country1");
-
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("cloudRegionVersion", "cloud-region-version-1");
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("cloudRegionVersion", "cloud-region-version-1");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionfromCountryQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionfromCountryQueryTest.java
index 38a20a1..1e5c751 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionfromCountryQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionfromCountryQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,50 +26,56 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class CloudRegionfromCountryQueryTest extends QueryTest {
- public CloudRegionfromCountryQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public CloudRegionfromCountryQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-1");
+ Vertex cloudregion =
+ graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1");
+
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "2", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-2");
+ Vertex cloudregion1 =
+ graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-2");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, complex, cloudregion);
+
+ rules.addEdge(g, complex1, cloudregion1);
+
+ expectedResult.add(cloudregion);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "cloudRegion-fromCountry";
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("physical-location-id", "physical-location-id-1");
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex", "physical-location-id", "physical-location-id-1");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1");
-
-
- Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "2", "aai-node-type", "complex", "physical-location-id", "physical-location-id-2");
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-2");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, complex,cloudregion);
-
- rules.addEdge(g, complex1,cloudregion1);
-
- expectedResult.add(cloudregion);
-
- }
+ }
- @Override
- protected String getQueryName() {
- return "cloudRegion-fromCountry";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("physical-location-id", "physical-location-id-1");
-
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionsByGenericVnfHGPairsTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionsByGenericVnfHGPairsTest.java
index 1bfff46..9bf61e2 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionsByGenericVnfHGPairsTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/CloudRegionsByGenericVnfHGPairsTest.java
@@ -10,7 +10,7 @@ package org.onap.aai.rest.search;
* 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
+ * 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,
@@ -34,176 +34,192 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-public class CloudRegionsByGenericVnfHGPairsTest extends LinkedHashMapQueryTest{
-
- public CloudRegionsByGenericVnfHGPairsTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void test() {
- super.run();
- String expectedServiceInstanceUri = "service-instance-id1";
- String[] expectedCloudRegions = {"c1oud-region-1","c1oud-region-3","c1oud-region-4"};
- String[] actualCloudRegions = new String[3];
- assertEquals("Number of results is correct", hashMapList.size(), 3);
- for(int i = 0; i < hashMapList.size(); i++) {
- LinkedHashMap currentMap = hashMapList.get(i);
- assertEquals("Result " + i + " has correct service-instance",
- currentMap.get("a").toString(), expectedServiceInstanceUri);
- actualCloudRegions[i] = currentMap.get("b").toString();
- }
- Arrays.sort(expectedCloudRegions);
- Arrays.sort(actualCloudRegions);
- assertTrue("Cloud regions are correct", Arrays.equals(actualCloudRegions, expectedCloudRegions));
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- // Set up the test graph
- Vertex servicesubscription = graph.addVertex(T.label, "service-subscription", T.id, "0", "aai-node-type",
- "service-subscription", "service-type", "DHV");
- Vertex servicesubscription1 = graph.addVertex(T.label, "service-subscription", T.id, "1", "aai-node-type",
- "service-subscription", "service-type", "HNGATEWAY");
- Vertex servicesubscription2 = graph.addVertex(T.label, "service-subscription", T.id, "2", "aai-node-type",
- "service-subscription", "service-type", "service-type-2");
-
- Vertex servicesubscription3 = graph.addVertex(T.label, "service-subscription", T.id, "3", "aai-node-type",
- "service-subscription", "service-type", "HNGATEWAY");
- Vertex servicesubscription4 = graph.addVertex(T.label, "service-subscription", T.id, "4", "aai-node-type",
- "service-subscription", "service-type", "HNGATEWAY");
- Vertex servicesubscription5 = graph.addVertex(T.label, "service-subscription", T.id, "5", "aai-node-type",
- "service-subscription", "service-type", "HNGATEWAY");
-
- Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "6", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id1", "aai-uri", "service-instance-id1");
- Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "7", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id2", "aai-uri", "service-instance-id2");
- Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "8", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id3", "aai-uri", "service-instance-id3");
- Vertex serviceinstance3 = graph.addVertex(T.label, "service-instance", T.id, "9", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id4", "aai-uri", "service-instance-id4");
-
- Vertex serviceinstance4 = graph.addVertex(T.label, "service-instance", T.id, "10", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id5", "aai-uri", "service-instance-id5");
- Vertex serviceinstance5 = graph.addVertex(T.label, "service-instance", T.id, "11", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id6", "aai-uri", "service-instance-id6");
- Vertex serviceinstance6 = graph.addVertex(T.label, "service-instance", T.id, "12", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id7", "aai-uri", "service-instance-id7");
-
- Vertex serviceinstance7 = graph.addVertex(T.label, "service-instance", T.id, "13", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id8", "aai-uri", "service-instance-id8");
- Vertex serviceinstance8 = graph.addVertex(T.label, "service-instance", T.id, "14", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id9", "aai-uri", "service-instance-id9");
- Vertex serviceinstance9 = graph.addVertex(T.label, "service-instance", T.id, "15", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id10", "aai-uri", "service-instance-id10");
-
- Vertex allottedresource = graph.addVertex(T.label, "allotted-resource", T.id, "16", "aai-node-type",
- "allotted-resource");
- Vertex allottedresource1 = graph.addVertex(T.label, "allotted-resource", T.id, "17", "aai-node-type",
- "allotted-resource");
- Vertex allottedresource2 = graph.addVertex(T.label, "allotted-resource", T.id, "18", "aai-node-type",
- "allotted-resource");
- Vertex allottedresource3 = graph.addVertex(T.label, "allotted-resource", T.id, "35", "aai-node-type",
- "allotted-resource");
-
- Vertex gvnf = graph.addVertex(T.label, "generic-vnf", T.id, "19", "aai-node-type", "generic-vnf", "vnf-id",
- "vnf-id-0", "vnf-type", "HG");
- Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "20", "aai-node-type", "generic-vnf", "vnf-id",
- "vnf-id-1", "vnf-type", "vnf-type-1");
- Vertex gvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "21", "aai-node-type", "generic-vnf", "vnf-id",
- "vnf-id-2", "vnf-type", "HG");
- Vertex gvnf3 = graph.addVertex(T.label, "generic-vnf", T.id, "22", "aai-node-type", "generic-vnf", "vnf-id",
- "vnf-id-2", "vnf-type", "HG");
- Vertex gvnf4 = graph.addVertex(T.label, "generic-vnf", T.id, "36", "aai-node-type", "generic-vnf", "vnf-id",
- "vnf-id-2", "vnf-type", "HP");
-
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "23", "aai-node-type", "vserver");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "24", "aai-node-type", "vserver");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "25", "aai-node-type", "vserver");
- Vertex vserver3 = graph.addVertex(T.label, "vserver", T.id, "26", "aai-node-type", "vserver");
- Vertex vserver4 = graph.addVertex(T.label, "vserver", T.id, "38", "aai-node-type", "vserver");
-
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "27", "aai-node-type", "tenant");
- Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "28", "aai-node-type", "tenant");
- Vertex tenant2 = graph.addVertex(T.label, "tenant", T.id, "29", "aai-node-type", "tenant");
- Vertex tenant3 = graph.addVertex(T.label, "tenant", T.id, "30", "aai-node-type", "tenant");
- Vertex tenant4 = graph.addVertex(T.label, "tenant", T.id, "39", "aai-node-type", "tenant");
-
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "31", "aai-node-type", "cloud-region",
- "aai-uri", "c1oud-region-1");
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "32", "aai-node-type", "cloud-region",
- "aai-uri", "c1oud-region-2");
- Vertex cloudregion2 = graph.addVertex(T.label, "cloud-region", T.id, "33", "aai-node-type", "cloud-region",
- "aai-uri", "c1oud-region-3");
- Vertex cloudregion3 = graph.addVertex(T.label, "cloud-region", T.id, "34", "aai-node-type", "cloud-region",
- "aai-uri", "c1oud-region-4");
- Vertex cloudregion4 = graph.addVertex(T.label, "cloud-region", T.id, "40", "aai-node-type", "cloud-region",
- "aai-uri", "c1oud-region-5");
-
- GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, servicesubscription, serviceinstance);
-
- rules.addEdge(g, serviceinstance, allottedresource);
- rules.addEdge(g, serviceinstance, allottedresource1);
- rules.addEdge(g, serviceinstance, allottedresource2);
- rules.addEdge(g, serviceinstance, allottedresource3);
-
- rules.addTreeEdge(g, allottedresource, serviceinstance1);
- rules.addTreeEdge(g, serviceinstance1, servicesubscription1);
- rules.addTreeEdge(g, servicesubscription1, serviceinstance2);
- rules.addEdge(g, serviceinstance2, gvnf);
- rules.addEdge(g, gvnf, vserver);
- rules.addTreeEdge(g, vserver, tenant);
- rules.addTreeEdge(g, tenant, cloudregion);
-
- rules.addTreeEdge(g, allottedresource1, serviceinstance4);
- rules.addTreeEdge(g, serviceinstance4, servicesubscription3);
- rules.addTreeEdge(g, servicesubscription3, serviceinstance5);
- rules.addEdge(g, serviceinstance5, gvnf2);
- rules.addEdge(g, gvnf2, vserver2);
- rules.addTreeEdge(g, vserver2, tenant2);
- rules.addTreeEdge(g, tenant2, cloudregion2);
-
- rules.addTreeEdge(g, allottedresource2, serviceinstance6);
- rules.addTreeEdge(g, serviceinstance6, servicesubscription4);
- rules.addTreeEdge(g, servicesubscription4, serviceinstance7);
- rules.addEdge(g, serviceinstance7, gvnf3);
- rules.addEdge(g, gvnf3, vserver3);
- rules.addTreeEdge(g, vserver3, tenant3);
- rules.addTreeEdge(g, tenant3, cloudregion3);
-
- rules.addTreeEdge(g, allottedresource3, serviceinstance8);
- rules.addTreeEdge(g, serviceinstance8, servicesubscription5);
- rules.addTreeEdge(g, servicesubscription5, serviceinstance9);
- rules.addEdge(g, serviceinstance9, gvnf4);
- rules.addEdge(g, gvnf4, vserver4);
- rules.addTreeEdge(g, vserver4, tenant4);
- rules.addTreeEdge(g, tenant4, cloudregion4);// Not expected in output as vnf-type is not HG
-
-
- rules.addTreeEdge(g, servicesubscription2, serviceinstance3);
- rules.addEdge(g, serviceinstance3, allottedresource);
- rules.addEdge(g, serviceinstance2, gvnf1);
- rules.addEdge(g, gvnf1, vserver1);
- rules.addTreeEdge(g, vserver1, tenant1);
- rules.addTreeEdge(g, tenant1, cloudregion1);// Not expected in output as service-subscription is not DHV
-
- }
-
- @Override
- protected String getQueryName() {
- return "cloud-regions-by-generic-vnf-HG-pairs";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "service-subscription").has("service-type", "DHV");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+public class CloudRegionsByGenericVnfHGPairsTest extends LinkedHashMapQueryTest {
+
+ public CloudRegionsByGenericVnfHGPairsTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void test() {
+ super.run();
+ String expectedServiceInstanceUri = "service-instance-id1";
+ String[] expectedCloudRegions = {"c1oud-region-1", "c1oud-region-3", "c1oud-region-4"};
+ String[] actualCloudRegions = new String[3];
+ assertEquals("Number of results is correct", hashMapList.size(), 3);
+ for (int i = 0; i < hashMapList.size(); i++) {
+ LinkedHashMap currentMap = hashMapList.get(i);
+ assertEquals("Result " + i + " has correct service-instance",
+ currentMap.get("a").toString(), expectedServiceInstanceUri);
+ actualCloudRegions[i] = currentMap.get("b").toString();
+ }
+ Arrays.sort(expectedCloudRegions);
+ Arrays.sort(actualCloudRegions);
+ assertTrue("Cloud regions are correct",
+ Arrays.equals(actualCloudRegions, expectedCloudRegions));
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex servicesubscription = graph.addVertex(T.label, "service-subscription", T.id, "0",
+ "aai-node-type", "service-subscription", "service-type", "DHV");
+ Vertex servicesubscription1 = graph.addVertex(T.label, "service-subscription", T.id, "1",
+ "aai-node-type", "service-subscription", "service-type", "HNGATEWAY");
+ Vertex servicesubscription2 = graph.addVertex(T.label, "service-subscription", T.id, "2",
+ "aai-node-type", "service-subscription", "service-type", "service-type-2");
+
+ Vertex servicesubscription3 = graph.addVertex(T.label, "service-subscription", T.id, "3",
+ "aai-node-type", "service-subscription", "service-type", "HNGATEWAY");
+ Vertex servicesubscription4 = graph.addVertex(T.label, "service-subscription", T.id, "4",
+ "aai-node-type", "service-subscription", "service-type", "HNGATEWAY");
+ Vertex servicesubscription5 = graph.addVertex(T.label, "service-subscription", T.id, "5",
+ "aai-node-type", "service-subscription", "service-type", "HNGATEWAY");
+
+ Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "6",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id1",
+ "aai-uri", "service-instance-id1");
+ Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "7",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id2",
+ "aai-uri", "service-instance-id2");
+ Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "8",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id3",
+ "aai-uri", "service-instance-id3");
+ Vertex serviceinstance3 = graph.addVertex(T.label, "service-instance", T.id, "9",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id4",
+ "aai-uri", "service-instance-id4");
+
+ Vertex serviceinstance4 = graph.addVertex(T.label, "service-instance", T.id, "10",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id5",
+ "aai-uri", "service-instance-id5");
+ Vertex serviceinstance5 = graph.addVertex(T.label, "service-instance", T.id, "11",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id6",
+ "aai-uri", "service-instance-id6");
+ Vertex serviceinstance6 = graph.addVertex(T.label, "service-instance", T.id, "12",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id7",
+ "aai-uri", "service-instance-id7");
+
+ Vertex serviceinstance7 = graph.addVertex(T.label, "service-instance", T.id, "13",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id8",
+ "aai-uri", "service-instance-id8");
+ Vertex serviceinstance8 = graph.addVertex(T.label, "service-instance", T.id, "14",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id9",
+ "aai-uri", "service-instance-id9");
+ Vertex serviceinstance9 = graph.addVertex(T.label, "service-instance", T.id, "15",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id10",
+ "aai-uri", "service-instance-id10");
+
+ Vertex allottedresource = graph.addVertex(T.label, "allotted-resource", T.id, "16",
+ "aai-node-type", "allotted-resource");
+ Vertex allottedresource1 = graph.addVertex(T.label, "allotted-resource", T.id, "17",
+ "aai-node-type", "allotted-resource");
+ Vertex allottedresource2 = graph.addVertex(T.label, "allotted-resource", T.id, "18",
+ "aai-node-type", "allotted-resource");
+ Vertex allottedresource3 = graph.addVertex(T.label, "allotted-resource", T.id, "35",
+ "aai-node-type", "allotted-resource");
+
+ Vertex gvnf = graph.addVertex(T.label, "generic-vnf", T.id, "19", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-0", "vnf-type", "HG");
+ Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "20", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1", "vnf-type", "vnf-type-1");
+ Vertex gvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "21", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-2", "vnf-type", "HG");
+ Vertex gvnf3 = graph.addVertex(T.label, "generic-vnf", T.id, "22", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-2", "vnf-type", "HG");
+ Vertex gvnf4 = graph.addVertex(T.label, "generic-vnf", T.id, "36", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-2", "vnf-type", "HP");
+
+ Vertex vserver =
+ graph.addVertex(T.label, "vserver", T.id, "23", "aai-node-type", "vserver");
+ Vertex vserver1 =
+ graph.addVertex(T.label, "vserver", T.id, "24", "aai-node-type", "vserver");
+ Vertex vserver2 =
+ graph.addVertex(T.label, "vserver", T.id, "25", "aai-node-type", "vserver");
+ Vertex vserver3 =
+ graph.addVertex(T.label, "vserver", T.id, "26", "aai-node-type", "vserver");
+ Vertex vserver4 =
+ graph.addVertex(T.label, "vserver", T.id, "38", "aai-node-type", "vserver");
+
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "27", "aai-node-type", "tenant");
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "28", "aai-node-type", "tenant");
+ Vertex tenant2 = graph.addVertex(T.label, "tenant", T.id, "29", "aai-node-type", "tenant");
+ Vertex tenant3 = graph.addVertex(T.label, "tenant", T.id, "30", "aai-node-type", "tenant");
+ Vertex tenant4 = graph.addVertex(T.label, "tenant", T.id, "39", "aai-node-type", "tenant");
+
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "31", "aai-node-type",
+ "cloud-region", "aai-uri", "c1oud-region-1");
+ Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "32", "aai-node-type",
+ "cloud-region", "aai-uri", "c1oud-region-2");
+ Vertex cloudregion2 = graph.addVertex(T.label, "cloud-region", T.id, "33", "aai-node-type",
+ "cloud-region", "aai-uri", "c1oud-region-3");
+ Vertex cloudregion3 = graph.addVertex(T.label, "cloud-region", T.id, "34", "aai-node-type",
+ "cloud-region", "aai-uri", "c1oud-region-4");
+ Vertex cloudregion4 = graph.addVertex(T.label, "cloud-region", T.id, "40", "aai-node-type",
+ "cloud-region", "aai-uri", "c1oud-region-5");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addTreeEdge(g, servicesubscription, serviceinstance);
+
+ rules.addEdge(g, serviceinstance, allottedresource);
+ rules.addEdge(g, serviceinstance, allottedresource1);
+ rules.addEdge(g, serviceinstance, allottedresource2);
+ rules.addEdge(g, serviceinstance, allottedresource3);
+
+ rules.addTreeEdge(g, allottedresource, serviceinstance1);
+ rules.addTreeEdge(g, serviceinstance1, servicesubscription1);
+ rules.addTreeEdge(g, servicesubscription1, serviceinstance2);
+ rules.addEdge(g, serviceinstance2, gvnf);
+ rules.addEdge(g, gvnf, vserver);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addTreeEdge(g, tenant, cloudregion);
+
+ rules.addTreeEdge(g, allottedresource1, serviceinstance4);
+ rules.addTreeEdge(g, serviceinstance4, servicesubscription3);
+ rules.addTreeEdge(g, servicesubscription3, serviceinstance5);
+ rules.addEdge(g, serviceinstance5, gvnf2);
+ rules.addEdge(g, gvnf2, vserver2);
+ rules.addTreeEdge(g, vserver2, tenant2);
+ rules.addTreeEdge(g, tenant2, cloudregion2);
+
+ rules.addTreeEdge(g, allottedresource2, serviceinstance6);
+ rules.addTreeEdge(g, serviceinstance6, servicesubscription4);
+ rules.addTreeEdge(g, servicesubscription4, serviceinstance7);
+ rules.addEdge(g, serviceinstance7, gvnf3);
+ rules.addEdge(g, gvnf3, vserver3);
+ rules.addTreeEdge(g, vserver3, tenant3);
+ rules.addTreeEdge(g, tenant3, cloudregion3);
+
+ rules.addTreeEdge(g, allottedresource3, serviceinstance8);
+ rules.addTreeEdge(g, serviceinstance8, servicesubscription5);
+ rules.addTreeEdge(g, servicesubscription5, serviceinstance9);
+ rules.addEdge(g, serviceinstance9, gvnf4);
+ rules.addEdge(g, gvnf4, vserver4);
+ rules.addTreeEdge(g, vserver4, tenant4);
+ rules.addTreeEdge(g, tenant4, cloudregion4);// Not expected in output as vnf-type is not HG
+
+ rules.addTreeEdge(g, servicesubscription2, serviceinstance3);
+ rules.addEdge(g, serviceinstance3, allottedresource);
+ rules.addEdge(g, serviceinstance2, gvnf1);
+ rules.addEdge(g, gvnf1, vserver1);
+ rules.addTreeEdge(g, vserver1, tenant1);
+ rules.addTreeEdge(g, tenant1, cloudregion1);// Not expected in output as
+ // service-subscription is not DHV
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "cloud-regions-by-generic-vnf-HG-pairs";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "service-subscription").has("service-type", "DHV");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/ColocatedDevicesQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/ColocatedDevicesQueryTest.java
index ee5db08..e94a7ef 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/ColocatedDevicesQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/ColocatedDevicesQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,89 +26,105 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class ColocatedDevicesQueryTest extends QueryTest {
- public ColocatedDevicesQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
-
- //Set up the test graph
- Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex", "physical-location-id", "clli1");
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver", "hostname", "pservername1");
- Vertex pserverint1 = graph.addVertex(T.label, "p-interface", T.id, "2", "aai-node-type", "p-interface", "interface-name", "xe0/0/0");
- Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "3", "aai-node-type", "pnf", "pnf-name", "pnfname1");
- Vertex pnfint1 = graph.addVertex(T.label, "p-interface", T.id, "4", "aai-node-type", "p-interface", "interface-name", "ge0/0/0");
- Vertex plink1 = graph.addVertex(T.label, "physical-link", T.id, "5", "aai-node-type", "physical-link", "link-name", "ge0/0/0-to-xe0/0/0");
-
- Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "6", "aai-node-type", "complex", "physical-location-id", "clli2");
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "7", "aai-node-type", "pserver", "hostname", "pservername2");
- Vertex pserverint2 = graph.addVertex(T.label, "p-interface", T.id, "8", "aai-node-type", "p-interface", "interface-name", "xe0/0/1");
- Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "9", "aai-node-type", "pserver", "hostname", "pservername3");
- Vertex pserverint3 = graph.addVertex(T.label, "p-interface", T.id, "10", "aai-node-type", "p-interface", "interface-name", "xe0/0/3");
- Vertex plink2 = graph.addVertex(T.label, "physical-link", T.id, "11", "aai-node-type", "physical-link", "link-name", "xe0/0/1-to-xe0/0/3");
-
- Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "12", "aai-node-type", "pnf", "pnf-name", "pnfname2");
- Vertex pnfint2 = graph.addVertex(T.label, "p-interface", T.id, "13", "aai-node-type", "p-interface", "interface-name", "ge0/0/2");
- Vertex pnf3 = graph.addVertex(T.label, "pnf", T.id, "14", "aai-node-type", "pnf", "pnf-name", "pnfname3");
- Vertex pnfint3 = graph.addVertex(T.label, "p-interface", T.id, "15", "aai-node-type", "p-interface", "interface-name", "ge0/0/3");
- Vertex plink3 = graph.addVertex(T.label, "physical-link", T.id, "16", "aai-node-type", "physical-link", "link-name", "ge0/0/2-to-ge0/0/3");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, pserver1, complex1);
- rules.addTreeEdge(g, pserver1, pserverint1);
- rules.addEdge(g, pnf1, complex1);
- rules.addTreeEdge(g, pnf1, pnfint1);
- rules.addEdge(g, pserverint1, plink1);
- rules.addEdge(g, pnfint1, plink1);
-
- rules.addEdge(g, pserver2, complex1);
- rules.addTreeEdge(g, pserver2, pserverint2);
- rules.addEdge(g, pserver3, complex2);
- rules.addTreeEdge(g, pserver3, pserverint3);
- rules.addEdge(g, pserverint2, plink2);
- rules.addEdge(g, pserverint3, plink2);
-
- rules.addEdge(g, pnf2, complex2);
- rules.addTreeEdge(g, pnf2, pnfint2);
- rules.addEdge(g, pnf3, complex2);
- rules.addTreeEdge(g, pnf3, pnfint3);
- rules.addEdge(g, pnfint2, plink3);
- rules.addEdge(g, pnfint3, plink3);
-
-
- expectedResult.add(pnf1);
- expectedResult.add(pnfint1);
- expectedResult.add(pserver1);
- expectedResult.add(pserverint1);
- expectedResult.add(plink1);
- expectedResult.add(pserver2);
- expectedResult.add(pserverint2);
- expectedResult.add(plink2);
-
-
- }
- @Override
- protected String getQueryName() {
- return "colocated-devices";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("hostname", "pservername1");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ public ColocatedDevicesQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+
+ // Set up the test graph
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex",
+ "physical-location-id", "clli1");
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver",
+ "hostname", "pservername1");
+ Vertex pserverint1 = graph.addVertex(T.label, "p-interface", T.id, "2", "aai-node-type",
+ "p-interface", "interface-name", "xe0/0/0");
+ Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "3", "aai-node-type", "pnf", "pnf-name",
+ "pnfname1");
+ Vertex pnfint1 = graph.addVertex(T.label, "p-interface", T.id, "4", "aai-node-type",
+ "p-interface", "interface-name", "ge0/0/0");
+ Vertex plink1 = graph.addVertex(T.label, "physical-link", T.id, "5", "aai-node-type",
+ "physical-link", "link-name", "ge0/0/0-to-xe0/0/0");
+
+ Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "6", "aai-node-type", "complex",
+ "physical-location-id", "clli2");
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "7", "aai-node-type", "pserver",
+ "hostname", "pservername2");
+ Vertex pserverint2 = graph.addVertex(T.label, "p-interface", T.id, "8", "aai-node-type",
+ "p-interface", "interface-name", "xe0/0/1");
+ Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "9", "aai-node-type", "pserver",
+ "hostname", "pservername3");
+ Vertex pserverint3 = graph.addVertex(T.label, "p-interface", T.id, "10", "aai-node-type",
+ "p-interface", "interface-name", "xe0/0/3");
+ Vertex plink2 = graph.addVertex(T.label, "physical-link", T.id, "11", "aai-node-type",
+ "physical-link", "link-name", "xe0/0/1-to-xe0/0/3");
+
+ Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "12", "aai-node-type", "pnf",
+ "pnf-name", "pnfname2");
+ Vertex pnfint2 = graph.addVertex(T.label, "p-interface", T.id, "13", "aai-node-type",
+ "p-interface", "interface-name", "ge0/0/2");
+ Vertex pnf3 = graph.addVertex(T.label, "pnf", T.id, "14", "aai-node-type", "pnf",
+ "pnf-name", "pnfname3");
+ Vertex pnfint3 = graph.addVertex(T.label, "p-interface", T.id, "15", "aai-node-type",
+ "p-interface", "interface-name", "ge0/0/3");
+ Vertex plink3 = graph.addVertex(T.label, "physical-link", T.id, "16", "aai-node-type",
+ "physical-link", "link-name", "ge0/0/2-to-ge0/0/3");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, pserver1, complex1);
+ rules.addTreeEdge(g, pserver1, pserverint1);
+ rules.addEdge(g, pnf1, complex1);
+ rules.addTreeEdge(g, pnf1, pnfint1);
+ rules.addEdge(g, pserverint1, plink1);
+ rules.addEdge(g, pnfint1, plink1);
+
+ rules.addEdge(g, pserver2, complex1);
+ rules.addTreeEdge(g, pserver2, pserverint2);
+ rules.addEdge(g, pserver3, complex2);
+ rules.addTreeEdge(g, pserver3, pserverint3);
+ rules.addEdge(g, pserverint2, plink2);
+ rules.addEdge(g, pserverint3, plink2);
+
+ rules.addEdge(g, pnf2, complex2);
+ rules.addTreeEdge(g, pnf2, pnfint2);
+ rules.addEdge(g, pnf3, complex2);
+ rules.addTreeEdge(g, pnf3, pnfint3);
+ rules.addEdge(g, pnfint2, plink3);
+ rules.addEdge(g, pnfint3, plink3);
+
+ expectedResult.add(pnf1);
+ expectedResult.add(pnfint1);
+ expectedResult.add(pserver1);
+ expectedResult.add(pserverint1);
+ expectedResult.add(plink1);
+ expectedResult.add(pserver2);
+ expectedResult.add(pserverint2);
+ expectedResult.add(plink2);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "colocated-devices";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("hostname", "pservername1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/ComplexFromVnfTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/ComplexFromVnfTest.java
index 72b2898..63a3a0c 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/ComplexFromVnfTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/ComplexFromVnfTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,56 +26,63 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class ComplexFromVnfTest extends QueryTest {
- public ComplexFromVnfTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public ComplexFromVnfTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "1", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "2", "aai-node-type", "pserver",
+ "hostname", "hostname-1");
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-1", "country", "US");
+
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver",
+ "hostname", "hostname-2");
+ Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "6", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-2", "country", "US");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, gnvf1, vserver1);
+ rules.addEdge(g, vserver1, pserver1);
+ rules.addEdge(g, pserver1, complex1);
+ rules.addEdge(g, gnvf1, pserver2);
+ rules.addEdge(g, pserver2, complex2);
+
+ expectedResult.add(gnvf1);
+ expectedResult.add(pserver1);
+ expectedResult.add(complex1);
+ expectedResult.add(pserver2);
+ expectedResult.add(complex2);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "complex-fromVnf";
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("vnf-name", "vnf-name-1");
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "1", "aai-node-type", "vserver", "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "2", "aai-node-type", "pserver", "hostname", "hostname-1");
- Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex", "physical-location-id", "physical-location-id-1", "country", "US");
-
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver", "hostname", "hostname-2");
- Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "6", "aai-node-type", "complex", "physical-location-id", "physical-location-id-2", "country", "US");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, gnvf1, vserver1);
- rules.addEdge(g, vserver1, pserver1);
- rules.addEdge(g, pserver1, complex1);
- rules.addEdge(g, gnvf1, pserver2);
- rules.addEdge(g, pserver2, complex2);
-
- expectedResult.add(gnvf1);
- expectedResult.add(pserver1);
- expectedResult.add(complex1);
- expectedResult.add(pserver2);
- expectedResult.add(complex2);
- }
+ }
- @Override
- protected String getQueryName() {
- return "complex-fromVnf";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("vnf-name", "vnf-name-1");
-
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/ContainmentPathQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/ContainmentPathQueryTest.java
index 1a7edb4..dd9dcdd 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/ContainmentPathQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/ContainmentPathQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,13 @@
*/
package org.onap.aai.rest.search;
+import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertThat;
+
+import java.util.Map;
+import java.util.stream.Collectors;
+
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.structure.T;
@@ -27,13 +34,6 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-import java.util.stream.Collectors;
-
-import static org.hamcrest.collection.IsIterableContainingInOrder.contains;
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertThat;
-
public class ContainmentPathQueryTest extends PathQueryTest {
public ContainmentPathQueryTest() throws AAIException, NoEdgeRuleFoundException {
@@ -42,10 +42,14 @@ public class ContainmentPathQueryTest extends PathQueryTest {
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "0", "aai-node-type", "pnf", "pnf-name", "pnf-1");
- Vertex pInterface1 = graph.addVertex(T.label, "p-interface", T.id, "1", "aai-node-type", "p-interface", "interface-name", "p-interface-1");
- Vertex lInterface1 = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type", "l-interface", "interface-name", "l-interface-1");
- Vertex vlan1 = graph.addVertex(T.label, "vlan", T.id, "3", "aai-node-type", "vlan", "vlan-interface", "vlan-1");
+ Vertex pnf1 =
+ graph.addVertex(T.label, "pnf", T.id, "0", "aai-node-type", "pnf", "pnf-name", "pnf-1");
+ Vertex pInterface1 = graph.addVertex(T.label, "p-interface", T.id, "1", "aai-node-type",
+ "p-interface", "interface-name", "p-interface-1");
+ Vertex lInterface1 = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type",
+ "l-interface", "interface-name", "l-interface-1");
+ Vertex vlan1 = graph.addVertex(T.label, "vlan", T.id, "3", "aai-node-type", "vlan",
+ "vlan-interface", "vlan-1");
rules.addTreeEdge(gts, pnf1, pInterface1);
rules.addTreeEdge(gts, pInterface1, lInterface1);
@@ -55,16 +59,22 @@ public class ContainmentPathQueryTest extends PathQueryTest {
@Test
public void vlanPathTest() {
super.run();
- assertEquals("1 path is returned ",1, pathList.size());
+ assertEquals("1 path is returned ", 1, pathList.size());
Path path = pathList.get(0);
- Vertex pnf1 = graph.traversal().V().has("aai-node-type", "pnf").has("pnf-name", "pnf-1").next();
- Vertex pInterface1 = graph.traversal().V().has("aai-node-type", "p-interface").has("interface-name", "p-interface-1").next();
- Vertex lInterface1 = graph.traversal().V().has("aai-node-type", "l-interface").has("interface-name", "l-interface-1").next();
- Vertex vlan1 = graph.traversal().V().has("aai-node-type", "vlan").has("vlan-interface", "vlan-1").next();
+ Vertex pnf1 =
+ graph.traversal().V().has("aai-node-type", "pnf").has("pnf-name", "pnf-1").next();
+ Vertex pInterface1 = graph.traversal().V().has("aai-node-type", "p-interface")
+ .has("interface-name", "p-interface-1").next();
+ Vertex lInterface1 = graph.traversal().V().has("aai-node-type", "l-interface")
+ .has("interface-name", "l-interface-1").next();
+ Vertex vlan1 = graph.traversal().V().has("aai-node-type", "vlan")
+ .has("vlan-interface", "vlan-1").next();
- //remoce edges
- assertThat(path.objects().stream().filter(o -> o instanceof Vertex).collect(Collectors.toList()), contains(vlan1, lInterface1, pInterface1, pnf1));
+ // remoce edges
+ assertThat(
+ path.objects().stream().filter(o -> o instanceof Vertex).collect(Collectors.toList()),
+ contains(vlan1, lInterface1, pInterface1, pnf1));
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/CountVnfByVnfTypeTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/CountVnfByVnfTypeTest.java
index 3ec0886..3f34e36 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/CountVnfByVnfTypeTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/CountVnfByVnfTypeTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -18,29 +18,33 @@
* ============LICENSE_END=========================================================
*/
/**
-* ============LICENSE_START=======================================================
-* org.onap.aai
-* ================================================================================
-* Copyright © 2017 AT&T Intellectual Property. All rights reserved.
-* ================================================================================
-* Licensed under the Apache License, Version 2.0 (the "License");
-* you may not use this file except in compliance with the License.
-* You may obtain a copy of the License at
-*
-* http://www.apache.org/licenses/LICENSE-2.0
-*
-* Unless required by applicable law or agreed to in writing, software
-* distributed under the License is distributed on an "AS IS" BASIS,
-* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
-* See the License for the specific language governing permissions and
-* limitations under the License.
-* ============LICENSE_END=========================================================
-*
-* ECOMP is a trademark and service mark of AT&T Intellectual Property.
-*/
+ * ============LICENSE_START=======================================================
+ * org.onap.aai
+ * ================================================================================
+ * Copyright © 2017 AT&T Intellectual Property. All rights reserved.
+ * ================================================================================
+ * Licensed under the Apache License, Version 2.0 (the "License");
+ * you may not use this file except in compliance with the License.
+ * You may obtain a copy of the License at
+ *
+ * http://www.apache.org/licenses/LICENSE-2.0
+ *
+ * Unless required by applicable law or agreed to in writing, software
+ * distributed under the License is distributed on an "AS IS" BASIS,
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ * See the License for the specific language governing permissions and
+ * limitations under the License.
+ * ============LICENSE_END=========================================================
+ *
+ * ECOMP is a trademark and service mark of AT&T Intellectual Property.
+ */
package org.onap.aai.rest.search;
import com.google.common.collect.ImmutableMap;
+
+import java.util.ArrayList;
+import java.util.Map;
+
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.T;
@@ -48,54 +52,57 @@ import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
-import java.util.ArrayList;
-import java.util.Map;
-
public class CountVnfByVnfTypeTest extends QueryCountTest {
- public CountVnfByVnfTypeTest() throws AAIException {
- super();
+ public CountVnfByVnfTypeTest() throws AAIException {
+ super();
}
@Test
public void test() {
- super.run();
+ super.run();
}
@Override
- protected void createGraph() throws AAIException {
- //Set up the test graph
- Vertex genericVnfTypeA1 = graph.addVertex(T.label, "genric-vnf", T.id, "1", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1", "vnf-type", "A");
- Vertex genericVnfTypeB1 = graph.addVertex(T.label, "genric-vnf", T.id, "2", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-2", "vnf-name", "vnf-name-2", "vnf-type", "B");
- Vertex genericVnfTypeC1 = graph.addVertex(T.label, "genric-vnf", T.id, "3", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-3", "vnf-name", "vnf-name-3", "vnf-type", "C");
- Vertex genericVnfTypeA2 = graph.addVertex(T.label, "genric-vnf", T.id, "4", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-4", "vnf-name", "vnf-name-4", "vnf-type", "A");
- Vertex genericVnfTypeB2 = graph.addVertex(T.label, "genric-vnf", T.id, "5", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-5", "vnf-name", "vnf-name-5", "vnf-type", "B");
- Vertex genericVnfTypeA3 = graph.addVertex(T.label, "genric-vnf", T.id, "6", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-6", "vnf-name", "vnf-name-6", "vnf-type", "A");
- Vertex genericVnfTypeA4 = graph.addVertex(T.label, "genric-vnf", T.id, "7", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-7", "vnf-name", "vnf-name-7", "vnf-type", "A");
-
- GraphTraversalSource g = graph.traversal();
+ protected void createGraph() throws AAIException {
+ // Set up the test graph
+ Vertex genericVnfTypeA1 = graph.addVertex(T.label, "genric-vnf", T.id, "1", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1", "vnf-type", "A");
+ Vertex genericVnfTypeB1 = graph.addVertex(T.label, "genric-vnf", T.id, "2", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-2", "vnf-name", "vnf-name-2", "vnf-type", "B");
+ Vertex genericVnfTypeC1 = graph.addVertex(T.label, "genric-vnf", T.id, "3", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-3", "vnf-name", "vnf-name-3", "vnf-type", "C");
+ Vertex genericVnfTypeA2 = graph.addVertex(T.label, "genric-vnf", T.id, "4", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-4", "vnf-name", "vnf-name-4", "vnf-type", "A");
+ Vertex genericVnfTypeB2 = graph.addVertex(T.label, "genric-vnf", T.id, "5", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-5", "vnf-name", "vnf-name-5", "vnf-type", "B");
+ Vertex genericVnfTypeA3 = graph.addVertex(T.label, "genric-vnf", T.id, "6", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-6", "vnf-name", "vnf-name-6", "vnf-type", "A");
+ Vertex genericVnfTypeA4 = graph.addVertex(T.label, "genric-vnf", T.id, "7", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-7", "vnf-name", "vnf-name-7", "vnf-type", "A");
- listOfMapEntryForCoutnQueries = new ArrayList<>();
- listOfMapEntryForCoutnQueries.add(ImmutableMap.of("A", 4L).entrySet().iterator().next());
- listOfMapEntryForCoutnQueries.add(ImmutableMap.of("B", 2L).entrySet().iterator().next());
- listOfMapEntryForCoutnQueries.add(ImmutableMap.of("C", 1L).entrySet().iterator().next());
- //expectedResultForMaps = expectedResultForMaps + "[A=4, B=2, C=1]";
- }
+ GraphTraversalSource g = graph.traversal();
- @Override
- protected String getQueryName() {
- return "count-vnf-byVnfType";
- }
+ listOfMapEntryForCoutnQueries = new ArrayList<>();
+ listOfMapEntryForCoutnQueries.add(ImmutableMap.of("A", 4L).entrySet().iterator().next());
+ listOfMapEntryForCoutnQueries.add(ImmutableMap.of("B", 2L).entrySet().iterator().next());
+ listOfMapEntryForCoutnQueries.add(ImmutableMap.of("C", 1L).entrySet().iterator().next());
+ // expectedResultForMaps = expectedResultForMaps + "[A=4, B=2, C=1]";
+ }
+ @Override
+ protected String getQueryName() {
+ return "count-vnf-byVnfType";
+ }
@Override
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- return;
+ return;
}
@Override
protected void addParam(Map<String, Object> params) {
- return;
+ return;
}
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/DestinationFromConfigurationQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/DestinationFromConfigurationQueryTest.java
index 47c7d84..bf50dde 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/DestinationFromConfigurationQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/DestinationFromConfigurationQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,7 +19,6 @@
*/
package org.onap.aai.rest.search;
-
import java.util.Map;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
@@ -32,69 +31,79 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class DestinationFromConfigurationQueryTest extends QueryTest {
- public DestinationFromConfigurationQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void test() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex config = graph.addVertex(T.label, "configuration", T.id, "0", "aai-node-type", "configuration", "configuration-id", "configuration");
- Vertex logicalLink = graph.addVertex(T.label, "l", T.id, "1", "aai-node-type", "logical-link", "link-name", "link-name-0");
- Vertex lInterface = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type", "l-interface", "interface-name", "interface-name-0");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserver-id-0", "vserver-name", "vserver-name-0");
- Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "4", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-0", "vf-module-name", "vf-module-name0");
-
- Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "5", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-0", "vnf-name", "vnf-name-0");
-
- Vertex logicalLink1 = graph.addVertex(T.label, "l", T.id, "11", "aai-node-type", "logical-link", "link-name", "link-name-1");
- Vertex lInterface1 = graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type", "l-interface", "interface-name", "interface-name-1");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "13", "aai-node-type", "vserver", "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
- Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "14", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
-
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "15", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
- Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "16", "aai-node-type", "pnf", "pnf-name", "pnfname-1");
-
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, config, logicalLink);
- rules.addEdge(g, logicalLink, lInterface,"org.onap.relationships.inventory.Destination");
- rules.addTreeEdge(g, lInterface, vserver);
- rules.addEdge(g, vserver, vfmodule);
- rules.addTreeEdge(g, vfmodule, gnvf);
-
- rules.addEdge(g, logicalLink, lInterface1,"tosca.relationships.network.LinksTo");//false
- rules.addTreeEdge(g, lInterface1, vserver1);//false
- rules.addEdge(g, vserver1, vfmodule1);//false
- rules.addTreeEdge(g, vfmodule1, gnvf1);//false
-
- rules.addEdge(g, config, logicalLink1);
- rules.addEdge(g, logicalLink1, gnvf1);
- rules.addEdge(g, gnvf1, pnf1);
-
-
- expectedResult.add(gnvf);
- expectedResult.add(pnf1);
- }
-
- @Override
- protected String getQueryName() {
- return "destination-FromConfiguration";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "configuration").has("configuration-id", "configuration");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ public DestinationFromConfigurationQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void test() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex config = graph.addVertex(T.label, "configuration", T.id, "0", "aai-node-type",
+ "configuration", "configuration-id", "configuration");
+ Vertex logicalLink = graph.addVertex(T.label, "l", T.id, "1", "aai-node-type",
+ "logical-link", "link-name", "link-name-0");
+ Vertex lInterface = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type",
+ "l-interface", "interface-name", "interface-name-0");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-0", "vserver-name", "vserver-name-0");
+ Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "4", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-0", "vf-module-name", "vf-module-name0");
+
+ Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "5", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-0", "vnf-name", "vnf-name-0");
+
+ Vertex logicalLink1 = graph.addVertex(T.label, "l", T.id, "11", "aai-node-type",
+ "logical-link", "link-name", "link-name-1");
+ Vertex lInterface1 = graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type",
+ "l-interface", "interface-name", "interface-name-1");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "13", "aai-node-type",
+ "vserver", "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
+ Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "14", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
+
+ Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "15", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
+ Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "16", "aai-node-type", "pnf",
+ "pnf-name", "pnfname-1");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, config, logicalLink);
+ rules.addEdge(g, logicalLink, lInterface, "org.onap.relationships.inventory.Destination");
+ rules.addTreeEdge(g, lInterface, vserver);
+ rules.addEdge(g, vserver, vfmodule);
+ rules.addTreeEdge(g, vfmodule, gnvf);
+
+ rules.addEdge(g, logicalLink, lInterface1, "tosca.relationships.network.LinksTo");// false
+ rules.addTreeEdge(g, lInterface1, vserver1);// false
+ rules.addEdge(g, vserver1, vfmodule1);// false
+ rules.addTreeEdge(g, vfmodule1, gnvf1);// false
+
+ rules.addEdge(g, config, logicalLink1);
+ rules.addEdge(g, logicalLink1, gnvf1);
+ rules.addEdge(g, gnvf1, pnf1);
+
+ expectedResult.add(gnvf);
+ expectedResult.add(pnf1);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "destination-FromConfiguration";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "configuration").has("configuration-id", "configuration");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/FabricInformationFromVnfTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/FabricInformationFromVnfTest.java
index 68393c5..dd4b530 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/FabricInformationFromVnfTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/FabricInformationFromVnfTest.java
@@ -10,7 +10,7 @@ package org.onap.aai.rest.search;
* 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
+ * 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,
@@ -30,76 +30,95 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-public class FabricInformationFromVnfTest extends QueryTest{
-
- public FabricInformationFromVnfTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+public class FabricInformationFromVnfTest extends QueryTest {
- @Test
- public void test() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex gvnf = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-0", "vnf-name", "vnf-name-0", "vnf-type", "vnf-type-0");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "1", "aai-node-type", "vserver", "vserver-id", "vserver-id-0", "vserver-name", "vserver-name-0", "vserver-selflink", "vserver-selflink-0");
- Vertex linterface = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type", "l-interface", "interface-name", "interface-name-0");
- Vertex sriovvf = graph.addVertex(T.label, "sriov-vf", T.id, "3", "aai-node-type", "sriov-vf", "pci-id", "pci-id-0");
- Vertex sriovpf = graph.addVertex(T.label, "sriov-pf", T.id, "4", "aai-node-type", "sriov-pf", "pf-pci-id", "pf-pci-id-0");
- Vertex pinterface = graph.addVertex(T.label, "p-interface", T.id, "5", "aai-node-type", "p-interface", "interface-name", "interface-name-0");
- Vertex pserver = graph.addVertex(T.label, "p-server", T.id, "6", "aai-node-type", "pserver", "hostname", "hostname-0");
- Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "7", "aai-node-type", "vnfc", "vnfc-name", "vnfc-name-0", "nfc-naming-code", "nfc-naming-code-0", "nfc-naming-function", "nfc-naming-function-0");
- Vertex cp = graph.addVertex(T.label, "cp", T.id, "8", "aai-node-type", "cp", "cp-instance-id", "cp-instance-id-0");
- Vertex vlantag = graph.addVertex(T.label, "vlan-tag", T.id, "9", "aai-node-type", "vlan-tag","vlan-tag-id", "vlan-tag-id-0");
-
- Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "16", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1", "vnf-type", "vnf-type-1");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "10", "aai-node-type", "vserver", "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-0", "vserver-selflink", "vserver-selflink-0");
- Vertex vlantag1 = graph.addVertex(T.label, "vlan-tag", T.id, "11", "aai-node-type", "vlan-tag","vlan-tag-id", "vlan-tag-id-1");
- Vertex vnfc1 = graph.addVertex(T.label, "vnfc", T.id, "14", "aai-node-type", "vnfc", "vnfc-name", "vnfc-name-1", "nfc-naming-code", "nfc-naming-code-1", "nfc-naming-function", "nfc-naming-function-1");
- Vertex cp1 = graph.addVertex(T.label, "cp", T.id, "15", "aai-node-type", "cp", "cp-instance-id", "cp-instance-id-1");
+ public FabricInformationFromVnfTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, gvnf, vserver);
- rules.addTreeEdge(g, vserver, linterface);
- rules.addTreeEdge(g, linterface, sriovvf);
- rules.addEdge(g, sriovvf, sriovpf);
- rules.addTreeEdge(g, sriovpf, pinterface);
- rules.addTreeEdge(g, pinterface, pserver);
- rules.addEdge(g, vserver, vnfc);
- rules.addTreeEdge(g, vnfc, cp);
- rules.addEdge(g, cp, vlantag);
-
- rules.addEdge(g, gvnf1, vserver1);
- rules.addEdge(g, vserver1, vnfc1);
- rules.addTreeEdge(g, vnfc1, cp1);
- rules.addEdge(g, cp1, vlantag1);//false
-
-
- expectedResult.add(gvnf);
- expectedResult.add(vserver);
- expectedResult.add(pinterface);
- expectedResult.add(pserver);
- expectedResult.add(vnfc);
- expectedResult.add(vlantag);
- }
+ @Test
+ public void test() {
+ super.run();
+ }
- @Override
- protected String getQueryName() {
- return "fabric-information-fromVnf";
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex gvnf =
+ graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnf-id-0", "vnf-name", "vnf-name-0", "vnf-type", "vnf-type-0");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "1", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-0", "vserver-name", "vserver-name-0", "vserver-selflink",
+ "vserver-selflink-0");
+ Vertex linterface = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type",
+ "l-interface", "interface-name", "interface-name-0");
+ Vertex sriovvf = graph.addVertex(T.label, "sriov-vf", T.id, "3", "aai-node-type",
+ "sriov-vf", "pci-id", "pci-id-0");
+ Vertex sriovpf = graph.addVertex(T.label, "sriov-pf", T.id, "4", "aai-node-type",
+ "sriov-pf", "pf-pci-id", "pf-pci-id-0");
+ Vertex pinterface = graph.addVertex(T.label, "p-interface", T.id, "5", "aai-node-type",
+ "p-interface", "interface-name", "interface-name-0");
+ Vertex pserver = graph.addVertex(T.label, "p-server", T.id, "6", "aai-node-type", "pserver",
+ "hostname", "hostname-0");
+ Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "7", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfc-name-0", "nfc-naming-code", "nfc-naming-code-0",
+ "nfc-naming-function", "nfc-naming-function-0");
+ Vertex cp = graph.addVertex(T.label, "cp", T.id, "8", "aai-node-type", "cp",
+ "cp-instance-id", "cp-instance-id-0");
+ Vertex vlantag = graph.addVertex(T.label, "vlan-tag", T.id, "9", "aai-node-type",
+ "vlan-tag", "vlan-tag-id", "vlan-tag-id-0");
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "generic-vnf").has("vnf-id", "vnf-id-0");
- }
+ Vertex gvnf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "16", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1", "vnf-type", "vnf-type-1");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "10", "aai-node-type",
+ "vserver", "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-0",
+ "vserver-selflink", "vserver-selflink-0");
+ Vertex vlantag1 = graph.addVertex(T.label, "vlan-tag", T.id, "11", "aai-node-type",
+ "vlan-tag", "vlan-tag-id", "vlan-tag-id-1");
+ Vertex vnfc1 = graph.addVertex(T.label, "vnfc", T.id, "14", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfc-name-1", "nfc-naming-code", "nfc-naming-code-1",
+ "nfc-naming-function", "nfc-naming-function-1");
+ Vertex cp1 = graph.addVertex(T.label, "cp", T.id, "15", "aai-node-type", "cp",
+ "cp-instance-id", "cp-instance-id-1");
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, gvnf, vserver);
+ rules.addTreeEdge(g, vserver, linterface);
+ rules.addTreeEdge(g, linterface, sriovvf);
+ rules.addEdge(g, sriovvf, sriovpf);
+ rules.addTreeEdge(g, sriovpf, pinterface);
+ rules.addTreeEdge(g, pinterface, pserver);
+ rules.addEdge(g, vserver, vnfc);
+ rules.addTreeEdge(g, vnfc, cp);
+ rules.addEdge(g, cp, vlantag);
+
+ rules.addEdge(g, gvnf1, vserver1);
+ rules.addEdge(g, vserver1, vnfc1);
+ rules.addTreeEdge(g, vnfc1, cp1);
+ rules.addEdge(g, cp1, vlantag1);// false
+
+ expectedResult.add(gvnf);
+ expectedResult.add(vserver);
+ expectedResult.add(pinterface);
+ expectedResult.add(pserver);
+ expectedResult.add(vnfc);
+ expectedResult.add(vlantag);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "fabric-information-fromVnf";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "generic-vnf").has("vnf-id", "vnf-id-0");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/FirstNetTopology_LineOfBusinessTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/FirstNetTopology_LineOfBusinessTest.java
index 35a0cd9..93a65d2 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/FirstNetTopology_LineOfBusinessTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/FirstNetTopology_LineOfBusinessTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,68 +30,82 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class FirstNetTopology_LineOfBusinessTest extends QueryTest {
- public FirstNetTopology_LineOfBusinessTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //set up test graph
- Vertex lineofbusiness = graph.addVertex(T.label, "line-of-business", T.id, "0", "aai-node-type", "line-of-business", "line-of-business-name", "business0");
- Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf", "vnf-id", "vnfid0","vnf-name", "vnf-name-1", "nf-type", "sample-nf-type");
- Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "2", "aai-node-type", "vnfc", "vnfc-name", "vnfc0", "nfc-naming-code", "namingCode0", "nfc-function", "function0");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserverid0","vserver-name", "vserver-name-1");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver", "hostname", "pservername1");
- Vertex pnf = graph.addVertex(T.label, "pnf", T.id, "5", "aai-node-type", "pnf", "pnf-name", "pnf1name");
-
-
- Vertex lineofbusiness1 = graph.addVertex(T.label, "line-of-business", T.id, "10", "aai-node-type", "line-of-business", "line-of-business-name", "business1");
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "11", "aai-node-type", "generic-vnf", "vnf-id", "vnfid1","vnf-name", "vnf-name-2", "nf-type", "sample-nf-type1");
- Vertex vnfc1 = graph.addVertex(T.label, "vnfc", T.id, "12", "aai-node-type", "vnfc", "vnfc-name", "vnfc1", "nfc-naming-code", "namingCode1", "nfc-function", "function1");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "13", "aai-node-type", "vserver", "vserver-id", "vserverid1","vserver-name", "vserver-name-2");
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "14", "aai-node-type", "pserver", "hostname", "pservername2");
- Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "15", "aai-node-type", "pnf", "pnf-name", "pnf1name1");
+ public FirstNetTopology_LineOfBusinessTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addEdge(g, genericvnf,lineofbusiness);
- rules.addEdge(g, genericvnf, vnfc);
- rules.addEdge(g, genericvnf, vserver);
- rules.addEdge(g, genericvnf,pserver);
- rules.addEdge(g, genericvnf, pnf);
-
- //false
- rules.addEdge(g, genericvnf1,lineofbusiness1);
- rules.addEdge(g, genericvnf1, vnfc1);
- rules.addEdge(g, genericvnf1, vserver1);
- rules.addEdge(g, genericvnf1,pserver1);
- rules.addEdge(g, genericvnf1, pnf1);
+ @Test
+ public void run() {
+ super.run();
+ }
- expectedResult.add(genericvnf);
- expectedResult.add(vnfc);
- expectedResult.add(vserver);
- expectedResult.add(pserver);
- expectedResult.add(pnf);
-
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // set up test graph
+ Vertex lineofbusiness = graph.addVertex(T.label, "line-of-business", T.id, "0",
+ "aai-node-type", "line-of-business", "line-of-business-name", "business0");
+ Vertex genericvnf =
+ graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnfid0", "vnf-name", "vnf-name-1", "nf-type", "sample-nf-type");
+ Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "2", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfc0", "nfc-naming-code", "namingCode0", "nfc-function", "function0");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver",
+ "vserver-id", "vserverid0", "vserver-name", "vserver-name-1");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver",
+ "hostname", "pservername1");
+ Vertex pnf = graph.addVertex(T.label, "pnf", T.id, "5", "aai-node-type", "pnf", "pnf-name",
+ "pnf1name");
+ Vertex lineofbusiness1 = graph.addVertex(T.label, "line-of-business", T.id, "10",
+ "aai-node-type", "line-of-business", "line-of-business-name", "business1");
+ Vertex genericvnf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "11", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnfid1", "vnf-name", "vnf-name-2", "nf-type", "sample-nf-type1");
+ Vertex vnfc1 = graph.addVertex(T.label, "vnfc", T.id, "12", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfc1", "nfc-naming-code", "namingCode1", "nfc-function", "function1");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "13", "aai-node-type",
+ "vserver", "vserver-id", "vserverid1", "vserver-name", "vserver-name-2");
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "14", "aai-node-type",
+ "pserver", "hostname", "pservername2");
+ Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "15", "aai-node-type", "pnf",
+ "pnf-name", "pnf1name1");
+ GraphTraversalSource g = graph.traversal();
- }
- @Override
- protected String getQueryName() {
- return "fn-topology";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "line-of-business").has("line-of-business-name", "business0");
+ rules.addEdge(g, genericvnf, lineofbusiness);
+ rules.addEdge(g, genericvnf, vnfc);
+ rules.addEdge(g, genericvnf, vserver);
+ rules.addEdge(g, genericvnf, pserver);
+ rules.addEdge(g, genericvnf, pnf);
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
-} \ No newline at end of file
+ // false
+ rules.addEdge(g, genericvnf1, lineofbusiness1);
+ rules.addEdge(g, genericvnf1, vnfc1);
+ rules.addEdge(g, genericvnf1, vserver1);
+ rules.addEdge(g, genericvnf1, pserver1);
+ rules.addEdge(g, genericvnf1, pnf1);
+
+ expectedResult.add(genericvnf);
+ expectedResult.add(vnfc);
+ expectedResult.add(vserver);
+ expectedResult.add(pserver);
+ expectedResult.add(pnf);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "fn-topology";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "line-of-business").has("line-of-business-name", "business0");
+
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/FirstNetTopology_ServiceInstanceTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/FirstNetTopology_ServiceInstanceTest.java
index 15a8302..b2accd5 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/FirstNetTopology_ServiceInstanceTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/FirstNetTopology_ServiceInstanceTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,75 +30,96 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class FirstNetTopology_ServiceInstanceTest extends QueryTest {
- public FirstNetTopology_ServiceInstanceTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //set up test graph
- Vertex customer = graph.addVertex(T.label, "customer", T.id, "0", "aai-node-type", "customer","global-customer-id", "global-customer-id-1", "subscriber-name", "subscriber-name-1");
- Vertex serviceSubscription = graph.addVertex(T.label, "service-subscription", T.id, "1", "aai-node-type","service-subscription", "service-type", "service-type-1");
- Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "2", "aai-node-type","service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name","service-instance-name-1");
- Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type", "generic-vnf", "vnf-id", "vnfid0","vnf-name", "vnf-name-1", "nf-type", "sample-nf-type");
- Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "4", "aai-node-type", "vnfc", "vnfc-name", "vnfc0", "nfc-naming-code", "namingCode0", "nfc-function", "function0");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "5", "aai-node-type", "vserver", "vserver-id", "vserverid0","vserver-name", "vserver-name-1");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "6", "aai-node-type", "pserver", "hostname", "pservername1");
- Vertex pnf = graph.addVertex(T.label, "pnf", T.id, "7", "aai-node-type", "pnf", "pnf-name", "pnf1name");
-
- Vertex customer1 = graph.addVertex(T.label, "customer", T.id, "10", "aai-node-type", "customer","global-customer-id", "global-customer-id-2", "subscriber-name", "subscriber-name-2");
- Vertex serviceSubscription1 = graph.addVertex(T.label, "service-subscription", T.id, "11", "aai-node-type","service-subscription", "service-type", "service-type-2");
- Vertex serviceInstance1 = graph.addVertex(T.label, "service-instance", T.id, "12", "aai-node-type","service-instance", "service-instance-id", "service-instance-id-2", "service-instance-name","service-instance-name-2");
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "13", "aai-node-type", "generic-vnf", "vnf-id", "vnfid1","vnf-name", "vnf-name-2", "nf-type", "sample-nf-type1");
- Vertex vnfc1 = graph.addVertex(T.label, "vnfc", T.id, "14", "aai-node-type", "vnfc", "vnfc-name", "vnfc1", "nfc-naming-code", "namingCode1", "nfc-function", "function1");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "15", "aai-node-type", "vserver", "vserver-id", "vserverid1","vserver-name", "vserver-name-2");
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "16", "aai-node-type", "pserver", "hostname", "pservername2");
- Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "17", "aai-node-type", "pnf", "pnf-name", "pnf1name1");
-
+ public FirstNetTopology_ServiceInstanceTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addEdge(g, genericvnf, serviceInstance);
- rules.addTreeEdge(g, serviceInstance, serviceSubscription);
- rules.addTreeEdge(g, serviceSubscription, customer);
- rules.addEdge(g, genericvnf, vnfc);
- rules.addEdge(g, genericvnf, vserver);
- rules.addEdge(g, genericvnf,pserver);
- rules.addEdge(g, genericvnf, pnf);
-
-
- //false
- rules.addEdge(g, genericvnf1, serviceInstance1);
- rules.addTreeEdge(g, serviceInstance1, serviceSubscription1);
- rules.addTreeEdge(g, serviceSubscription1, customer1);
- rules.addEdge(g, genericvnf1, vnfc1);
- rules.addEdge(g, genericvnf1, vserver1);
- rules.addEdge(g, genericvnf1,pserver1);
- rules.addEdge(g, genericvnf1, pnf1);
+ @Test
+ public void run() {
+ super.run();
+ }
- expectedResult.add(genericvnf);
- expectedResult.add(vnfc);
- expectedResult.add(vserver);
- expectedResult.add(pserver);
- expectedResult.add(pnf);
-
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // set up test graph
+ Vertex customer = graph.addVertex(T.label, "customer", T.id, "0", "aai-node-type",
+ "customer", "global-customer-id", "global-customer-id-1", "subscriber-name",
+ "subscriber-name-1");
+ Vertex serviceSubscription = graph.addVertex(T.label, "service-subscription", T.id, "1",
+ "aai-node-type", "service-subscription", "service-type", "service-type-1");
+ Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "2",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
+ Vertex genericvnf =
+ graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnfid0", "vnf-name", "vnf-name-1", "nf-type", "sample-nf-type");
+ Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "4", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfc0", "nfc-naming-code", "namingCode0", "nfc-function", "function0");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "5", "aai-node-type", "vserver",
+ "vserver-id", "vserverid0", "vserver-name", "vserver-name-1");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "6", "aai-node-type", "pserver",
+ "hostname", "pservername1");
+ Vertex pnf = graph.addVertex(T.label, "pnf", T.id, "7", "aai-node-type", "pnf", "pnf-name",
+ "pnf1name");
+ Vertex customer1 = graph.addVertex(T.label, "customer", T.id, "10", "aai-node-type",
+ "customer", "global-customer-id", "global-customer-id-2", "subscriber-name",
+ "subscriber-name-2");
+ Vertex serviceSubscription1 = graph.addVertex(T.label, "service-subscription", T.id, "11",
+ "aai-node-type", "service-subscription", "service-type", "service-type-2");
+ Vertex serviceInstance1 = graph.addVertex(T.label, "service-instance", T.id, "12",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2",
+ "service-instance-name", "service-instance-name-2");
+ Vertex genericvnf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "13", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnfid1", "vnf-name", "vnf-name-2", "nf-type", "sample-nf-type1");
+ Vertex vnfc1 = graph.addVertex(T.label, "vnfc", T.id, "14", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfc1", "nfc-naming-code", "namingCode1", "nfc-function", "function1");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "15", "aai-node-type",
+ "vserver", "vserver-id", "vserverid1", "vserver-name", "vserver-name-2");
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "16", "aai-node-type",
+ "pserver", "hostname", "pservername2");
+ Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "17", "aai-node-type", "pnf",
+ "pnf-name", "pnf1name1");
+ GraphTraversalSource g = graph.traversal();
- }
- @Override
- protected String getQueryName() {
- return "fn-topology";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("service-instance-name", "service-instance-name-1");
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- }
-} \ No newline at end of file
+ rules.addEdge(g, genericvnf, serviceInstance);
+ rules.addTreeEdge(g, serviceInstance, serviceSubscription);
+ rules.addTreeEdge(g, serviceSubscription, customer);
+ rules.addEdge(g, genericvnf, vnfc);
+ rules.addEdge(g, genericvnf, vserver);
+ rules.addEdge(g, genericvnf, pserver);
+ rules.addEdge(g, genericvnf, pnf);
+
+ // false
+ rules.addEdge(g, genericvnf1, serviceInstance1);
+ rules.addTreeEdge(g, serviceInstance1, serviceSubscription1);
+ rules.addTreeEdge(g, serviceSubscription1, customer1);
+ rules.addEdge(g, genericvnf1, vnfc1);
+ rules.addEdge(g, genericvnf1, vserver1);
+ rules.addEdge(g, genericvnf1, pserver1);
+ rules.addEdge(g, genericvnf1, pnf1);
+
+ expectedResult.add(genericvnf);
+ expectedResult.add(vnfc);
+ expectedResult.add(vserver);
+ expectedResult.add(pserver);
+ expectedResult.add(pnf);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "fn-topology";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("service-instance-name", "service-instance-name-1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ }
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GFPVnfDataTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GFPVnfDataTest.java
index 6f2d0ad..08287a3 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GFPVnfDataTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GFPVnfDataTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,107 +30,146 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class GFPVnfDataTest extends QueryTest {
- public GFPVnfDataTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //set up test graph
- Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf", "vnf-id", "vnfid0","vnf-name", "vnf-name-1", "nf-type", "sample-nf-type");
- Vertex linterface = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0");
- Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "3", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "l3-interface-ipv4-address-0");
- Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "4", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "l3-interface-ipv6-address-0");
- Vertex vlan = graph.addVertex(T.label, "vlan", T.id, "5", "aai-node-type", "vlan","vlan-interface", "vlan1");
- Vertex vnfImage = graph.addVertex(T.label, "vnf-image", T.id, "6", "aai-node-type", "vnf-image", "vnf-image-uuid", "vnf1imageuuid");
- Vertex networkProfile = graph.addVertex(T.label, "network-profile", T.id, "7","aai-node-type", "network-profile","nm-profile-name", "nm-profile-name-1");
- Vertex lagint = graph.addVertex(T.label, "lag-interface", T.id, "8", "aai-node-type", "lag-interface","interface-name", "lagint1");
-
- Vertex lagint0 = graph.addVertex(T.label, "lag-interface", T.id, "11", "aai-node-type", "lag-interface","interface-name", "lagint31");
- Vertex linterface0 = graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id30", "l-interface-name", "l-interface-name30");
- Vertex vlan0 = graph.addVertex(T.label, "vlan", T.id, "13", "aai-node-type", "vlan","vlan-interface", "vlan31");
- Vertex l3inter1ipv4addresslist0 = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "14", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "l3-interface-ipv4-address-30");
- Vertex l3inter1ipv6addresslist0 = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "15", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "l3-interface-ipv6-address-30");
-
-
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "10", "aai-node-type", "generic-vnf", "vnf-id", "vnfid10","vnf-name", "vnf-name-11", "nf-type", "sample-nf-type11");
- Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "20", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id10", "l-interface-name", "l-interface-name10");
- Vertex l3inter1ipv4addresslist1 = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "30", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "l3-interface-ipv4-address-10");
- Vertex l3inter1ipv6addresslist1 = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "40", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "l3-interface-ipv6-address-10");
- Vertex vlan1 = graph.addVertex(T.label, "vlan", T.id, "50", "aai-node-type", "vlan","vlan-interface", "vlan11");
- Vertex vnfImage1 = graph.addVertex(T.label, "vnf-image", T.id, "60", "aai-node-type", "vnf-image", "vnf-image-uuid", "vnf1imageuuid11");
- Vertex networkProfile1 = graph.addVertex(T.label, "network-profile", T.id, "70","aai-node-type", "network-profile","nm-profile-name", "nm-profile-name-11");
- Vertex lagint1 = graph.addVertex(T.label, "lag-interface", T.id, "80", "aai-node-type", "lag-interface","interface-name", "lagint11");
-
-
- Vertex lagint2 = graph.addVertex(T.label, "lag-interface", T.id, "21", "aai-node-type", "lag-interface","interface-name", "lagint312");
- Vertex linterface2 = graph.addVertex(T.label, "l-interface", T.id, "22", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id30", "l-interface-name", "l-interface-name302");
- Vertex vlan2 = graph.addVertex(T.label, "vlan", T.id, "23", "aai-node-type", "vlan","vlan-interface", "vlan312");
- Vertex l3inter1ipv4addresslist2 = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "24", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "l3-interface-ipv4-address-302");
- Vertex l3inter1ipv6addresslist2 = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "25", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "l3-interface-ipv6-address-302");
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addTreeEdge(g, genericvnf, linterface);
- rules.addTreeEdge(g, l3inter1ipv4addresslist, linterface);
- rules.addTreeEdge(g, l3inter1ipv6addresslist, linterface);
- rules.addTreeEdge(g, linterface,vlan);
- rules.addTreeEdge(g, l3inter1ipv4addresslist, vlan);
- rules.addTreeEdge(g, l3inter1ipv6addresslist, vlan);
-
- rules.addTreeEdge(g, genericvnf, lagint0);
- rules.addTreeEdge(g, lagint0,linterface0);
- rules.addTreeEdge(g, linterface0,vlan0);
- rules.addTreeEdge(g, l3inter1ipv4addresslist0, linterface0);
- rules.addTreeEdge(g, l3inter1ipv6addresslist0, linterface0);
-
- rules.addEdge(g, genericvnf, vnfImage);
- rules.addEdge(g, genericvnf, networkProfile);
-
-
-
- //false
- rules.addTreeEdge(g, genericvnf1, linterface1);
- rules.addTreeEdge(g, l3inter1ipv4addresslist1, linterface1);
- rules.addTreeEdge(g, l3inter1ipv6addresslist1, linterface1);
- rules.addTreeEdge(g, linterface1,vlan1);
- rules.addTreeEdge(g, l3inter1ipv4addresslist1, vlan1);
- rules.addTreeEdge(g, l3inter1ipv6addresslist1, vlan1);
-
- rules.addTreeEdge(g, genericvnf1, lagint2);
- rules.addTreeEdge(g, linterface2,lagint2);
- rules.addTreeEdge(g, linterface2,vlan2);
- rules.addTreeEdge(g, l3inter1ipv4addresslist2, linterface2);
- rules.addTreeEdge(g, l3inter1ipv6addresslist2, linterface2);
-
- rules.addEdge(g, genericvnf1, vnfImage1);
- rules.addEdge(g, genericvnf1, networkProfile1);
-
-
- expectedResult.add(genericvnf);
- expectedResult.add(l3inter1ipv4addresslist);
- expectedResult.add(l3inter1ipv6addresslist);
- expectedResult.add(vlan);
- expectedResult.add(linterface0);
- expectedResult.add(vnfImage);
- expectedResult.add(networkProfile);
-
-
- }
- @Override
- protected String getQueryName() {
- return "gfp-vnf-data";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "generic-vnf").has("vnf-name", "vnf-name-1").has("vnf-id", "vnfid0");
-
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ public GFPVnfDataTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // set up test graph
+ Vertex genericvnf =
+ graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnfid0", "vnf-name", "vnf-name-1", "nf-type", "sample-nf-type");
+ Vertex linterface =
+ graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0");
+ Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "3", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-0");
+ Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "4", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-0");
+ Vertex vlan = graph.addVertex(T.label, "vlan", T.id, "5", "aai-node-type", "vlan",
+ "vlan-interface", "vlan1");
+ Vertex vnfImage = graph.addVertex(T.label, "vnf-image", T.id, "6", "aai-node-type",
+ "vnf-image", "vnf-image-uuid", "vnf1imageuuid");
+ Vertex networkProfile = graph.addVertex(T.label, "network-profile", T.id, "7",
+ "aai-node-type", "network-profile", "nm-profile-name", "nm-profile-name-1");
+ Vertex lagint = graph.addVertex(T.label, "lag-interface", T.id, "8", "aai-node-type",
+ "lag-interface", "interface-name", "lagint1");
+
+ Vertex lagint0 = graph.addVertex(T.label, "lag-interface", T.id, "11", "aai-node-type",
+ "lag-interface", "interface-name", "lagint31");
+ Vertex linterface0 =
+ graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id30", "l-interface-name", "l-interface-name30");
+ Vertex vlan0 = graph.addVertex(T.label, "vlan", T.id, "13", "aai-node-type", "vlan",
+ "vlan-interface", "vlan31");
+ Vertex l3inter1ipv4addresslist0 = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "14", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-30");
+ Vertex l3inter1ipv6addresslist0 = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "15", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-30");
+
+ Vertex genericvnf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "10", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnfid10", "vnf-name", "vnf-name-11", "nf-type", "sample-nf-type11");
+ Vertex linterface1 =
+ graph.addVertex(T.label, "l-interface", T.id, "20", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id10", "l-interface-name", "l-interface-name10");
+ Vertex l3inter1ipv4addresslist1 = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "30", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-10");
+ Vertex l3inter1ipv6addresslist1 = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "40", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-10");
+ Vertex vlan1 = graph.addVertex(T.label, "vlan", T.id, "50", "aai-node-type", "vlan",
+ "vlan-interface", "vlan11");
+ Vertex vnfImage1 = graph.addVertex(T.label, "vnf-image", T.id, "60", "aai-node-type",
+ "vnf-image", "vnf-image-uuid", "vnf1imageuuid11");
+ Vertex networkProfile1 = graph.addVertex(T.label, "network-profile", T.id, "70",
+ "aai-node-type", "network-profile", "nm-profile-name", "nm-profile-name-11");
+ Vertex lagint1 = graph.addVertex(T.label, "lag-interface", T.id, "80", "aai-node-type",
+ "lag-interface", "interface-name", "lagint11");
+
+ Vertex lagint2 = graph.addVertex(T.label, "lag-interface", T.id, "21", "aai-node-type",
+ "lag-interface", "interface-name", "lagint312");
+ Vertex linterface2 =
+ graph.addVertex(T.label, "l-interface", T.id, "22", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id30", "l-interface-name", "l-interface-name302");
+ Vertex vlan2 = graph.addVertex(T.label, "vlan", T.id, "23", "aai-node-type", "vlan",
+ "vlan-interface", "vlan312");
+ Vertex l3inter1ipv4addresslist2 = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "24", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-302");
+ Vertex l3inter1ipv6addresslist2 = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "25", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-302");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addTreeEdge(g, genericvnf, linterface);
+ rules.addTreeEdge(g, l3inter1ipv4addresslist, linterface);
+ rules.addTreeEdge(g, l3inter1ipv6addresslist, linterface);
+ rules.addTreeEdge(g, linterface, vlan);
+ rules.addTreeEdge(g, l3inter1ipv4addresslist, vlan);
+ rules.addTreeEdge(g, l3inter1ipv6addresslist, vlan);
+
+ rules.addTreeEdge(g, genericvnf, lagint0);
+ rules.addTreeEdge(g, lagint0, linterface0);
+ rules.addTreeEdge(g, linterface0, vlan0);
+ rules.addTreeEdge(g, l3inter1ipv4addresslist0, linterface0);
+ rules.addTreeEdge(g, l3inter1ipv6addresslist0, linterface0);
+
+ rules.addEdge(g, genericvnf, vnfImage);
+ rules.addEdge(g, genericvnf, networkProfile);
+
+ // false
+ rules.addTreeEdge(g, genericvnf1, linterface1);
+ rules.addTreeEdge(g, l3inter1ipv4addresslist1, linterface1);
+ rules.addTreeEdge(g, l3inter1ipv6addresslist1, linterface1);
+ rules.addTreeEdge(g, linterface1, vlan1);
+ rules.addTreeEdge(g, l3inter1ipv4addresslist1, vlan1);
+ rules.addTreeEdge(g, l3inter1ipv6addresslist1, vlan1);
+
+ rules.addTreeEdge(g, genericvnf1, lagint2);
+ rules.addTreeEdge(g, linterface2, lagint2);
+ rules.addTreeEdge(g, linterface2, vlan2);
+ rules.addTreeEdge(g, l3inter1ipv4addresslist2, linterface2);
+ rules.addTreeEdge(g, l3inter1ipv6addresslist2, linterface2);
+
+ rules.addEdge(g, genericvnf1, vnfImage1);
+ rules.addEdge(g, genericvnf1, networkProfile1);
+
+ expectedResult.add(genericvnf);
+ expectedResult.add(l3inter1ipv4addresslist);
+ expectedResult.add(l3inter1ipv6addresslist);
+ expectedResult.add(vlan);
+ expectedResult.add(linterface0);
+ expectedResult.add(vnfImage);
+ expectedResult.add(networkProfile);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "gfp-vnf-data";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "generic-vnf").has("vnf-name", "vnf-name-1").has("vnf-id", "vnfid0");
+
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GenericVnfsFromPserverTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GenericVnfsFromPserverTest.java
index 4d42fce..80e9c51 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GenericVnfsFromPserverTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GenericVnfsFromPserverTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,78 +26,95 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class GenericVnfsFromPserverTest extends QueryTest {
- public GenericVnfsFromPserverTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public GenericVnfsFromPserverTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+
+ Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1", "vnf-type", "test",
+ "nf-function", "test", "nf-role", "test", "nf-naming-code", "test");
+ Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-2", "vnf-name", "vnf-name-2", "vnf-type", "test",
+ "nf-function", "test", "nf-role", "test", "nf-naming-code", "test");
+ Vertex vnf3 = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-3", "vnf-name", "vnf-name-3", "vnf-type", "test",
+ "nf-function", "test", "nf-role", "test", "nf-naming-code", "test");
+ Vertex vnf4 = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-4", "vnf-name", "vnf-name-4", "vnf-type", "test",
+ "nf-function", "test", "nf-role", "test", "nf-naming-code", "test");
+ Vertex badVnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-bad-1", "vnf-name", "vnf-bad-1", "vnf-type", "test");
+ Vertex badVnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "5", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-bad-2", "vnf-name", "vnf-bad-2", "nf-function", "test");
+ Vertex badVnf3 = graph.addVertex(T.label, "generic-vnf", T.id, "6", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-bad-3", "vnf-name", "vnf-bad-3", "vnf-type", "bad",
+ "nf-function", "bad");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
+ Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "8", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-2", "vserver-name", "vserver-name-2");
+ Vertex badVserver = graph.addVertex(T.label, "vserver", T.id, "9", "aai-node-type",
+ "vserver", "vserver-id", "vserver-bad", "vserver-name", "vserver-bad");
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "10", "aai-node-type",
+ "pserver", "hostname", "hostname-1", "fqdn", "fqdn");
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "11", "aai-node-type",
+ "pserver", "hostname", "hostname-2", "fqdn", "fqdn");
+ Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "12", "aai-node-type",
+ "pserver", "hostname", "hostname-3", "fqdn", "fqdn");
+ Vertex badPserver1 = graph.addVertex(T.label, "pserver", T.id, "13", "aai-node-type",
+ "pserver", "hostname", "hostname-bad-1", "fqdn", "fqdn");
+ Vertex badPserver2 = graph.addVertex(T.label, "pserver", T.id, "14", "aai-node-type",
+ "pserver", "hostname", "hostname-bad-2", "fqdn", "fqdn");
+ Vertex badPserver3 = graph.addVertex(T.label, "pserver", T.id, "15", "aai-node-type",
+ "pserver", "hostname", "hostname-bad-3", "fqdn", "fqdn");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, pserver1, vnf1);
+ rules.addEdge(g, pserver2, vserver1);
+ rules.addEdge(g, vserver1, vnf2);
+ rules.addEdge(g, pserver3, vnf3);
+ rules.addEdge(g, pserver3, vserver2);
+ rules.addEdge(g, vserver2, vnf4);
+ rules.addEdge(g, badPserver1, badVnf1);
+ rules.addEdge(g, badPserver2, badVserver);
+ rules.addEdge(g, badVserver, badVnf2);
+ rules.addEdge(g, badPserver3, badVnf3);
- @Test
- public void run() {
- super.run();
- }
+ expectedResult.add(vnf1);
+ expectedResult.add(vnf2);
+ expectedResult.add(vnf3);
+ expectedResult.add(vnf4);
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
+ @Override
+ protected String getQueryName() {
+ return "genericVnfs-fromPserver";
+ }
- Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1", "vnf-type", "test", "nf-function", "test"
- ,"nf-role", "test", "nf-naming-code", "test");
- Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-2", "vnf-name", "vnf-name-2", "vnf-type", "test", "nf-function", "test"
- ,"nf-role", "test", "nf-naming-code", "test");
- Vertex vnf3 = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-3", "vnf-name", "vnf-name-3", "vnf-type", "test", "nf-function", "test"
- ,"nf-role", "test", "nf-naming-code", "test");
- Vertex vnf4 = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-4", "vnf-name", "vnf-name-4", "vnf-type", "test", "nf-function", "test"
- ,"nf-role", "test", "nf-naming-code", "test");
- Vertex badVnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type", "generic-vnf", "vnf-id", "vnf-bad-1", "vnf-name", "vnf-bad-1", "vnf-type", "test");
- Vertex badVnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "5", "aai-node-type", "generic-vnf", "vnf-id", "vnf-bad-2", "vnf-name", "vnf-bad-2", "nf-function", "test");
- Vertex badVnf3 = graph.addVertex(T.label, "generic-vnf", T.id, "6", "aai-node-type", "generic-vnf", "vnf-id", "vnf-bad-3", "vnf-name", "vnf-bad-3", "vnf-type", "bad", "nf-function", "bad");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver", "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "8", "aai-node-type", "vserver", "vserver-id", "vserver-id-2", "vserver-name", "vserver-name-2");
- Vertex badVserver = graph.addVertex(T.label, "vserver", T.id, "9", "aai-node-type", "vserver", "vserver-id", "vserver-bad", "vserver-name", "vserver-bad");
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "10", "aai-node-type", "pserver", "hostname", "hostname-1", "fqdn", "fqdn");
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "11", "aai-node-type", "pserver", "hostname", "hostname-2", "fqdn", "fqdn");
- Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "12", "aai-node-type", "pserver", "hostname", "hostname-3", "fqdn", "fqdn");
- Vertex badPserver1 = graph.addVertex(T.label, "pserver", T.id, "13", "aai-node-type", "pserver", "hostname", "hostname-bad-1", "fqdn", "fqdn");
- Vertex badPserver2 = graph.addVertex(T.label, "pserver", T.id, "14", "aai-node-type", "pserver", "hostname", "hostname-bad-2", "fqdn", "fqdn");
- Vertex badPserver3 = graph.addVertex(T.label, "pserver", T.id, "15", "aai-node-type", "pserver", "hostname", "hostname-bad-3", "fqdn", "fqdn");
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "pserver").has("fqdn", "fqdn");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, pserver1, vnf1);
- rules.addEdge(g, pserver2, vserver1);
- rules.addEdge(g, vserver1, vnf2);
- rules.addEdge(g, pserver3, vnf3);
- rules.addEdge(g, pserver3, vserver2);
- rules.addEdge(g, vserver2, vnf4);
- rules.addEdge(g, badPserver1, badVnf1);
- rules.addEdge(g, badPserver2, badVserver);
- rules.addEdge(g, badVserver, badVnf2);
- rules.addEdge(g, badPserver3, badVnf3);
-
- expectedResult.add(vnf1);
- expectedResult.add(vnf2);
- expectedResult.add(vnf3);
- expectedResult.add(vnf4);
- }
+ }
- @Override
- protected String getQueryName() {
- return "genericVnfs-fromPserver";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "pserver").has("fqdn", "fqdn");
-
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("vnfType","test");
- params.put("nfFunction","test");
- params.put("nfRole","test");
- params.put("nfNamingCode", "test");
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("vnfType", "test");
+ params.put("nfFunction", "test");
+ params.put("nfRole", "test");
+ params.put("nfNamingCode", "test");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetClfiRoadmTailSummaryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetClfiRoadmTailSummaryTest.java
index 73f7595..5fde2db 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetClfiRoadmTailSummaryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetClfiRoadmTailSummaryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,11 @@
*/
package org.onap.aai.rest.search;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Map;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.T;
@@ -27,79 +32,89 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Map;
-
public class GetClfiRoadmTailSummaryTest extends TreeQueryTest {
- public GetClfiRoadmTailSummaryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public GetClfiRoadmTailSummaryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex logicalLink1 = graph.addVertex(T.label, "logical-link", T.id, "5", "aai-node-type", "logical-link", "link-name", "logical-link-1");
- Vertex pInterface1 = graph.addVertex(T.label, "p-interface", T.id, "6", "aai-node-type", "p-interface", "interface-name", "p-interface-1");
- Vertex pInterface2 = graph.addVertex(T.label, "p-interface", T.id, "7", "aai-node-type", "p-interface", "interface-name", "p-interface-2");
- Vertex pInterface3 = graph.addVertex(T.label, "p-interface", T.id, "8", "aai-node-type", "p-interface", "interface-name", "p-interface-3");
- Vertex pInterface4 = graph.addVertex(T.label, "p-interface", T.id, "9", "aai-node-type", "p-interface", "interface-name", "p-interface-4");
- Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "12", "aai-node-type", "pnf", "pnf-name", "pnf1name");
- Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "10", "aai-node-type", "pnf", "pnf-name", "pnf2name");
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex logicalLink1 = graph.addVertex(T.label, "logical-link", T.id, "5", "aai-node-type",
+ "logical-link", "link-name", "logical-link-1");
+ Vertex pInterface1 = graph.addVertex(T.label, "p-interface", T.id, "6", "aai-node-type",
+ "p-interface", "interface-name", "p-interface-1");
+ Vertex pInterface2 = graph.addVertex(T.label, "p-interface", T.id, "7", "aai-node-type",
+ "p-interface", "interface-name", "p-interface-2");
+ Vertex pInterface3 = graph.addVertex(T.label, "p-interface", T.id, "8", "aai-node-type",
+ "p-interface", "interface-name", "p-interface-3");
+ Vertex pInterface4 = graph.addVertex(T.label, "p-interface", T.id, "9", "aai-node-type",
+ "p-interface", "interface-name", "p-interface-4");
+ Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "12", "aai-node-type", "pnf",
+ "pnf-name", "pnf1name");
+ Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "10", "aai-node-type", "pnf",
+ "pnf-name", "pnf2name");
- Vertex lInterface1 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type", "l-interface", "interface-name", "l-interface-1");
+ Vertex lInterface1 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type",
+ "l-interface", "interface-name", "l-interface-1");
rules.addEdge(gts, logicalLink1, pInterface1);
rules.addEdge(gts, logicalLink1, pInterface2);
rules.addEdge(gts, logicalLink1, pInterface3);
- rules.addEdge(gts, logicalLink1, pInterface4);//false
+ rules.addEdge(gts, logicalLink1, pInterface4);// false
rules.addTreeEdge(gts, pnf1, pInterface1);
rules.addTreeEdge(gts, pnf2, pInterface2);
rules.addTreeEdge(gts, pnf2, pInterface3);
- rules.addEdge(gts, logicalLink1, lInterface1);//false
-
- }
-
- @Test
- public void run() {
- super.run();
- Tree tree = treeList.get(0);
-
- Vertex l1 = graph.traversal().V().has("aai-node-type","logical-link").has("link-name","logical-link-1").next();
- Vertex pInt1 = graph.traversal().V().has("aai-node-type","p-interface").has("interface-name","p-interface-1").next();
- Vertex pInt2 = graph.traversal().V().has("aai-node-type","p-interface").has("interface-name","p-interface-2").next();
- Vertex pInt3 = graph.traversal().V().has("aai-node-type","p-interface").has("interface-name","p-interface-3").next();
- Vertex pInt4 = graph.traversal().V().has("aai-node-type","p-interface").has("interface-name","p-interface-4").next();
- Vertex pnf1 = graph.traversal().V().has("aai-node-type","pnf").has("pnf-name","pnf1name").next();
- Vertex pnf2 = graph.traversal().V().has("aai-node-type","pnf").has("pnf-name","pnf2name").next();
-
- assertTrue(tree.containsKey(l1));
+ rules.addEdge(gts, logicalLink1, lInterface1);// false
+
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ Tree tree = treeList.get(0);
+
+ Vertex l1 = graph.traversal().V().has("aai-node-type", "logical-link")
+ .has("link-name", "logical-link-1").next();
+ Vertex pInt1 = graph.traversal().V().has("aai-node-type", "p-interface")
+ .has("interface-name", "p-interface-1").next();
+ Vertex pInt2 = graph.traversal().V().has("aai-node-type", "p-interface")
+ .has("interface-name", "p-interface-2").next();
+ Vertex pInt3 = graph.traversal().V().has("aai-node-type", "p-interface")
+ .has("interface-name", "p-interface-3").next();
+ Vertex pInt4 = graph.traversal().V().has("aai-node-type", "p-interface")
+ .has("interface-name", "p-interface-4").next();
+ Vertex pnf1 =
+ graph.traversal().V().has("aai-node-type", "pnf").has("pnf-name", "pnf1name").next();
+ Vertex pnf2 =
+ graph.traversal().V().has("aai-node-type", "pnf").has("pnf-name", "pnf2name").next();
+
+ assertTrue(tree.containsKey(l1));
assertTrue(((Tree) tree.get(l1)).containsKey(pInt1));
assertTrue(((Tree) tree.get(l1)).containsKey(pInt2));
assertTrue(((Tree) tree.get(l1)).containsKey(pInt3));
- assertFalse(((Tree) tree.get(l1)).containsKey(pInt4)); //pInt4 does not have an edge to any pnf
+ assertFalse(((Tree) tree.get(l1)).containsKey(pInt4)); // pInt4 does not have an edge to any
+ // pnf
assertTrue(((Tree) tree.get(l1)).getLeafObjects().contains(pnf1));
assertTrue(((Tree) tree.get(l1)).getLeafObjects().contains(pnf2));
-
- }
- @Override
- protected String getQueryName() {
- return "getClfiRoadmTailSummary";
- }
+ }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "logical-link").has("link-name", "logical-link-1");
- }
+ @Override
+ protected String getQueryName() {
+ return "getClfiRoadmTailSummary";
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "logical-link").has("link-name", "logical-link-1");
+ }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetComplexAndPserversTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetComplexAndPserversTest.java
index 5b17f32..b47b7a1 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetComplexAndPserversTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetComplexAndPserversTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,47 +30,53 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class GetComplexAndPserversTest extends QueryTest {
- public GetComplexAndPserversTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public GetComplexAndPserversTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "1", "aai-node-type", "complex", "complex-id", "complex-1");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "2", "aai-node-type", "pserver", "hostname", "pservername1");
-
- Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex", "complex-id", "complex-2");
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver", "hostname", "pservername2");
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addEdge(g, complex, pserver );
-
- //Not expected in result
- rules.addEdge(g, complex1, pserver1 );
- //Not expected in result
-
- expectedResult.add(complex);
- expectedResult.add(pserver);
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- @Override
- protected String getQueryName() {
- return "getComplexAndPservers";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "complex").has("complex-id", "complex-1");
-
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "1", "aai-node-type", "complex",
+ "complex-id", "complex-1");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "2", "aai-node-type", "pserver",
+ "hostname", "pservername1");
+
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex",
+ "complex-id", "complex-2");
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver",
+ "hostname", "pservername2");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addEdge(g, complex, pserver);
+
+ // Not expected in result
+ rules.addEdge(g, complex1, pserver1);
+ // Not expected in result
+
+ expectedResult.add(complex);
+ expectedResult.add(pserver);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "getComplexAndPservers";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "complex").has("complex-id", "complex-1");
+
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetComplexByPnfNameQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetComplexByPnfNameQueryTest.java
index 1d79466..733c382 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetComplexByPnfNameQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetComplexByPnfNameQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,8 @@
*/
package org.onap.aai.rest.search;
+import java.util.Map;
+
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.T;
@@ -27,49 +29,51 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-
public class GetComplexByPnfNameQueryTest extends QueryTest {
- public GetComplexByPnfNameQueryTest () throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public GetComplexByPnfNameQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "0", "aai-node-type", "pnf", "pnf-name",
+ "pnf1name", "equip-vendor", "equip-vendor1", "equip-model", "equip-model1");
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "1", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-1");
- // Set up the test graph
- Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "0", "aai-node-type", "pnf", "pnf-name", "pnf1name", "equip-vendor", "equip-vendor1", "equip-model","equip-model1");
- Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "1", "aai-node-type", "complex", "physical-location-id", "physical-location-id-1");
-
- // adding extra vertices and edges which shouldn't be picked.
- Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "2", "aai-node-type", "pnf", "pnf-name", "pnf2name", "equip-vendor", "equip-vendor2", "equip-model","equip-model2");
- Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex", "physical-location-id", "physical-location-id-2");
+ // adding extra vertices and edges which shouldn't be picked.
+ Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "2", "aai-node-type", "pnf", "pnf-name",
+ "pnf2name", "equip-vendor", "equip-vendor2", "equip-model", "equip-model2");
+ Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-2");
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, pnf1, complex1);
- rules.addEdge(g, pnf2, complex2);
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, pnf1, complex1);
+ rules.addEdge(g, pnf2, complex2);
- expectedResult.add(pnf1);
- expectedResult.add(complex1);
- }
+ expectedResult.add(pnf1);
+ expectedResult.add(complex1);
+ }
- @Override
- protected String getQueryName() {
- return "getComplexByPnfName";
- }
+ @Override
+ protected String getQueryName() {
+ return "getComplexByPnfName";
+ }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "pnf").has("pnf-name", "pnf1name");
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "pnf").has("pnf-name", "pnf1name");
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetComplexFromHostnameQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetComplexFromHostnameQueryTest.java
index 694b1c5..fe8a162 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetComplexFromHostnameQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetComplexFromHostnameQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,11 @@
*/
package org.onap.aai.rest.search;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Map;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.T;
@@ -27,51 +32,52 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
public class GetComplexFromHostnameQueryTest extends TreeQueryTest {
- public GetComplexFromHostnameQueryTest () throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public GetComplexFromHostnameQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @SuppressWarnings("rawtypes")
- @Test
- public void run() {
- super.run();
- Tree tree = treeList.get(0);
- Vertex pserver1 = graph.traversal().V().has("aai-node-type","pserver").has("hostname","pserver-name-1").next();
- Vertex pserver2 = graph.traversal().V().has("aai-node-type","pserver").has("hostname","pserver-name-2").next();
- Vertex complex1 = graph.traversal().V().has("aai-node-type", "complex").has( "physical-location-id", "physical-location-id-1").next();
+ @SuppressWarnings("rawtypes")
+ @Test
+ public void run() {
+ super.run();
+ Tree tree = treeList.get(0);
+ Vertex pserver1 = graph.traversal().V().has("aai-node-type", "pserver")
+ .has("hostname", "pserver-name-1").next();
+ Vertex pserver2 = graph.traversal().V().has("aai-node-type", "pserver")
+ .has("hostname", "pserver-name-2").next();
+ Vertex complex1 = graph.traversal().V().has("aai-node-type", "complex")
+ .has("physical-location-id", "physical-location-id-1").next();
assertTrue(tree.containsKey(pserver1));
assertTrue(((Tree) tree.get(pserver1)).containsKey(complex1));
assertFalse(tree.containsKey(pserver2));
- }
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- // Set up the test graph
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "0", "aai-node-type", "pserver", "hostname", "pserver-name-1");
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver", "hostname", "pserver-name-2");
- Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "1", "aai-node-type", "complex", "physical-location-id", "physical-location-id-1");
- rules.addEdge(gts, pserver1, complex1);
- rules.addEdge(gts, pserver2, complex1);
- }
+ // Set up the test graph
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "0", "aai-node-type", "pserver",
+ "hostname", "pserver-name-1");
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver",
+ "hostname", "pserver-name-2");
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "1", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-1");
+ rules.addEdge(gts, pserver1, complex1);
+ rules.addEdge(gts, pserver2, complex1);
+ }
- @Override
- protected String getQueryName() {
- return "getComplexFromHostname";
- }
+ @Override
+ protected String getQueryName() {
+ return "getComplexFromHostname";
+ }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "pserver").has("hostname", "pserver-name-1");
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "pserver").has("hostname", "pserver-name-1");
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetCustomQueryConfigTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetCustomQueryConfigTest.java
index 864b14b..3ab960f 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetCustomQueryConfigTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetCustomQueryConfigTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -21,63 +21,61 @@ package org.onap.aai.rest.search;
import static org.junit.Assert.*;
+import com.google.common.collect.Lists;
+
import java.util.ArrayList;
import org.junit.Before;
import org.junit.Test;
-import com.google.common.collect.Lists;
-
public class GetCustomQueryConfigTest {
- private String configJson;
-
- @Before
- public void setUp() throws Exception {
- System.setProperty("AJSC_HOME", ".");
- System.setProperty("BUNDLECONFIG_DIR", "src/main/resources");
-
+ private String configJson;
+
+ @Before
+ public void setUp() throws Exception {
+ System.setProperty("AJSC_HOME", ".");
+ System.setProperty("BUNDLECONFIG_DIR", "src/main/resources");
+
+ configJson = "{\n \"stored-queries\": [{\n"
+ + " \"queryName1\": {\n \"query\": {\n \"required-properties\": [\"prop1\", \"prop2\"],\n \"optional-properties\": [\"prop3\", \"prop4\"]\n },\n \"stored-query\": \"out('blah').has('something','foo')\"\n }\n }, {\n"
+ + " \"queryName2\": {\n \"query\": {\n \"optional-properties\": [\"prop5\"]\n },\n \"stored-query\": \"out('bar').has('stuff','baz')\"\n }\n }, {\n"
+ + " \"queryName3\": {\n \"stored-query\": \"out('bar1').has('stuff','baz1')\"\n }\n }]\n}";
+ }
+
+ @Test
+ public void testGetStoredQueryNameWithOptAndReqProps() {
- configJson = "{\n \"stored-queries\": [{\n" +
- " \"queryName1\": {\n \"query\": {\n \"required-properties\": [\"prop1\", \"prop2\"],\n \"optional-properties\": [\"prop3\", \"prop4\"]\n },\n \"stored-query\": \"out('blah').has('something','foo')\"\n }\n }, {\n" +
- " \"queryName2\": {\n \"query\": {\n \"optional-properties\": [\"prop5\"]\n },\n \"stored-query\": \"out('bar').has('stuff','baz')\"\n }\n }, {\n" +
- " \"queryName3\": {\n \"stored-query\": \"out('bar1').has('stuff','baz1')\"\n }\n }]\n}";
- }
+ GetCustomQueryConfig getCustomQueryConfig = new GetCustomQueryConfig(configJson);
+ CustomQueryConfig cqc = getCustomQueryConfig.getStoredQuery("queryName1");
+ assertEquals(Lists.newArrayList("prop3", "prop4"), cqc.getQueryOptionalProperties());
+ assertEquals(Lists.newArrayList("prop1", "prop2"), cqc.getQueryRequiredProperties());
+ assertEquals("out('blah').has('something','foo')", cqc.getQuery());
- @Test
- public void testGetStoredQueryNameWithOptAndReqProps() {
-
- GetCustomQueryConfig getCustomQueryConfig = new GetCustomQueryConfig(configJson);
- CustomQueryConfig cqc = getCustomQueryConfig.getStoredQuery("queryName1");
+ }
- assertEquals(Lists.newArrayList("prop3", "prop4"), cqc.getQueryOptionalProperties());
- assertEquals(Lists.newArrayList("prop1", "prop2"), cqc.getQueryRequiredProperties());
- assertEquals("out('blah').has('something','foo')", cqc.getQuery());
+ @Test
+ public void testGetStoredQueryNameWithOptProps() {
- }
+ GetCustomQueryConfig getCustomQueryConfig = new GetCustomQueryConfig(configJson);
+ CustomQueryConfig cqc = getCustomQueryConfig.getStoredQuery("queryName2");
- @Test
- public void testGetStoredQueryNameWithOptProps() {
-
- GetCustomQueryConfig getCustomQueryConfig = new GetCustomQueryConfig(configJson);
- CustomQueryConfig cqc = getCustomQueryConfig.getStoredQuery("queryName2");
+ assertEquals(Lists.newArrayList("prop5"), cqc.getQueryOptionalProperties());
+ assertEquals(new ArrayList<String>(), cqc.getQueryRequiredProperties());
+ assertEquals("out('bar').has('stuff','baz')", cqc.getQuery());
- assertEquals(Lists.newArrayList("prop5"), cqc.getQueryOptionalProperties());
- assertEquals(new ArrayList<String>(), cqc.getQueryRequiredProperties());
- assertEquals("out('bar').has('stuff','baz')", cqc.getQuery());
+ }
- }
+ @Test
+ public void testGetStoredQueryNameWithNoProps() {
- @Test
- public void testGetStoredQueryNameWithNoProps() {
-
- GetCustomQueryConfig getCustomQueryConfig = new GetCustomQueryConfig(configJson);
- CustomQueryConfig cqc = getCustomQueryConfig.getStoredQuery("queryName3");
+ GetCustomQueryConfig getCustomQueryConfig = new GetCustomQueryConfig(configJson);
+ CustomQueryConfig cqc = getCustomQueryConfig.getStoredQuery("queryName3");
- assertEquals(new ArrayList<String>(), cqc.getQueryOptionalProperties());
- assertEquals(new ArrayList<String>(), cqc.getQueryRequiredProperties());
- assertEquals("out('bar1').has('stuff','baz1')", cqc.getQuery());
+ assertEquals(new ArrayList<String>(), cqc.getQueryOptionalProperties());
+ assertEquals(new ArrayList<String>(), cqc.getQueryRequiredProperties());
+ assertEquals("out('bar1').has('stuff','baz1')", cqc.getQuery());
- }
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetCustomerVPNBondingServiceDetailsTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetCustomerVPNBondingServiceDetailsTest.java
index d080016..bdd47f8 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetCustomerVPNBondingServiceDetailsTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetCustomerVPNBondingServiceDetailsTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -33,70 +33,80 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class GetCustomerVPNBondingServiceDetailsTest extends QueryTest {
- public GetCustomerVPNBondingServiceDetailsTest() throws AAIException, NoEdgeRuleFoundException {
- super();
+ public GetCustomerVPNBondingServiceDetailsTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
}
@Test
public void test() {
- super.run();
+ super.run();
}
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
-
- Vertex serviceSubscription = graph.addVertex(T.label, "service-subscription", T.id, "1", "aai-node-type", "service-subscription",
- "service-type", "start-test");
- Vertex customer = graph.addVertex(T.label, "customer", T.id, "2", "aai-node-type", "customer",
- "global-customer-id", "customer-test", "subscriber-name", "test-name", "subscriber-type", "test-type");
- Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "3", "aai-node-type", "service-instance",
- "service-instance-id", "test-instance");
- Vertex configurationOne = graph.addVertex(T.label, "configuration", T.id, "4", "aai-node-type", "configuration",
- "configuration-id", "test-config-1", "configuration-type", "VLAN-NETWORK-RECEPTOR");
- Vertex configurationTwo = graph.addVertex(T.label, "configuration", T.id, "5", "aai-node-type", "configuration",
- "configuration-id", "test-config-2", "configuration-type", "VLAN-NETWORK-RECEPTOR");
- Vertex badConfiguration = graph.addVertex(T.label, "configuration", T.id, "6", "aai-node-type", "configuration",
- "configuration-id", "bad-config", "configuration-type", "bad");
- Vertex genericVnfOne = graph.addVertex(T.label, "generic-vnf", T.id, "7", "aai-node-type", "generic-vnf",
- "vnf-id", "test-generic-vnf-1", "vnf-type", "right-relationship");
- Vertex genericVnfTwo = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type", "generic-vnf",
- "vnf-id", "test-generic-vnf-2", "vnf-type", "wrong-relationship");
- Vertex rightInstanceGroup = graph.addVertex(T.label, "instance-group", T.id, "9", "aai-node-type", "instance-group",
- "id", "test-group-right", "description", "MemberOf relationship", "instance-group-type", "lower case ha for high availability");
- Vertex wrongInstanceGroup = graph.addVertex(T.label, "instance-group", T.id, "10", "aai-node-type", "instance-group",
- "id", "test-group-wrong", "description", "Uses relationship", "instance-group-type", "lower case ha for high availability");
- Vertex l3Network = graph.addVertex(T.label, "l3-network", T.id, "11", "aai-node-type", "l3-network",
- "network-id", "test-l3");
- Vertex subnet = graph.addVertex(T.label, "subnet", T.id, "12", "aai-node-type", "subnet",
- "subnet-id", "test-subnet");
- Vertex l3InterfaceIpv6AddressList = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "13", "aai-node-type", "l3-interface-ipv6-address-list",
- "l3-interface-ipv6-address", "test-ipv6");
- Vertex l3InterfaceIpv4AddressList = graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "14", "aai-node-type", "l3-interface-ipv4-address-list",
- "l3-interface-ipv4-address", "test-ipv4");
- Vertex l3VpnBinding = graph.addVertex(T.label, "vpn-binding", T.id, "15", "aai-node-type", "vpn-binding",
- "vpn-id", "test-binding", "vpn-name", "test");
- Vertex l3RouteTarget = graph.addVertex(T.label, "route-target", T.id, "16", "aai-node-type", "route-target",
- "global-route-target", "test-target", "route-target-role", "test");
- Vertex parentLInterface = graph.addVertex(T.label, "l-interface", T.id, "17", "aai-node-type", "l-interface",
- "interface-name", "parent-test-l-interface");
- Vertex vlan = graph.addVertex(T.label, "vlan", T.id, "18", "aai-node-type", "vlan",
- "vlan-interface", "test-vlan");
- Vertex childLInterface = graph.addVertex(T.label, "l-interface", T.id, "19", "aai-node-type", "l-interface",
- "interface-name", "child-test-l-interface");
- Vertex configurationThree = graph.addVertex(T.label, "configuration", T.id, "20", "aai-node-type", "configuration",
- "configuration-id", "test-config-3", "configuration-type", "VRF ENTRY");
- Vertex configVpnBinding = graph.addVertex(T.label, "vpn-binding", T.id, "21", "aai-node-type", "vpn-binding",
- "vpn-id", "test-binding-config", "vpn-name", "test");
- Vertex configRouteTarget = graph.addVertex(T.label, "route-target", T.id, "22", "aai-node-type", "route-target",
- "global-route-target", "test-target-config", "route-target-role", "test");
- Vertex pnf = graph.addVertex(T.label, "pnf", T.id, "23", "aai-node-type", "pnf",
- "pnf-name", "test-pnf", "nf-role", "D2IPE");
- Vertex badPnf = graph.addVertex(T.label, "pnf", T.id, "24", "aai-node-type", "pnf",
- "pnf-name", "test-pnf", "nf-role", "none");
-
+ // Set up the test graph
+
+ Vertex serviceSubscription = graph.addVertex(T.label, "service-subscription", T.id, "1",
+ "aai-node-type", "service-subscription", "service-type", "start-test");
+ Vertex customer = graph.addVertex(T.label, "customer", T.id, "2", "aai-node-type",
+ "customer", "global-customer-id", "customer-test", "subscriber-name", "test-name",
+ "subscriber-type", "test-type");
+ Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "3",
+ "aai-node-type", "service-instance", "service-instance-id", "test-instance");
+ Vertex configurationOne =
+ graph.addVertex(T.label, "configuration", T.id, "4", "aai-node-type", "configuration",
+ "configuration-id", "test-config-1", "configuration-type", "VLAN-NETWORK-RECEPTOR");
+ Vertex configurationTwo =
+ graph.addVertex(T.label, "configuration", T.id, "5", "aai-node-type", "configuration",
+ "configuration-id", "test-config-2", "configuration-type", "VLAN-NETWORK-RECEPTOR");
+ Vertex badConfiguration =
+ graph.addVertex(T.label, "configuration", T.id, "6", "aai-node-type", "configuration",
+ "configuration-id", "bad-config", "configuration-type", "bad");
+ Vertex genericVnfOne = graph.addVertex(T.label, "generic-vnf", T.id, "7", "aai-node-type",
+ "generic-vnf", "vnf-id", "test-generic-vnf-1", "vnf-type", "right-relationship");
+ Vertex genericVnfTwo = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type",
+ "generic-vnf", "vnf-id", "test-generic-vnf-2", "vnf-type", "wrong-relationship");
+ Vertex rightInstanceGroup = graph.addVertex(T.label, "instance-group", T.id, "9",
+ "aai-node-type", "instance-group", "id", "test-group-right", "description",
+ "MemberOf relationship", "instance-group-type", "lower case ha for high availability");
+ Vertex wrongInstanceGroup = graph.addVertex(T.label, "instance-group", T.id, "10",
+ "aai-node-type", "instance-group", "id", "test-group-wrong", "description",
+ "Uses relationship", "instance-group-type", "lower case ha for high availability");
+ Vertex l3Network = graph.addVertex(T.label, "l3-network", T.id, "11", "aai-node-type",
+ "l3-network", "network-id", "test-l3");
+ Vertex subnet = graph.addVertex(T.label, "subnet", T.id, "12", "aai-node-type", "subnet",
+ "subnet-id", "test-subnet");
+ Vertex l3InterfaceIpv6AddressList =
+ graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "13", "aai-node-type",
+ "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test-ipv6");
+ Vertex l3InterfaceIpv4AddressList =
+ graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "14", "aai-node-type",
+ "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test-ipv4");
+ Vertex l3VpnBinding = graph.addVertex(T.label, "vpn-binding", T.id, "15", "aai-node-type",
+ "vpn-binding", "vpn-id", "test-binding", "vpn-name", "test");
+ Vertex l3RouteTarget = graph.addVertex(T.label, "route-target", T.id, "16", "aai-node-type",
+ "route-target", "global-route-target", "test-target", "route-target-role", "test");
+ Vertex parentLInterface = graph.addVertex(T.label, "l-interface", T.id, "17",
+ "aai-node-type", "l-interface", "interface-name", "parent-test-l-interface");
+ Vertex vlan = graph.addVertex(T.label, "vlan", T.id, "18", "aai-node-type", "vlan",
+ "vlan-interface", "test-vlan");
+ Vertex childLInterface = graph.addVertex(T.label, "l-interface", T.id, "19",
+ "aai-node-type", "l-interface", "interface-name", "child-test-l-interface");
+ Vertex configurationThree =
+ graph.addVertex(T.label, "configuration", T.id, "20", "aai-node-type", "configuration",
+ "configuration-id", "test-config-3", "configuration-type", "VRF ENTRY");
+ Vertex configVpnBinding = graph.addVertex(T.label, "vpn-binding", T.id, "21",
+ "aai-node-type", "vpn-binding", "vpn-id", "test-binding-config", "vpn-name", "test");
+ Vertex configRouteTarget =
+ graph.addVertex(T.label, "route-target", T.id, "22", "aai-node-type", "route-target",
+ "global-route-target", "test-target-config", "route-target-role", "test");
+ Vertex pnf = graph.addVertex(T.label, "pnf", T.id, "23", "aai-node-type", "pnf", "pnf-name",
+ "test-pnf", "nf-role", "D2IPE");
+ Vertex badPnf = graph.addVertex(T.label, "pnf", T.id, "24", "aai-node-type", "pnf",
+ "pnf-name", "test-pnf", "nf-role", "none");
+
GraphTraversalSource g = graph.traversal();
-
+
rules.addTreeEdge(g, customer, serviceSubscription);
rules.addTreeEdge(g, serviceSubscription, serviceInstance);
rules.addEdge(g, serviceInstance, configurationOne);
@@ -104,8 +114,10 @@ public class GetCustomerVPNBondingServiceDetailsTest extends QueryTest {
rules.addEdge(g, serviceInstance, badConfiguration);
rules.addEdge(g, configurationOne, genericVnfOne);
rules.addEdge(g, configurationTwo, genericVnfTwo);
- rules.addEdge(g, genericVnfOne, rightInstanceGroup, "org.onap.relationships.inventory.MemberOf");
- rules.addEdge(g, genericVnfTwo, wrongInstanceGroup, "org.onap.relationships.inventory.Uses");
+ rules.addEdge(g, genericVnfOne, rightInstanceGroup,
+ "org.onap.relationships.inventory.MemberOf");
+ rules.addEdge(g, genericVnfTwo, wrongInstanceGroup,
+ "org.onap.relationships.inventory.Uses");
rules.addEdge(g, configurationOne, l3Network);
rules.addTreeEdge(g, l3Network, subnet);
rules.addEdge(g, subnet, l3InterfaceIpv6AddressList);
@@ -120,7 +132,7 @@ public class GetCustomerVPNBondingServiceDetailsTest extends QueryTest {
rules.addTreeEdge(g, configVpnBinding, configRouteTarget);
rules.addEdge(g, configurationThree, pnf);
rules.addEdge(g, configurationThree, badPnf);
-
+
expectedResult.add(customer);
expectedResult.add(serviceInstance);
expectedResult.add(configurationOne);
@@ -145,17 +157,17 @@ public class GetCustomerVPNBondingServiceDetailsTest extends QueryTest {
@Override
protected String getQueryName() {
- return "getCustomerVPNBondingServiceDetails";
+ return "getCustomerVPNBondingServiceDetails";
}
@Override
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "service-subscription").has("service-type", "start-test");
+ g.has("aai-node-type", "service-subscription").has("service-type", "start-test");
}
@Override
protected void addParam(Map<String, Object> params) {
- return;
+ return;
}
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetDHVLogicalLinkTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetDHVLogicalLinkTest.java
index 6659d20..7ed3d34 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetDHVLogicalLinkTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetDHVLogicalLinkTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,8 @@
*/
package org.onap.aai.rest.search;
+import static org.junit.Assert.*;
+
import java.util.Map;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
@@ -30,8 +32,6 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import static org.junit.Assert.*;
-
public class GetDHVLogicalLinkTest extends TreeQueryTest {
public GetDHVLogicalLinkTest() throws AAIException, NoEdgeRuleFoundException {
super();
@@ -42,58 +42,69 @@ public class GetDHVLogicalLinkTest extends TreeQueryTest {
super.run();
Tree tree = treeList.get(0);
- Vertex gvnf1 = graph.traversal().V().has("aai-node-type", "generic-vnf").has("vnfname", "vnfname1").next();
- Vertex linterface1 = graph.traversal().V().has("aai-node-type", "l-interface").has("network-name", "networkName1").next();
- Vertex vlan1 = graph.traversal().V().has("aai-node-type", "vlan").has("vlan-interface", "vlan-interface1").next();
- Vertex logicalLink1 = graph.traversal().V().has("aai-node-type", "logical-link").has("link-type", "linkType1").next();
-
- Vertex gvnf2 = graph.traversal().V().has("aai-node-type", "generic-vnf").has("vnfname", "vnfname2").next();
+ Vertex gvnf1 = graph.traversal().V().has("aai-node-type", "generic-vnf")
+ .has("vnfname", "vnfname1").next();
+ Vertex linterface1 = graph.traversal().V().has("aai-node-type", "l-interface")
+ .has("network-name", "networkName1").next();
+ Vertex vlan1 = graph.traversal().V().has("aai-node-type", "vlan")
+ .has("vlan-interface", "vlan-interface1").next();
+ Vertex logicalLink1 = graph.traversal().V().has("aai-node-type", "logical-link")
+ .has("link-type", "linkType1").next();
+
+ Vertex gvnf2 = graph.traversal().V().has("aai-node-type", "generic-vnf")
+ .has("vnfname", "vnfname2").next();
assertTrue(tree.containsKey(gvnf1));
assertTrue(((Tree) tree.get(gvnf1)).containsKey(linterface1));
- assertTrue(((Tree)(((Tree) tree.get(gvnf1)).get(linterface1))).containsKey(vlan1));
- assertTrue(((Tree)((Tree)(((Tree) tree.get(gvnf1)).get(linterface1))).get(vlan1)).containsKey(logicalLink1));
+ assertTrue(((Tree) (((Tree) tree.get(gvnf1)).get(linterface1))).containsKey(vlan1));
+ assertTrue(((Tree) ((Tree) (((Tree) tree.get(gvnf1)).get(linterface1))).get(vlan1))
+ .containsKey(logicalLink1));
assertFalse(tree.containsKey(gvnf2));
}
+
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type",
+ "generic-vnf", "vnfname", "vnfname1", "vnf-name", "vnfname1", "vnf-type", "vnftype1");
- //Set up the test graph
- Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf", "vnfname", "vnfname1", "vnf-name", "vnfname1", "vnf-type", "vnftype1");
-
+ Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "1", "aai-node-type",
+ "l-interface", "l-interface-id", "l-interface-id0", "l-interface-name",
+ "l-interface-name1", "network-name", "networkName1");
- Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "1", "aai-node-type", "l-interface",
- "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name1","network-name","networkName1");
+ Vertex vlan1 = graph.addVertex(T.label, "vlan", T.id, "2", "aai-node-type", "vlan",
+ "vlan-interface", "vlan-interface1");
- Vertex vlan1 = graph.addVertex(T.label, "vlan", T.id, "2", "aai-node-type", "vlan", "vlan-interface", "vlan-interface1");
+ Vertex logicalLink1 =
+ graph.addVertex(T.label, "logical-link", T.id, "3", "aai-node-type", "logical-link",
+ "link-name", "linkName1", "in-maint", "false", "link-type", "linkType1");
- Vertex logicalLink1 = graph.addVertex(T.label, "logical-link", T.id, "3", "aai-node-type", "logical-link",
- "link-name", "linkName1", "in-maint", "false", "link-type","linkType1");
+ // Set up the test graph for false test cases
+ Vertex gvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type",
+ "generic-vnf", "vnfname", "vnfname2", "vnf-name", "vnfname2", "vnf-type", "vnftype2");
- //Set up the test graph for false test cases
- Vertex gvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type", "generic-vnf", "vnfname", "vnfname2", "vnf-name", "vnfname2", "vnf-type", "vnftype2");
+ Vertex linterface2 = graph.addVertex(T.label, "l-interface", T.id, "5", "aai-node-type",
+ "l-interface", "l-interface-id", "l-interface-id2", "l-interface-name",
+ "l-interface-name2", "network-name", "networkName2");
+ Vertex vlan2 = graph.addVertex(T.label, "vlan", T.id, "6", "aai-node-type", "vlan",
+ "vlan-interface", "vlan-interface2");
- Vertex linterface2 = graph.addVertex(T.label, "l-interface", T.id, "5", "aai-node-type", "l-interface",
- "l-interface-id", "l-interface-id2", "l-interface-name", "l-interface-name2","network-name","networkName2");
+ Vertex logicalLink2 =
+ graph.addVertex(T.label, "logical-link", T.id, "7", "aai-node-type", "logical-link",
+ "link-name", "linkName2", "in-maint", "false", "link-type", "linkType2");
- Vertex vlan2 = graph.addVertex(T.label, "vlan", T.id, "6", "aai-node-type", "vlan", "vlan-interface", "vlan-interface2");
+ // GraphTraversalSource g = graph.traversal();
- Vertex logicalLink2 = graph.addVertex(T.label, "logical-link", T.id, "7", "aai-node-type", "logical-link",
- "link-name", "linkName2", "in-maint", "false", "link-type","linkType2");
+ rules.addTreeEdge(gts, gvnf1, linterface1); // true
+ rules.addTreeEdge(gts, linterface1, vlan1); // true
+ rules.addEdge(gts, vlan1, logicalLink1); // true
-
- //GraphTraversalSource g = graph.traversal();
-
- rules.addTreeEdge(gts, gvnf1, linterface1); // true
- rules.addTreeEdge(gts, linterface1, vlan1); // true
- rules.addEdge(gts, vlan1, logicalLink1); // true
-
- rules.addTreeEdge(gts, gvnf2, linterface2); // false
- rules.addTreeEdge(gts, linterface2, vlan2); // false
- rules.addEdge(gts, vlan2, logicalLink2); // false
+ rules.addTreeEdge(gts, gvnf2, linterface2); // false
+ rules.addTreeEdge(gts, linterface2, vlan2); // false
+ rules.addEdge(gts, vlan2, logicalLink2); // false
expectedResult.add(gvnf1);
expectedResult.add(linterface1);
@@ -101,13 +112,16 @@ public class GetDHVLogicalLinkTest extends TreeQueryTest {
expectedResult.add(logicalLink1);
}
+
@Override
protected String getQueryName() {
return "getDHVLogicalLink";
}
+
@Override
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "generic-vnf").has("vnfname", "vnfname1"); }
+ g.has("aai-node-type", "generic-vnf").has("vnfname", "vnfname1");
+ }
@Override
protected void addParam(Map<String, Object> params) {
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetL3networkCloudRegionByNetworkRoleQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetL3networkCloudRegionByNetworkRoleQueryTest.java
index a9fedcd..d059a9c 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetL3networkCloudRegionByNetworkRoleQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetL3networkCloudRegionByNetworkRoleQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,8 @@
*/
package org.onap.aai.rest.search;
+import java.util.Map;
+
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.T;
@@ -27,10 +29,9 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-
public class GetL3networkCloudRegionByNetworkRoleQueryTest extends QueryTest {
- public GetL3networkCloudRegionByNetworkRoleQueryTest () throws AAIException, NoEdgeRuleFoundException {
+ public GetL3networkCloudRegionByNetworkRoleQueryTest()
+ throws AAIException, NoEdgeRuleFoundException {
super();
}
@@ -43,18 +44,32 @@ public class GetL3networkCloudRegionByNetworkRoleQueryTest extends QueryTest {
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
// Set up the test graph
- Vertex l3Network1 = graph.addVertex(T.label, "l3-network", T.id, "0", "aai-node-type", "l3-network", "network-id", "networkId1", "network-name", "networkName1", "network-role","networkRole1");
- Vertex genericVnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf", "vnf-id", "vnfId1", "vnf-name", "vnfName1", "vnf-type", "vnfType1");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "2", "aai-node-type", "vserver", "vserver-id", "vserverId1", "vserver-name", "vserverName1", "vserver-selflink", "vserverSelfLink1");
- Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "3", "aai-node-type", "tenant", "tenant-id", "tenantId1", "tenant-name" ,"tenantName1");
- Vertex cloudRegion1 = graph.addVertex(T.label, "cloud-region", T.id, "4", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner1", "cloud-region-id", "cloudRegionId1");
+ Vertex l3Network1 = graph.addVertex(T.label, "l3-network", T.id, "0", "aai-node-type",
+ "l3-network", "network-id", "networkId1", "network-name", "networkName1",
+ "network-role", "networkRole1");
+ Vertex genericVnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfId1", "vnf-name", "vnfName1", "vnf-type", "vnfType1");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "2", "aai-node-type", "vserver",
+ "vserver-id", "vserverId1", "vserver-name", "vserverName1", "vserver-selflink",
+ "vserverSelfLink1");
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "3", "aai-node-type", "tenant",
+ "tenant-id", "tenantId1", "tenant-name", "tenantName1");
+ Vertex cloudRegion1 = graph.addVertex(T.label, "cloud-region", T.id, "4", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloudOwner1", "cloud-region-id", "cloudRegionId1");
// adding extra vertices and edges which shouldn't be picked.
- Vertex l3Network2 = graph.addVertex(T.label, "l3-network", T.id, "5", "aai-node-type", "l3-network", "network-id", "networkId2", "network-name", "networkName2", "network-role","networkRole2");
- Vertex genericVnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "6", "aai-node-type", "generic-vnf", "vnf-id", "vnfId2", "vnf-name", "vnfName2", "vnf-type", "vnfType2");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver", "vserver-id", "vserverId2", "vserver-name", "vserverName2", "vserver-selflink", "vserverSelfLink2");
- Vertex tenant2 = graph.addVertex(T.label, "tenant", T.id, "8", "aai-node-type", "tenant", "tenant-id", "tenantId2", "tenant-name" ,"tenantName2");
- Vertex cloudRegion2 = graph.addVertex(T.label, "cloud-region", T.id, "9", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner2", "cloud-region-id", "cloudRegionId2");
+ Vertex l3Network2 = graph.addVertex(T.label, "l3-network", T.id, "5", "aai-node-type",
+ "l3-network", "network-id", "networkId2", "network-name", "networkName2",
+ "network-role", "networkRole2");
+ Vertex genericVnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "6", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfId2", "vnf-name", "vnfName2", "vnf-type", "vnfType2");
+ Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver",
+ "vserver-id", "vserverId2", "vserver-name", "vserverName2", "vserver-selflink",
+ "vserverSelfLink2");
+ Vertex tenant2 = graph.addVertex(T.label, "tenant", T.id, "8", "aai-node-type", "tenant",
+ "tenant-id", "tenantId2", "tenant-name", "tenantName2");
+ Vertex cloudRegion2 = graph.addVertex(T.label, "cloud-region", T.id, "9", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloudOwner2", "cloud-region-id", "cloudRegionId2");
GraphTraversalSource g = graph.traversal();
rules.addEdge(g, l3Network1, genericVnf1);
@@ -81,7 +96,8 @@ public class GetL3networkCloudRegionByNetworkRoleQueryTest extends QueryTest {
@Override
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "l3-network").has("network-id", "networkId1").has("network-role", "networkRole1");
+ g.has("aai-node-type", "l3-network").has("network-id", "networkId1").has("network-role",
+ "networkRole1");
}
@Override
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetLinterfaceFromNewvceTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetLinterfaceFromNewvceTest.java
index fbb77b8..1becf6c 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetLinterfaceFromNewvceTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetLinterfaceFromNewvceTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,8 @@
*/
package org.onap.aai.rest.search;
+import java.util.Map;
+
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.T;
@@ -27,10 +29,8 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-
public class GetLinterfaceFromNewvceTest extends QueryTest {
- public GetLinterfaceFromNewvceTest () throws AAIException, NoEdgeRuleFoundException {
+ public GetLinterfaceFromNewvceTest() throws AAIException, NoEdgeRuleFoundException {
super();
}
@@ -43,64 +43,81 @@ public class GetLinterfaceFromNewvceTest extends QueryTest {
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
// Set up the test graph
- Vertex newvce = graph.addVertex(T.label, "newvce", T.id, "0", "aai-node-type", "newvce", "vnf-id2", "vnfId2-1", "vnf-name", "vnfName-1", "vnf-type", "vnfType-1");
- Vertex linterfaceNewvce1 = graph.addVertex(T.label, "l-interface", T.id, "1", "aai-node-type", "l-interface", "l-interface-id", "lInterfaceId-10",
- "l-interface-name", "lInterfaceName-1", "interface-role", "UPLINK");
- Vertex linterfaceNewvce2 = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type", "l-interface", "l-interface-id", "lInterfaceId-20",
- "l-interface-name", "lInterfaceName-1", "interface-role", "CUSTOMER");
- Vertex linterfaceNewvce3 = graph.addVertex(T.label, "l-interface", T.id, "3", "aai-node-type", "l-interface", "l-interface-id", "lInterfaceId-30",
- "l-interface-name", "lInterfaceName-3", "interface-role", "CUSTOMER-UPLINK");
-
- Vertex logicalLink1 = graph.addVertex(T.label, "logical-link", T.id, "4", "aai-node-type", "logical-link", "link-name", "linkName-1", "in-maint", "false", "link-type","linkType-1");
-
- // 1 generic-vnf with 2 lags each has 1 linterface
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "5", "aai-node-type", "generic-vnf", "vnf-id", "vnfId-1","vnf-name", "vnfName-1");
- Vertex lagint1 = graph.addVertex(T.label, "lag-interface", T.id, "6", "aai-node-type", "lag-interface","interface-name", "lagIntName-1");
- Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "7", "aai-node-type", "l-interface", "l-interface-id", "lInterfaceId-1",
- "l-interface-name", "lInterfaceName-1", "interface-role", "CUSTOMER");
-
- Vertex linterface2 = graph.addVertex(T.label, "l-interface", T.id, "9", "aai-node-type", "l-interface", "l-interface-id", "lInterfaceId-2",
- "l-interface-name", "lInterfaceName-2", "interface-role", "CUSTOMER-UPLINK");
- Vertex linterface3 = graph.addVertex(T.label, "l-interface", T.id, "10", "aai-node-type", "l-interface", "l-interface-id", "lInterfaceId-3",
- "l-interface-name", "lInterfaceName-3", "interface-role", "UPLINK");
- Vertex linterface4 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type", "l-interface", "l-interface-id", "lInterfaceId-4", "l-interface-name", "lInterfaceName-4", "interface-role", "CUSTOMER-UPLINK");
-
- Vertex lagint2 = graph.addVertex(T.label, "lag-interface", T.id, "8", "aai-node-type", "lag-interface","interface-name", "lagIntName-2");
- Vertex linterface21 = graph.addVertex(T.label, "l-interface", T.id, "20", "aai-node-type", "l-interface", "l-interface-id", "lInterfaceId-21",
- "l-interface-name", "lInterfaceName-2", "interface-role", "CUSTOMER-UPLINK");
-
- Vertex genericvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "12", "aai-node-type", "generic-vnf", "vnf-id", "vnfId-2","vnf-name", "vnfName-2");
- Vertex linterface31 = graph.addVertex(T.label, "l-interface", T.id, "13", "aai-node-type", "l-interface", "l-interface-id", "lInterfaceId-21", "l-interface-name", "lInterfaceName-21", "interface-role", "CUSTOMER-UPLINK");
- Vertex lagint3 = graph.addVertex(T.label, "lag-interface", T.id, "14", "aai-node-type", "lag-interface","interface-name", "lagIntName-22");
-
-
+ Vertex newvce = graph.addVertex(T.label, "newvce", T.id, "0", "aai-node-type", "newvce",
+ "vnf-id2", "vnfId2-1", "vnf-name", "vnfName-1", "vnf-type", "vnfType-1");
+ Vertex linterfaceNewvce1 = graph.addVertex(T.label, "l-interface", T.id, "1",
+ "aai-node-type", "l-interface", "l-interface-id", "lInterfaceId-10", "l-interface-name",
+ "lInterfaceName-1", "interface-role", "UPLINK");
+ Vertex linterfaceNewvce2 = graph.addVertex(T.label, "l-interface", T.id, "2",
+ "aai-node-type", "l-interface", "l-interface-id", "lInterfaceId-20", "l-interface-name",
+ "lInterfaceName-1", "interface-role", "CUSTOMER");
+ Vertex linterfaceNewvce3 = graph.addVertex(T.label, "l-interface", T.id, "3",
+ "aai-node-type", "l-interface", "l-interface-id", "lInterfaceId-30", "l-interface-name",
+ "lInterfaceName-3", "interface-role", "CUSTOMER-UPLINK");
+
+ Vertex logicalLink1 =
+ graph.addVertex(T.label, "logical-link", T.id, "4", "aai-node-type", "logical-link",
+ "link-name", "linkName-1", "in-maint", "false", "link-type", "linkType-1");
+
+ // 1 generic-vnf with 2 lags each has 1 linterface
+ Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "5", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfId-1", "vnf-name", "vnfName-1");
+ Vertex lagint1 = graph.addVertex(T.label, "lag-interface", T.id, "6", "aai-node-type",
+ "lag-interface", "interface-name", "lagIntName-1");
+ Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "7", "aai-node-type",
+ "l-interface", "l-interface-id", "lInterfaceId-1", "l-interface-name",
+ "lInterfaceName-1", "interface-role", "CUSTOMER");
+
+ Vertex linterface2 = graph.addVertex(T.label, "l-interface", T.id, "9", "aai-node-type",
+ "l-interface", "l-interface-id", "lInterfaceId-2", "l-interface-name",
+ "lInterfaceName-2", "interface-role", "CUSTOMER-UPLINK");
+ Vertex linterface3 = graph.addVertex(T.label, "l-interface", T.id, "10", "aai-node-type",
+ "l-interface", "l-interface-id", "lInterfaceId-3", "l-interface-name",
+ "lInterfaceName-3", "interface-role", "UPLINK");
+ Vertex linterface4 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type",
+ "l-interface", "l-interface-id", "lInterfaceId-4", "l-interface-name",
+ "lInterfaceName-4", "interface-role", "CUSTOMER-UPLINK");
+
+ Vertex lagint2 = graph.addVertex(T.label, "lag-interface", T.id, "8", "aai-node-type",
+ "lag-interface", "interface-name", "lagIntName-2");
+ Vertex linterface21 = graph.addVertex(T.label, "l-interface", T.id, "20", "aai-node-type",
+ "l-interface", "l-interface-id", "lInterfaceId-21", "l-interface-name",
+ "lInterfaceName-2", "interface-role", "CUSTOMER-UPLINK");
+
+ Vertex genericvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "12", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfId-2", "vnf-name", "vnfName-2");
+ Vertex linterface31 = graph.addVertex(T.label, "l-interface", T.id, "13", "aai-node-type",
+ "l-interface", "l-interface-id", "lInterfaceId-21", "l-interface-name",
+ "lInterfaceName-21", "interface-role", "CUSTOMER-UPLINK");
+ Vertex lagint3 = graph.addVertex(T.label, "lag-interface", T.id, "14", "aai-node-type",
+ "lag-interface", "interface-name", "lagIntName-22");
+
GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, newvce, linterfaceNewvce1); // true
+ rules.addTreeEdge(g, newvce, linterfaceNewvce1); // true
rules.addTreeEdge(g, newvce, linterfaceNewvce2);
- rules.addTreeEdge(g, newvce, linterfaceNewvce3);
- rules.addEdge(g, linterfaceNewvce1, logicalLink1); // true
- rules.addEdge(g, linterfaceNewvce2, logicalLink1);
-
+ rules.addTreeEdge(g, newvce, linterfaceNewvce3);
+ rules.addEdge(g, linterfaceNewvce1, logicalLink1); // true
+ rules.addEdge(g, linterfaceNewvce2, logicalLink1);
+
rules.addTreeEdge(g, genericvnf1, lagint1);
rules.addTreeEdge(g, lagint1, linterface1);
- rules.addTreeEdge(g, lagint1, linterface2); // true
- rules.addTreeEdge(g, lagint1, linterface3);
- rules.addTreeEdge(g, lagint1, linterface4); // true
+ rules.addTreeEdge(g, lagint1, linterface2); // true
+ rules.addTreeEdge(g, lagint1, linterface3);
+ rules.addTreeEdge(g, lagint1, linterface4); // true
rules.addTreeEdge(g, lagint2, linterface21);
-
- rules.addEdge(g, linterface2, logicalLink1); // true
- rules.addEdge(g, linterface4, logicalLink1); // true
- rules.addEdge(g, linterface21, logicalLink1); // true
-
+
+ rules.addEdge(g, linterface2, logicalLink1); // true
+ rules.addEdge(g, linterface4, logicalLink1); // true
+ rules.addEdge(g, linterface21, logicalLink1); // true
+
rules.addTreeEdge(g, genericvnf2, lagint3);
rules.addTreeEdge(g, lagint2, linterface31);
-
expectedResult.add(linterface2);
expectedResult.add(linterface4);
expectedResult.add(linterface21);
-
+
}
@Override
@@ -115,7 +132,7 @@ public class GetLinterfaceFromNewvceTest extends QueryTest {
@Override
protected void addParam(Map<String, Object> params) {
- params.put("interfaceRole1", "UPLINK");
- params.put("interfaceRole2", "CUSTOMER-UPLINK");
+ params.put("interfaceRole1", "UPLINK");
+ params.put("interfaceRole2", "CUSTOMER-UPLINK");
}
-} \ No newline at end of file
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetNetworksByServiceInstanceTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetNetworksByServiceInstanceTest.java
index 1b1395c..6af6e1b 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetNetworksByServiceInstanceTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetNetworksByServiceInstanceTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -31,90 +31,100 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class GetNetworksByServiceInstanceTest extends QueryTest {
- public GetNetworksByServiceInstanceTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex serviceInstance = graph.addVertex(T.label, "service-instance",T.id, "0", "aai-node-type", "service-instance", "service-instance-id", "serviceinstanceid");
- Vertex l3Network = graph.addVertex(T.label, "l3-network",T.id, "1", "aai-node-type", "l3-network","network-id", "networkId");
- Vertex vlanTag = graph.addVertex(T.label, "vlan-tag",T.id, "2", "aai-node-type", "vlan-tag","vlan-tag-id", "vlanTagId");
- Vertex l3Network1 = graph.addVertex(T.label, "l3-network",T.id, "3", "aai-node-type", "l3-network","network-id", "networkId1");
- Vertex vlanTag1 = graph.addVertex(T.label, "vlan-tag",T.id, "4", "aai-node-type", "vlan-tag","vlan-tag-id", "vlanTagId");
-
- Vertex serviceInstance2 = graph.addVertex(T.label, "service-instance",T.id, "5", "aai-node-type", "service-instance", "service-instance-id", "serviceinstanceid1");
- Vertex l3Network2 = graph.addVertex(T.label, "l3-network",T.id, "6", "aai-node-type", "l3-network","network-id", "networkId2");
- Vertex vlanTag2 = graph.addVertex(T.label, "vlan-tag",T.id, "7", "aai-node-type", "vlan-tag","vlan-tag-id", "vlanTagId");
- Vertex l3Network3 = graph.addVertex(T.label, "l3-network",T.id, "8", "aai-node-type", "l3-network","network-id", "networkId3");
- Vertex vlanTag3 = graph.addVertex(T.label, "vlan-tag",T.id, "9", "aai-node-type", "vlan-tag","vlan-tag-id", "vlanTagId");
- Vertex vlanTag4 = graph.addVertex(T.label, "vlan-tag",T.id, "10", "aai-node-type", "vlan-tag","vlan-tag-id", "vlanTagId");
-
-
- Vertex l3Network4 = graph.addVertex(T.label, "l3-network",T.id, "11", "aai-node-type", "l3-network","network-id", "networkId4");
- Vertex l3Network5 = graph.addVertex(T.label, "l3-network",T.id, "12", "aai-node-type", "l3-network","network-id", "networkId5");
-
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addEdge(g, serviceInstance,l3Network);
- rules.addEdge(g, serviceInstance,l3Network2);
-
- rules.addEdge(g, l3Network,vlanTag);
- rules.addEdge(g, l3Network,vlanTag2);
-
- rules.addEdge(g, l3Network,l3Network1);
- rules.addEdge(g, l3Network1,vlanTag1);
-
- rules.addEdge(g, l3Network2,vlanTag4);
-
- rules.addEdge(g, l3Network2,l3Network3);
- rules.addEdge(g, l3Network3,vlanTag3);
-
- rules.addEdge(g, l3Network4,l3Network5);
- rules.addEdge(g, serviceInstance,l3Network5);
-
- expectedResult.add(l3Network);
- expectedResult.add(l3Network2);
-
- expectedResult.add(vlanTag);
- expectedResult.add(vlanTag2);
-
- expectedResult.add(l3Network1);
- expectedResult.add(vlanTag1);
-
- expectedResult.add(vlanTag4);
-
- expectedResult.add(l3Network3);
- expectedResult.add(vlanTag3);
-
- expectedResult.add(l3Network4);
- expectedResult.add(l3Network5);
-
- //expectedResult.add(vlanTag1);//false
- //expectedResult.add(l3Network1);//false
- //expectedResult.add(linterface1);//false
- }
-
- @Override
- protected String getQueryName() {
- return "getNetworksByServiceInstance";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "service-instance").has("service-instance-id", "serviceinstanceid");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
-
-
-} \ No newline at end of file
+ public GetNetworksByServiceInstanceTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "0",
+ "aai-node-type", "service-instance", "service-instance-id", "serviceinstanceid");
+ Vertex l3Network = graph.addVertex(T.label, "l3-network", T.id, "1", "aai-node-type",
+ "l3-network", "network-id", "networkId");
+ Vertex vlanTag = graph.addVertex(T.label, "vlan-tag", T.id, "2", "aai-node-type",
+ "vlan-tag", "vlan-tag-id", "vlanTagId");
+ Vertex l3Network1 = graph.addVertex(T.label, "l3-network", T.id, "3", "aai-node-type",
+ "l3-network", "network-id", "networkId1");
+ Vertex vlanTag1 = graph.addVertex(T.label, "vlan-tag", T.id, "4", "aai-node-type",
+ "vlan-tag", "vlan-tag-id", "vlanTagId");
+
+ Vertex serviceInstance2 = graph.addVertex(T.label, "service-instance", T.id, "5",
+ "aai-node-type", "service-instance", "service-instance-id", "serviceinstanceid1");
+ Vertex l3Network2 = graph.addVertex(T.label, "l3-network", T.id, "6", "aai-node-type",
+ "l3-network", "network-id", "networkId2");
+ Vertex vlanTag2 = graph.addVertex(T.label, "vlan-tag", T.id, "7", "aai-node-type",
+ "vlan-tag", "vlan-tag-id", "vlanTagId");
+ Vertex l3Network3 = graph.addVertex(T.label, "l3-network", T.id, "8", "aai-node-type",
+ "l3-network", "network-id", "networkId3");
+ Vertex vlanTag3 = graph.addVertex(T.label, "vlan-tag", T.id, "9", "aai-node-type",
+ "vlan-tag", "vlan-tag-id", "vlanTagId");
+ Vertex vlanTag4 = graph.addVertex(T.label, "vlan-tag", T.id, "10", "aai-node-type",
+ "vlan-tag", "vlan-tag-id", "vlanTagId");
+
+ Vertex l3Network4 = graph.addVertex(T.label, "l3-network", T.id, "11", "aai-node-type",
+ "l3-network", "network-id", "networkId4");
+ Vertex l3Network5 = graph.addVertex(T.label, "l3-network", T.id, "12", "aai-node-type",
+ "l3-network", "network-id", "networkId5");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addEdge(g, serviceInstance, l3Network);
+ rules.addEdge(g, serviceInstance, l3Network2);
+
+ rules.addEdge(g, l3Network, vlanTag);
+ rules.addEdge(g, l3Network, vlanTag2);
+
+ rules.addEdge(g, l3Network, l3Network1);
+ rules.addEdge(g, l3Network1, vlanTag1);
+
+ rules.addEdge(g, l3Network2, vlanTag4);
+
+ rules.addEdge(g, l3Network2, l3Network3);
+ rules.addEdge(g, l3Network3, vlanTag3);
+
+ rules.addEdge(g, l3Network4, l3Network5);
+ rules.addEdge(g, serviceInstance, l3Network5);
+
+ expectedResult.add(l3Network);
+ expectedResult.add(l3Network2);
+
+ expectedResult.add(vlanTag);
+ expectedResult.add(vlanTag2);
+
+ expectedResult.add(l3Network1);
+ expectedResult.add(vlanTag1);
+
+ expectedResult.add(vlanTag4);
+
+ expectedResult.add(l3Network3);
+ expectedResult.add(vlanTag3);
+
+ expectedResult.add(l3Network4);
+ expectedResult.add(l3Network5);
+
+ // expectedResult.add(vlanTag1);//false
+ // expectedResult.add(l3Network1);//false
+ // expectedResult.add(linterface1);//false
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "getNetworksByServiceInstance";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "service-instance").has("service-instance-id", "serviceinstanceid");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
+
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetNetworksTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetNetworksTest.java
index 8e34236..3e4c1ee 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetNetworksTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetNetworksTest.java
@@ -9,7 +9,7 @@ package org.onap.aai.rest.search;
* 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
+ * 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,
@@ -30,63 +30,86 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class GetNetworksTest extends QueryTest {
-
- public GetNetworksTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
- @Test
- public void test() {
- super.run();
- }
+ public GetNetworksTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex owningentity = graph.addVertex(T.label, "owning-entity", T.id, "1", "aai-node-type", "owning-entity", "owning-entity-id", "owning-entity-id-0", "owning-entity-name", "owning-entity-name-0");
- Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "2", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-0");
- Vertex l3network = graph.addVertex(T.label, "l3-network", T.id, "3", "aai-node-type", "l3-network", "network-id", "network-id-0", "network-role", "network-role-0", "is-bound-to-vpn", "false", "is-provider-network", "false", "is-shared-network", "false", "is-external-network", "false");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "10", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-0", "cloud-region-owner", "cloud-owner-name-0","cloud-region-version","cloud-region-version-0");
- Vertex l3network2 = graph.addVertex(T.label, "l3-network", T.id, "8", "aai-node-type", "l3-network", "network-id", "network-id-2", "network-role", "network-role-2", "is-bound-to-vpn", "false", "is-provider-network", "false", "is-shared-network", "false", "is-external-network", "false");
- Vertex l3network3 = graph.addVertex(T.label, "l3-network", T.id, "9", "aai-node-type", "l3-network", "network-id", "network-id-0", "network-role", "network-role-3", "is-bound-to-vpn", "false", "is-provider-network", "false", "is-shared-network", "false", "is-external-network", "false");
- Vertex cloudregion2 = graph.addVertex(T.label, "cloud-region", T.id, "11", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-0","cloud-region-version","cloud-region-version-0");
-
- Vertex owningentity1 = graph.addVertex(T.label, "owning-entity", T.id, "4", "aai-node-type", "owning-entity", "owning-entity-id", "owning-entity-id-1", "owning-entity-name", "owning-entity-name-1");
- Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "5", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1");
- Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "6", "aai-node-type", "l3-network", "network-id", "network-id-1", "is-bound-to-vpn", "false", "is-provider-network", "false", "is-shared-network", "false", "is-external-network", "false");
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "7", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1","cloud-region-version","cloud-region-version-1");
+ @Test
+ public void test() {
+ super.run();
+ }
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, owningentity, serviceinstance);
- rules.addEdge(g, serviceinstance, l3network);
- rules.addEdge(g, l3network, cloudregion);
- rules.addEdge(g, serviceinstance, l3network2);
- rules.addEdge(g, l3network2, cloudregion);
- rules.addEdge(g, l3network3, cloudregion2);
- rules.addEdge(g, serviceinstance, l3network3);
-
- rules.addEdge(g, owningentity1, serviceinstance1);
- rules.addEdge(g, serviceinstance1, l3network1); //false
- rules.addEdge(g, l3network1, cloudregion1);
-
- expectedResult.add(l3network);
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex owningentity = graph.addVertex(T.label, "owning-entity", T.id, "1", "aai-node-type",
+ "owning-entity", "owning-entity-id", "owning-entity-id-0", "owning-entity-name",
+ "owning-entity-name-0");
+ Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "2",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-0");
+ Vertex l3network = graph.addVertex(T.label, "l3-network", T.id, "3", "aai-node-type",
+ "l3-network", "network-id", "network-id-0", "network-role", "network-role-0",
+ "is-bound-to-vpn", "false", "is-provider-network", "false", "is-shared-network",
+ "false", "is-external-network", "false");
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "10", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region-id-0", "cloud-region-owner",
+ "cloud-owner-name-0", "cloud-region-version", "cloud-region-version-0");
+ Vertex l3network2 = graph.addVertex(T.label, "l3-network", T.id, "8", "aai-node-type",
+ "l3-network", "network-id", "network-id-2", "network-role", "network-role-2",
+ "is-bound-to-vpn", "false", "is-provider-network", "false", "is-shared-network",
+ "false", "is-external-network", "false");
+ Vertex l3network3 = graph.addVertex(T.label, "l3-network", T.id, "9", "aai-node-type",
+ "l3-network", "network-id", "network-id-0", "network-role", "network-role-3",
+ "is-bound-to-vpn", "false", "is-provider-network", "false", "is-shared-network",
+ "false", "is-external-network", "false");
+ Vertex cloudregion2 = graph.addVertex(T.label, "cloud-region", T.id, "11", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region-id-2", "cloud-region-owner",
+ "cloud-owner-name-0", "cloud-region-version", "cloud-region-version-0");
- @Override
- protected String getQueryName() {
- return "getNetworks";
- }
+ Vertex owningentity1 = graph.addVertex(T.label, "owning-entity", T.id, "4", "aai-node-type",
+ "owning-entity", "owning-entity-id", "owning-entity-id-1", "owning-entity-name",
+ "owning-entity-name-1");
+ Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "5",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1");
+ Vertex l3network1 =
+ graph.addVertex(T.label, "l3-network", T.id, "6", "aai-node-type", "l3-network",
+ "network-id", "network-id-1", "is-bound-to-vpn", "false", "is-provider-network",
+ "false", "is-shared-network", "false", "is-external-network", "false");
+ Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "7", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner",
+ "cloud-owner-name-1", "cloud-region-version", "cloud-region-version-1");
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "owning-entity").has("owning-entity-id", "owning-entity-id-0");
- }
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, owningentity, serviceinstance);
+ rules.addEdge(g, serviceinstance, l3network);
+ rules.addEdge(g, l3network, cloudregion);
+ rules.addEdge(g, serviceinstance, l3network2);
+ rules.addEdge(g, l3network2, cloudregion);
+ rules.addEdge(g, l3network3, cloudregion2);
+ rules.addEdge(g, serviceinstance, l3network3);
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("networkRole", "network-role-0");
- params.put("cloudRegionId", "cloud-region-id-0");
- }
+ rules.addEdge(g, owningentity1, serviceinstance1);
+ rules.addEdge(g, serviceinstance1, l3network1); // false
+ rules.addEdge(g, l3network1, cloudregion1);
+
+ expectedResult.add(l3network);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "getNetworks";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "owning-entity").has("owning-entity-id", "owning-entity-id-0");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("networkRole", "network-role-0");
+ params.put("cloudRegionId", "cloud-region-id-0");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetPinterfacePhysicalLinkBySvcInstIdTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetPinterfacePhysicalLinkBySvcInstIdTest.java
index b271183..f1bf3f1 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetPinterfacePhysicalLinkBySvcInstIdTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetPinterfacePhysicalLinkBySvcInstIdTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,7 +19,6 @@
*/
package org.onap.aai.rest.search;
-
import java.util.Map;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
@@ -32,75 +31,85 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class GetPinterfacePhysicalLinkBySvcInstIdTest extends QueryTest {
- public GetPinterfacePhysicalLinkBySvcInstIdTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void test() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "0", "aai-node-type", "service-instance", "service-instance-id", "s-instance-id1");
- Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id", "s-instance-id2");
-
- Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-2", "vnf-name", "vnf-name-2");
-
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver", "hostname", "pservername1");
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver", "hostname", "pservername2");
-
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "6", "aai-node-type", "vserver", "vserver-id", "vserverid1");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver", "vserver-id", "vserverid2");
-
- Vertex pInterface = graph.addVertex(T.label, "p-interface", T.id, "8", "aai-node-type", "p-interface", "interface-name", "p-interface-1");
- Vertex pInterface1 = graph.addVertex(T.label, "p-interface", T.id, "9", "aai-node-type", "p-interface", "interface-name", "p-interface-2");
-
- Vertex plink = graph.addVertex(T.label, "physical-link", T.id, "10", "aai-node-type", "physical-link", "link-name", "link-name-1" );
- Vertex plink1 = graph.addVertex(T.label, "physical-link", T.id, "11", "aai-node-type", "physical-link", "link-name", "link-name-2" );
-
-
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addEdge(g, serviceinstance, gnvf);
- rules.addEdge(g, gnvf, vserver);
- rules.addEdge(g, vserver, pserver);
- rules.addTreeEdge(g, pserver, pInterface);
- rules.addEdge(g, pInterface, plink);
-
- rules.addEdge(g, serviceinstance1, gnvf1);
- rules.addEdge(g, gnvf1, vserver1);
- rules.addEdge(g, vserver1, pserver1);
- rules.addTreeEdge(g, pserver1, pInterface1);
- rules.addEdge(g, pInterface1, plink1);
-
- expectedResult.add(serviceinstance);
- expectedResult.add(gnvf);
- expectedResult.add(vserver);
- expectedResult.add(pserver);
- expectedResult.add(pInterface);
- expectedResult.add(plink);
-
-
- }
-
- @Override
- protected String getQueryName() {
- return "getPinterfacePhysicalLinkBySvcInstId";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "service-instance").has("service-instance-id", "s-instance-id1");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ public GetPinterfacePhysicalLinkBySvcInstIdTest()
+ throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void test() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "0",
+ "aai-node-type", "service-instance", "service-instance-id", "s-instance-id1");
+ Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "s-instance-id2");
+
+ Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
+ Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-2", "vnf-name", "vnf-name-2");
+
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver",
+ "hostname", "pservername1");
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver",
+ "hostname", "pservername2");
+
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "6", "aai-node-type", "vserver",
+ "vserver-id", "vserverid1");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver",
+ "vserver-id", "vserverid2");
+
+ Vertex pInterface = graph.addVertex(T.label, "p-interface", T.id, "8", "aai-node-type",
+ "p-interface", "interface-name", "p-interface-1");
+ Vertex pInterface1 = graph.addVertex(T.label, "p-interface", T.id, "9", "aai-node-type",
+ "p-interface", "interface-name", "p-interface-2");
+
+ Vertex plink = graph.addVertex(T.label, "physical-link", T.id, "10", "aai-node-type",
+ "physical-link", "link-name", "link-name-1");
+ Vertex plink1 = graph.addVertex(T.label, "physical-link", T.id, "11", "aai-node-type",
+ "physical-link", "link-name", "link-name-2");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addEdge(g, serviceinstance, gnvf);
+ rules.addEdge(g, gnvf, vserver);
+ rules.addEdge(g, vserver, pserver);
+ rules.addTreeEdge(g, pserver, pInterface);
+ rules.addEdge(g, pInterface, plink);
+
+ rules.addEdge(g, serviceinstance1, gnvf1);
+ rules.addEdge(g, gnvf1, vserver1);
+ rules.addEdge(g, vserver1, pserver1);
+ rules.addTreeEdge(g, pserver1, pInterface1);
+ rules.addEdge(g, pInterface1, plink1);
+
+ expectedResult.add(serviceinstance);
+ expectedResult.add(gnvf);
+ expectedResult.add(vserver);
+ expectedResult.add(pserver);
+ expectedResult.add(pInterface);
+ expectedResult.add(plink);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "getPinterfacePhysicalLinkBySvcInstId";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "service-instance").has("service-instance-id", "s-instance-id1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetRouterRoadmTailSummaryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetRouterRoadmTailSummaryTest.java
index 6e0f852..bbde1d4 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetRouterRoadmTailSummaryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetRouterRoadmTailSummaryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,11 @@
*/
package org.onap.aai.rest.search;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Map;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.T;
@@ -27,12 +32,7 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
-import java.util.Map;
-
-public class GetRouterRoadmTailSummaryTest extends TreeQueryTest{
+public class GetRouterRoadmTailSummaryTest extends TreeQueryTest {
public GetRouterRoadmTailSummaryTest() throws AAIException, NoEdgeRuleFoundException {
super();
@@ -40,16 +40,25 @@ public class GetRouterRoadmTailSummaryTest extends TreeQueryTest{
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex logicalLink1 = graph.addVertex(T.label, "logical-link", T.id, "4", "aai-node-type", "logical-link", "link-name", "logical-link-1");
- Vertex logicalLink2 = graph.addVertex(T.label, "logical-link", T.id, "5", "aai-node-type", "logical-link", "link-name", "logical-link-2");
- Vertex pInterface1 = graph.addVertex(T.label, "p-interface", T.id, "6", "aai-node-type", "p-interface", "interface-name", "p-interface-1");
- Vertex pInterface2 = graph.addVertex(T.label, "p-interface", T.id, "7", "aai-node-type", "p-interface", "interface-name", "p-interface-2");
- Vertex pInterface3 = graph.addVertex(T.label, "p-interface", T.id, "8", "aai-node-type", "p-interface", "interface-name", "p-interface-3");
- Vertex pInterface4 = graph.addVertex(T.label, "p-interface", T.id, "12", "aai-node-type", "p-interface", "interface-name", "p-interface-4");
- Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "9", "aai-node-type", "pnf", "pnf-name", "pnf1name");
- Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "10", "aai-node-type", "pnf", "pnf-name", "pnf2name");
+ Vertex logicalLink1 = graph.addVertex(T.label, "logical-link", T.id, "4", "aai-node-type",
+ "logical-link", "link-name", "logical-link-1");
+ Vertex logicalLink2 = graph.addVertex(T.label, "logical-link", T.id, "5", "aai-node-type",
+ "logical-link", "link-name", "logical-link-2");
+ Vertex pInterface1 = graph.addVertex(T.label, "p-interface", T.id, "6", "aai-node-type",
+ "p-interface", "interface-name", "p-interface-1");
+ Vertex pInterface2 = graph.addVertex(T.label, "p-interface", T.id, "7", "aai-node-type",
+ "p-interface", "interface-name", "p-interface-2");
+ Vertex pInterface3 = graph.addVertex(T.label, "p-interface", T.id, "8", "aai-node-type",
+ "p-interface", "interface-name", "p-interface-3");
+ Vertex pInterface4 = graph.addVertex(T.label, "p-interface", T.id, "12", "aai-node-type",
+ "p-interface", "interface-name", "p-interface-4");
+ Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "9", "aai-node-type", "pnf", "pnf-name",
+ "pnf1name");
+ Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "10", "aai-node-type", "pnf",
+ "pnf-name", "pnf2name");
- Vertex lInterface1 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type", "l-interface", "interface-name", "l-interface-1");
+ Vertex lInterface1 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type",
+ "l-interface", "interface-name", "l-interface-1");
rules.addEdge(gts, logicalLink2, logicalLink1);
rules.addEdge(gts, logicalLink2, pInterface1);
@@ -59,56 +68,65 @@ public class GetRouterRoadmTailSummaryTest extends TreeQueryTest{
rules.addTreeEdge(gts, pInterface1, pnf1);
rules.addTreeEdge(gts, pInterface2, pnf2);
rules.addTreeEdge(gts, pInterface3, pnf2);
- rules.addTreeEdge(gts, pInterface4, pnf1); //false
+ rules.addTreeEdge(gts, pInterface4, pnf1); // false
- rules.addEdge(gts, logicalLink2, lInterface1);//false
+ rules.addEdge(gts, logicalLink2, lInterface1);// false
expectedResult.add(pnf1);
expectedResult.add(pInterface1);
- //expectedResult.add(logicalLink1);
+ // expectedResult.add(logicalLink1);
expectedResult.add(pInterface2);
expectedResult.add(pInterface3);
expectedResult.add(pnf2);
expectedResult.add(logicalLink2);
-
+
}
@Test
public void run() {
super.run();
-
- Tree tree = treeList.get(0); //pnf1
-
- Vertex l1 = graph.traversal().V().has("aai-node-type","logical-link").has("link-name","logical-link-1").next();
-
- Vertex l2 = graph.traversal().V().has("aai-node-type","logical-link").has("link-name","logical-link-2").next();
- Vertex pInt1 = graph.traversal().V().has("aai-node-type","p-interface").has("interface-name","p-interface-1").next();
- Vertex pInt2 = graph.traversal().V().has("aai-node-type","p-interface").has("interface-name","p-interface-2").next();
- Vertex pInt3 = graph.traversal().V().has("aai-node-type","p-interface").has("interface-name","p-interface-3").next();
- Vertex pInt4 = graph.traversal().V().has("aai-node-type","p-interface").has("interface-name","p-interface-4").next();
- Vertex pnf1 = graph.traversal().V().has("aai-node-type","pnf").has("pnf-name","pnf1name").next();
- Vertex pnf2 = graph.traversal().V().has("aai-node-type","pnf").has("pnf-name","pnf2name").next();
-
+
+ Tree tree = treeList.get(0); // pnf1
+
+ Vertex l1 = graph.traversal().V().has("aai-node-type", "logical-link")
+ .has("link-name", "logical-link-1").next();
+
+ Vertex l2 = graph.traversal().V().has("aai-node-type", "logical-link")
+ .has("link-name", "logical-link-2").next();
+ Vertex pInt1 = graph.traversal().V().has("aai-node-type", "p-interface")
+ .has("interface-name", "p-interface-1").next();
+ Vertex pInt2 = graph.traversal().V().has("aai-node-type", "p-interface")
+ .has("interface-name", "p-interface-2").next();
+ Vertex pInt3 = graph.traversal().V().has("aai-node-type", "p-interface")
+ .has("interface-name", "p-interface-3").next();
+ Vertex pInt4 = graph.traversal().V().has("aai-node-type", "p-interface")
+ .has("interface-name", "p-interface-4").next();
+ Vertex pnf1 =
+ graph.traversal().V().has("aai-node-type", "pnf").has("pnf-name", "pnf1name").next();
+ Vertex pnf2 =
+ graph.traversal().V().has("aai-node-type", "pnf").has("pnf-name", "pnf2name").next();
+
/*
* Expected:
- * {v[9] -> pnf1
- {v[6] -> pInt1
- {v[5] -> l2
- {
- v[6] -> pInt1
- {v[9]={}}, -> pnf1
- v[7]= -> pInt2
- {v[10]={}}, -> pnf2
- v[8]= -> pInt3
- {v[10]={}} -> pnf2
- }
- }
- }
- }
+ * {v[9] -> pnf1
+ * {v[6] -> pInt1
+ * {v[5] -> l2
+ * {
+ * v[6] -> pInt1
+ * {v[9]={}}, -> pnf1
+ * v[7]= -> pInt2
+ * {v[10]={}}, -> pnf2
+ * v[8]= -> pInt3
+ * {v[10]={}} -> pnf2
+ * }
+ * }
+ * }
+ * }
*/
-
+
assertTrue(tree.containsKey(pnf1));
- assertFalse(((Tree) tree.get(pnf1)).containsKey(pInt4)); //pInt4 is not connected to any logical-link
+ assertFalse(((Tree) tree.get(pnf1)).containsKey(pInt4)); // pInt4 is not connected to any
+ // logical-link
assertTrue(((Tree) tree.get(pnf1)).containsKey(pInt1));
assertTrue(tree.getObjectsAtDepth(3).contains(l2));
assertTrue(tree.getObjectsAtDepth(4).contains(pInt1));
@@ -117,7 +135,7 @@ public class GetRouterRoadmTailSummaryTest extends TreeQueryTest{
assertTrue(tree.getObjectsAtDepth(4).contains(pInt3));
assertTrue(tree.getObjectsAtDepth(5).contains(pnf2));
}
-
+
@Override
protected String getQueryName() {
return "getRouterRoadmTailSummary";
@@ -133,4 +151,4 @@ public class GetRouterRoadmTailSummaryTest extends TreeQueryTest{
return;
}
-} \ No newline at end of file
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetServiceInstanceSummaryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetServiceInstanceSummaryTest.java
index 1fba932..d2a248e 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetServiceInstanceSummaryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetServiceInstanceSummaryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,79 +26,100 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class GetServiceInstanceSummaryTest extends QueryTest {
-
- public GetServiceInstanceSummaryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //set up test graph
- Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id", "serviceinstanceid0");
- Vertex l3network = graph.addVertex(T.label, "l3-network", T.id, "2", "aai-node-type", "l3-network", "network-id", "networkid0");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
- Vertex servicesub = graph.addVertex(T.label, "service-subscription", T.id, "4", "aai-node-type", "service-subscription", "service-type", "servicetype0");
- Vertex customer = graph.addVertex(T.label, "customer", T.id, "5", "aai-node-type", "customer", "customer-id", "customerid0");
- Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "6", "aai-node-type", "generic-vnf", "vnf-id", "vnfid0");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver", "vserver-id", "vserverid0");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "8", "aai-node-type", "tenant", "tenant-id", "tenantid0", "tenant-name", "tenantName0");
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "9", "aai-node-type", "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
-
- Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "10", "aai-node-type", "service-instance", "service-instance-id", "serviceinstanceid1");
- Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "11", "aai-node-type", "l3-network", "network-id", "networkid0");
- Vertex cloudregion2 = graph.addVertex(T.label, "cloud-region", T.id, "12", "aai-node-type", "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
- Vertex servicesub1 = graph.addVertex(T.label, "service-subscription", T.id, "13", "aai-node-type", "service-subscription", "service-type", "servicetype0");
- Vertex customer1 = graph.addVertex(T.label, "customer", T.id, "14", "aai-node-type", "customer", "customer-id", "customerid0");
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "15", "aai-node-type", "generic-vnf", "vnf-id", "vnfid0");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "16", "aai-node-type", "vserver", "vserver-id", "vserverid0");
- Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "17", "aai-node-type", "tenant", "tenant-id", "tenantid0", "tenant-name", "tenantName0");
- Vertex cloudregion3 = graph.addVertex(T.label, "cloud-region", T.id, "18", "aai-node-type", "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
- GraphTraversalSource g = graph.traversal();
-
- rules.addEdge(g, serviceinstance, l3network);
- rules.addEdge(g, l3network, cloudregion);
- rules.addTreeEdge(g, serviceinstance, servicesub);
- rules.addTreeEdge(g, servicesub, customer);
- rules.addEdge(g, serviceinstance, genericvnf);
- rules.addEdge(g, genericvnf, vserver);
- rules.addTreeEdge(g, vserver, tenant);
- rules.addTreeEdge(g, tenant, cloudregion1);
-
- rules.addEdge(g, serviceinstance1, l3network1);//false
- rules.addEdge(g, l3network1, cloudregion2);//false
- rules.addTreeEdge(g, serviceinstance1, servicesub1);//false
- rules.addTreeEdge(g, servicesub1, customer1);//false
- rules.addEdge(g, serviceinstance1, genericvnf1);//false
- rules.addEdge(g, genericvnf1, vserver1);//false
- rules.addTreeEdge(g, vserver1, tenant1);//false
- rules.addTreeEdge(g, tenant1, cloudregion3);//false
-
- expectedResult.add(serviceinstance);
- expectedResult.add(cloudregion);
- expectedResult.add(cloudregion1);
- expectedResult.add(servicesub);
- expectedResult.add(customer);
- }
- @Override
- protected String getQueryName() {
- return "getServiceInstanceSummary";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "service-instance").has("service-instance-id", "serviceinstanceid0");
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ public GetServiceInstanceSummaryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // set up test graph
+ Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "serviceinstanceid0");
+ Vertex l3network = graph.addVertex(T.label, "l3-network", T.id, "2", "aai-node-type",
+ "l3-network", "network-id", "networkid0");
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
+ Vertex servicesub = graph.addVertex(T.label, "service-subscription", T.id, "4",
+ "aai-node-type", "service-subscription", "service-type", "servicetype0");
+ Vertex customer = graph.addVertex(T.label, "customer", T.id, "5", "aai-node-type",
+ "customer", "customer-id", "customerid0");
+ Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "6", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid0");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver",
+ "vserver-id", "vserverid0");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "8", "aai-node-type", "tenant",
+ "tenant-id", "tenantid0", "tenant-name", "tenantName0");
+ Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "9", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
+
+ Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "10",
+ "aai-node-type", "service-instance", "service-instance-id", "serviceinstanceid1");
+ Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "11", "aai-node-type",
+ "l3-network", "network-id", "networkid0");
+ Vertex cloudregion2 = graph.addVertex(T.label, "cloud-region", T.id, "12", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
+ Vertex servicesub1 = graph.addVertex(T.label, "service-subscription", T.id, "13",
+ "aai-node-type", "service-subscription", "service-type", "servicetype0");
+ Vertex customer1 = graph.addVertex(T.label, "customer", T.id, "14", "aai-node-type",
+ "customer", "customer-id", "customerid0");
+ Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "15", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid0");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "16", "aai-node-type",
+ "vserver", "vserver-id", "vserverid0");
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "17", "aai-node-type", "tenant",
+ "tenant-id", "tenantid0", "tenant-name", "tenantName0");
+ Vertex cloudregion3 = graph.addVertex(T.label, "cloud-region", T.id, "18", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addEdge(g, serviceinstance, l3network);
+ rules.addEdge(g, l3network, cloudregion);
+ rules.addTreeEdge(g, serviceinstance, servicesub);
+ rules.addTreeEdge(g, servicesub, customer);
+ rules.addEdge(g, serviceinstance, genericvnf);
+ rules.addEdge(g, genericvnf, vserver);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addTreeEdge(g, tenant, cloudregion1);
+
+ rules.addEdge(g, serviceinstance1, l3network1);// false
+ rules.addEdge(g, l3network1, cloudregion2);// false
+ rules.addTreeEdge(g, serviceinstance1, servicesub1);// false
+ rules.addTreeEdge(g, servicesub1, customer1);// false
+ rules.addEdge(g, serviceinstance1, genericvnf1);// false
+ rules.addEdge(g, genericvnf1, vserver1);// false
+ rules.addTreeEdge(g, vserver1, tenant1);// false
+ rules.addTreeEdge(g, tenant1, cloudregion3);// false
+
+ expectedResult.add(serviceinstance);
+ expectedResult.add(cloudregion);
+ expectedResult.add(cloudregion1);
+ expectedResult.add(servicesub);
+ expectedResult.add(customer);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "getServiceInstanceSummary";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "service-instance").has("service-instance-id", "serviceinstanceid0");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetServiceInstanceVnfVfModuleModelsTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetServiceInstanceVnfVfModuleModelsTest.java
index 64abbae..6714a13 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetServiceInstanceVnfVfModuleModelsTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetServiceInstanceVnfVfModuleModelsTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,8 @@
*/
package org.onap.aai.rest.search;
+import java.util.Map;
+
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.T;
@@ -29,59 +31,72 @@ import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-
public class GetServiceInstanceVnfVfModuleModelsTest extends QueryTest {
public GetServiceInstanceVnfVfModuleModelsTest() throws AAIException, NoEdgeRuleFoundException {
super();
}
+
@Test
public void run() {
super.run();
}
+ @Override
+ protected void createGraph()
+ throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+ Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
+ Vertex modelver = graph.addVertex(T.label, "model-ver", T.id, "2", "aai-node-type",
+ "model-ver", "model-ver-id", "model-ver-id-1");
+ Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1");
+ Vertex modelver1 = graph.addVertex(T.label, "model-ver", T.id, "4", "aai-node-type",
+ "model-ver", "model-ver-id", "model-ver-id-1");
+ Vertex model = graph.addVertex(T.label, "model", T.id, "5", "aai-node-type", "model",
+ "model-id", "model-id-1");
+ Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "6", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-1");
+ Vertex modelver2 = graph.addVertex(T.label, "model-ver", T.id, "7", "aai-node-type",
+ "model-ver", "model-ver-id", "model-ver-id-2");
+ Vertex model1 = graph.addVertex(T.label, "model", T.id, "8", "aai-node-type", "model",
+ "model-id", "model-id-2");
+
+ Vertex serviceInstance1 = graph.addVertex(T.label, "service-instance", T.id, "9",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2",
+ "service-instance-name", "service-instance-name-2");
+ Vertex l3network = graph.addVertex(T.label, "l3-network", T.id, "10", "aai-node-type",
+ "l3-network", "l3-network-id", "l3-network-id-1");
+ Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "11", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-2");
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "12", "aai-node-type", "complex",
+ "complex-id", "complex-1");
+ Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "13", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-2");
+ Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "14", "aai-node-type",
+ "l3-network", "l3-network-id", "l3-network-id-2");
+
+ Vertex model2 = graph.addVertex(T.label, "model", T.id, "15", "aai-node-type", "model",
+ "model-id", "model-id-3");
- @Override
- protected void createGraph() throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
-
- Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name", "service-instance-name-1");
- Vertex modelver = graph.addVertex(T.label, "model-ver", T.id, "2", "aai-node-type", "model-ver","model-ver-id", "model-ver-id-1");
- Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1");
- Vertex modelver1 = graph.addVertex(T.label, "model-ver", T.id, "4", "aai-node-type", "model-ver","model-ver-id", "model-ver-id-1");
- Vertex model = graph.addVertex(T.label, "model", T.id, "5", "aai-node-type", "model","model-id", "model-id-1");
- Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "6", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-1");
- Vertex modelver2 = graph.addVertex(T.label, "model-ver", T.id, "7", "aai-node-type", "model-ver","model-ver-id", "model-ver-id-2");
- Vertex model1 = graph.addVertex(T.label, "model", T.id, "8", "aai-node-type", "model","model-id", "model-id-2");
-
- Vertex serviceInstance1 = graph.addVertex(T.label, "service-instance", T.id, "9", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2", "service-instance-name", "service-instance-name-2");
- Vertex l3network = graph.addVertex(T.label, "l3-network", T.id, "10", "aai-node-type", "l3-network","l3-network-id", "l3-network-id-1");
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "11", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-2");
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "12", "aai-node-type", "complex","complex-id", "complex-1");
- Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "13", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-2");
- Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "14", "aai-node-type", "l3-network","l3-network-id", "l3-network-id-2");
-
- Vertex model2 = graph.addVertex(T.label, "model", T.id, "15", "aai-node-type", "model","model-id", "model-id-3");
-
-
GraphTraversalSource g = graph.traversal();
- rules.addPrivateEdge(g, serviceInstance, modelver,null);
+ rules.addPrivateEdge(g, serviceInstance, modelver, null);
rules.addTreeEdge(g, modelver, model2);
rules.addEdge(g, serviceInstance, genericvnf);
- rules.addPrivateEdge(g, genericvnf, modelver1,null);
+ rules.addPrivateEdge(g, genericvnf, modelver1, null);
rules.addTreeEdge(g, modelver1, model);
rules.addTreeEdge(g, genericvnf, vfmodule);
- rules.addPrivateEdge(g, vfmodule, modelver2,null);
+ rules.addPrivateEdge(g, vfmodule, modelver2, null);
rules.addTreeEdge(g, modelver2, model1);
-
- rules.addEdge(g, serviceInstance1, l3network);//not expected in result
- rules.addEdge(g, serviceInstance1, genericvnf1);//not expected in result
- rules.addEdge(g, genericvnf1, complex);//not expected in result
- rules.addTreeEdge(g, genericvnf1, vfmodule1);//not expected in result
- rules.addEdge(g, vfmodule1, l3network1);//not expected in result
-
-
+
+ rules.addEdge(g, serviceInstance1, l3network);// not expected in result
+ rules.addEdge(g, serviceInstance1, genericvnf1);// not expected in result
+ rules.addEdge(g, genericvnf1, complex);// not expected in result
+ rules.addTreeEdge(g, genericvnf1, vfmodule1);// not expected in result
+ rules.addEdge(g, vfmodule1, l3network1);// not expected in result
+
expectedResult.add(serviceInstance);
expectedResult.add(modelver);
expectedResult.add(model2);
@@ -91,19 +106,20 @@ public class GetServiceInstanceVnfVfModuleModelsTest extends QueryTest {
expectedResult.add(vfmodule);
expectedResult.add(modelver2);
expectedResult.add(model1);
-
}
-
@Override
protected String getQueryName() {
- return "getServiceInstanceVnfVfModuleModels";
+ return "getServiceInstanceVnfVfModuleModels";
}
+
@Override
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "service-instance").has("service-instance-id", "service-instance-id-1");
+ g.has("aai-node-type", "service-instance").has("service-instance-id",
+ "service-instance-id-1");
}
+
@Override
protected void addParam(Map<String, Object> params) {
return;
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetServiceTopologyTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetServiceTopologyTest.java
index 5475ea8..c9694d0 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetServiceTopologyTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetServiceTopologyTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -36,143 +36,191 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class GetServiceTopologyTest extends TreeQueryTest {
- public GetServiceTopologyTest() throws AAIException, NoEdgeRuleFoundException {
- super();
+ public GetServiceTopologyTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
}
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
-
-
-
- Vertex customer = graph.addVertex(T.label, "customer", T.id, "1", "aai-node-type", "customer", "global-customer-id", "customer-id-1", "subscriber-name", "customer-name1", "subscriber-type", "customer-type1");
- Vertex serviceSubscription = graph.addVertex(T.label, "service-subscription", T.id, "2", "aai-node-type", "service-subscription", "service-type", "service-subcription-1");
-
- Vertex serviceInstanceOne = graph.addVertex(T.label, "service-instance", T.id, "3", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name", "service-instance-name-1");
- Vertex genericVnfOne = graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type", "generic-vnf", "vnf-name", "vnf-name", "vnf-type", "test", "vnf-id", "vnf-test=1");
- Vertex lInterfaceOne = graph.addVertex(T.label, "l-interface", T.id, "5", "aai-node-type", "l-interface", "interface-name", "test-l-interface-one");
- Vertex l3Ipv4AddressListOne = graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "6", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test1");
- Vertex l3Ipv6AddressListOne = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "7", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test2");
-
- Vertex vlanOne = graph.addVertex(T.label, "vlan", T.id, "8", "aai-node-type", "vlan", "vlan-interface", "test-vlan-one");
- Vertex l3Ipv4AddressListTwo = graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "9", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test3");
- Vertex l3Ipv6AddressListTwo = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "10", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test4");
-
- Vertex vserverOne = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type", "vserver", "vserver-id-one", "test-vserver", "vserver-selflink", "test", "vserver-name", "test-vserver");
- Vertex lInterfaceTwo = graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type", "l-interface", "interface-name", "test-l-interface-two");
- Vertex l3Ipv4AddressListThree = graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "13", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test5");
- Vertex l3Ipv6AddressListThree = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "14", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test6");
-
- Vertex vlanTwo = graph.addVertex(T.label, "vlan", T.id, "15", "aai-node-type", "vlan", "vlan-interface", "test-vlan-two");
- Vertex l3Ipv4AddressListFour = graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "16", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test7");
- Vertex l3Ipv6AddressListFour = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "17", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test8");
-
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "18", "aai-node-type", "pserver", "hostname", "test-pserver");
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "19", "aai-node-type", "complex", "physical-location-id", "test-complex");
-
- Vertex allottedResource = graph.addVertex(T.label, "allotted-resource", T.id, "20", "aai-node-type", "allotted-resource", "id", "test-resource");
- Vertex serviceInstanceTwo = graph.addVertex(T.label, "service-instance", T.id, "21", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2", "service-instance-name", "service-instance-name-1");
- Vertex genericVnfTwo = graph.addVertex(T.label, "generic-vnf", T.id, "22", "aai-node-type", "generic-vnf", "vnf-name", "vnf-name", "vnf-type", "test", "vnf-id", "vnf-test-2");
- Vertex lInterfaceThree = graph.addVertex(T.label, "l-interface", T.id, "23", "aai-node-type", "l-interface", "interface-name", "test-l-interface-three");
- Vertex l3Ipv4AddressListFive = graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "24", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test9");
- Vertex l3Ipv6AddressListFive = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "25", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test10");
-
- Vertex vlanThree = graph.addVertex(T.label, "vlan", T.id, "26", "aai-node-type", "vlan", "vlan-interface", "test-vlan-three");
- Vertex l3Ipv4AddressListSix = graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "27", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test11");
- Vertex l3Ipv6AddressListSix = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "28", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test12");
-
- Vertex vserverTwo = graph.addVertex(T.label, "vserver", T.id, "29", "aai-node-type", "vserver", "vserver-id", "test-vserver", "vserver-selflink", "test", "vserver-name", "test-vserver=two");
- Vertex lInterfaceFour = graph.addVertex(T.label, "l-interface", T.id, "30", "aai-node-type", "l-interface", "interface-name", "test-l-interface-four");
- Vertex l3Ipv4AddressListSeven = graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "31", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test13");
- Vertex l3Ipv6AddressListSeven = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "32", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test14");
-
- Vertex vlanFour = graph.addVertex(T.label, "vlan", T.id, "33", "aai-node-type", "vlan", "vlan-interface", "test-vlan-four");
- Vertex l3Ipv4AddressListEight = graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "34", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test15");
- Vertex l3Ipv6AddressListEight = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "35", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test16");
-
-
+ // Set up the test graph
+
+ Vertex customer = graph.addVertex(T.label, "customer", T.id, "1", "aai-node-type",
+ "customer", "global-customer-id", "customer-id-1", "subscriber-name", "customer-name1",
+ "subscriber-type", "customer-type1");
+ Vertex serviceSubscription = graph.addVertex(T.label, "service-subscription", T.id, "2",
+ "aai-node-type", "service-subscription", "service-type", "service-subcription-1");
+
+ Vertex serviceInstanceOne = graph.addVertex(T.label, "service-instance", T.id, "3",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
+ Vertex genericVnfOne = graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type",
+ "generic-vnf", "vnf-name", "vnf-name", "vnf-type", "test", "vnf-id", "vnf-test=1");
+ Vertex lInterfaceOne = graph.addVertex(T.label, "l-interface", T.id, "5", "aai-node-type",
+ "l-interface", "interface-name", "test-l-interface-one");
+ Vertex l3Ipv4AddressListOne =
+ graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "6", "aai-node-type",
+ "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test1");
+ Vertex l3Ipv6AddressListOne =
+ graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "7", "aai-node-type",
+ "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test2");
+
+ Vertex vlanOne = graph.addVertex(T.label, "vlan", T.id, "8", "aai-node-type", "vlan",
+ "vlan-interface", "test-vlan-one");
+ Vertex l3Ipv4AddressListTwo =
+ graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "9", "aai-node-type",
+ "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test3");
+ Vertex l3Ipv6AddressListTwo =
+ graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "10", "aai-node-type",
+ "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test4");
+
+ Vertex vserverOne = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type",
+ "vserver", "vserver-id-one", "test-vserver", "vserver-selflink", "test", "vserver-name",
+ "test-vserver");
+ Vertex lInterfaceTwo = graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type",
+ "l-interface", "interface-name", "test-l-interface-two");
+ Vertex l3Ipv4AddressListThree =
+ graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "13", "aai-node-type",
+ "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test5");
+ Vertex l3Ipv6AddressListThree =
+ graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "14", "aai-node-type",
+ "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test6");
+
+ Vertex vlanTwo = graph.addVertex(T.label, "vlan", T.id, "15", "aai-node-type", "vlan",
+ "vlan-interface", "test-vlan-two");
+ Vertex l3Ipv4AddressListFour =
+ graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "16", "aai-node-type",
+ "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test7");
+ Vertex l3Ipv6AddressListFour =
+ graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "17", "aai-node-type",
+ "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test8");
+
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "18", "aai-node-type", "pserver",
+ "hostname", "test-pserver");
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "19", "aai-node-type", "complex",
+ "physical-location-id", "test-complex");
+
+ Vertex allottedResource = graph.addVertex(T.label, "allotted-resource", T.id, "20",
+ "aai-node-type", "allotted-resource", "id", "test-resource");
+ Vertex serviceInstanceTwo = graph.addVertex(T.label, "service-instance", T.id, "21",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2",
+ "service-instance-name", "service-instance-name-1");
+ Vertex genericVnfTwo = graph.addVertex(T.label, "generic-vnf", T.id, "22", "aai-node-type",
+ "generic-vnf", "vnf-name", "vnf-name", "vnf-type", "test", "vnf-id", "vnf-test-2");
+ Vertex lInterfaceThree = graph.addVertex(T.label, "l-interface", T.id, "23",
+ "aai-node-type", "l-interface", "interface-name", "test-l-interface-three");
+ Vertex l3Ipv4AddressListFive =
+ graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "24", "aai-node-type",
+ "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test9");
+ Vertex l3Ipv6AddressListFive =
+ graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "25", "aai-node-type",
+ "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test10");
+
+ Vertex vlanThree = graph.addVertex(T.label, "vlan", T.id, "26", "aai-node-type", "vlan",
+ "vlan-interface", "test-vlan-three");
+ Vertex l3Ipv4AddressListSix =
+ graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "27", "aai-node-type",
+ "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test11");
+ Vertex l3Ipv6AddressListSix =
+ graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "28", "aai-node-type",
+ "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test12");
+
+ Vertex vserverTwo = graph.addVertex(T.label, "vserver", T.id, "29", "aai-node-type",
+ "vserver", "vserver-id", "test-vserver", "vserver-selflink", "test", "vserver-name",
+ "test-vserver=two");
+ Vertex lInterfaceFour = graph.addVertex(T.label, "l-interface", T.id, "30", "aai-node-type",
+ "l-interface", "interface-name", "test-l-interface-four");
+ Vertex l3Ipv4AddressListSeven =
+ graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "31", "aai-node-type",
+ "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test13");
+ Vertex l3Ipv6AddressListSeven =
+ graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "32", "aai-node-type",
+ "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test14");
+
+ Vertex vlanFour = graph.addVertex(T.label, "vlan", T.id, "33", "aai-node-type", "vlan",
+ "vlan-interface", "test-vlan-four");
+ Vertex l3Ipv4AddressListEight =
+ graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "34", "aai-node-type",
+ "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "test15");
+ Vertex l3Ipv6AddressListEight =
+ graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "35", "aai-node-type",
+ "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "test16");
+
GraphTraversalSource g = graph.traversal();
-
-
+
rules.addTreeEdge(g, customer, serviceSubscription);
rules.addTreeEdge(g, serviceSubscription, serviceInstanceOne);
-
+
rules.addEdge(g, serviceInstanceOne, genericVnfOne);
rules.addTreeEdge(g, genericVnfOne, lInterfaceOne);
rules.addTreeEdge(g, lInterfaceOne, l3Ipv4AddressListOne);
rules.addTreeEdge(g, lInterfaceOne, l3Ipv6AddressListOne);
-
+
rules.addTreeEdge(g, lInterfaceOne, vlanOne);
rules.addTreeEdge(g, vlanOne, l3Ipv4AddressListTwo);
rules.addTreeEdge(g, vlanOne, l3Ipv6AddressListTwo);
-
+
rules.addEdge(g, genericVnfOne, vserverOne);
- rules.addTreeEdge(g, vserverOne, lInterfaceTwo);
+ rules.addTreeEdge(g, vserverOne, lInterfaceTwo);
rules.addTreeEdge(g, lInterfaceTwo, l3Ipv4AddressListThree);
rules.addTreeEdge(g, lInterfaceTwo, l3Ipv6AddressListThree);
rules.addTreeEdge(g, lInterfaceTwo, vlanTwo);
rules.addTreeEdge(g, vlanTwo, l3Ipv4AddressListFour);
rules.addTreeEdge(g, vlanTwo, l3Ipv6AddressListFour);
rules.addEdge(g, vserverOne, pserver);
- rules.addEdge(g, pserver, complex);
-
+ rules.addEdge(g, pserver, complex);
+
rules.addEdge(g, serviceInstanceOne, allottedResource);
rules.addTreeEdge(g, allottedResource, serviceInstanceTwo);
-
+
rules.addEdge(g, serviceInstanceTwo, genericVnfTwo);
rules.addTreeEdge(g, genericVnfTwo, lInterfaceThree);
rules.addTreeEdge(g, lInterfaceThree, l3Ipv4AddressListFive);
rules.addTreeEdge(g, lInterfaceThree, l3Ipv6AddressListFive);
-
+
rules.addTreeEdge(g, lInterfaceThree, vlanThree);
rules.addTreeEdge(g, vlanThree, l3Ipv4AddressListSix);
rules.addTreeEdge(g, vlanThree, l3Ipv6AddressListSix);
-
+
rules.addEdge(g, genericVnfTwo, vserverTwo);
- rules.addTreeEdge(g, vserverTwo, lInterfaceFour);
+ rules.addTreeEdge(g, vserverTwo, lInterfaceFour);
rules.addTreeEdge(g, lInterfaceFour, l3Ipv4AddressListSeven);
rules.addTreeEdge(g, lInterfaceFour, l3Ipv6AddressListSeven);
rules.addTreeEdge(g, lInterfaceFour, vlanFour);
rules.addTreeEdge(g, vlanFour, l3Ipv4AddressListEight);
rules.addTreeEdge(g, vlanFour, l3Ipv6AddressListEight);
-
-
-
-
+
expectedResult.add(serviceInstanceOne);
expectedResult.add(genericVnfOne);
expectedResult.add(lInterfaceOne);
expectedResult.add(l3Ipv4AddressListOne);
expectedResult.add(l3Ipv6AddressListOne);
- expectedResult.add(vlanOne);
+ expectedResult.add(vlanOne);
expectedResult.add(l3Ipv4AddressListTwo);
expectedResult.add(l3Ipv6AddressListTwo);
-
-
+
expectedResult.add(vserverOne);
expectedResult.add(lInterfaceTwo);
expectedResult.add(l3Ipv4AddressListThree);
expectedResult.add(l3Ipv6AddressListThree);
-
+
expectedResult.add(vlanTwo);
expectedResult.add(l3Ipv4AddressListFour);
expectedResult.add(l3Ipv6AddressListFour);
-
+
expectedResult.add(pserver);
expectedResult.add(complex);
-
+
expectedResult.add(allottedResource);
expectedResult.add(serviceInstanceTwo);
expectedResult.add(genericVnfTwo);
expectedResult.add(lInterfaceThree);
expectedResult.add(l3Ipv4AddressListFive);
expectedResult.add(l3Ipv6AddressListFive);
-
+
expectedResult.add(vlanThree);
expectedResult.add(l3Ipv4AddressListSix);
expectedResult.add(l3Ipv6AddressListSix);
-
+
expectedResult.add(vserverTwo);
expectedResult.add(lInterfaceFour);
expectedResult.add(l3Ipv4AddressListSeven);
@@ -180,9 +228,9 @@ public class GetServiceTopologyTest extends TreeQueryTest {
expectedResult.add(vlanFour);
expectedResult.add(l3Ipv4AddressListEight);
expectedResult.add(l3Ipv6AddressListEight);
-
+
}
-
+
@Test
public void run() {
super.run();
@@ -190,31 +238,34 @@ public class GetServiceTopologyTest extends TreeQueryTest {
ArrayList<Vertex> actualResult = new ArrayList<Vertex>();
int i = 1;
do {
- actualResult.addAll(tree.getObjectsAtDepth(i));
- i++;
- } while(!tree.getObjectsAtDepth(i).isEmpty());
-
- assertEquals("result has expected number of values", actualResult.size(), expectedResult.size());
+ actualResult.addAll(tree.getObjectsAtDepth(i));
+ i++;
+ } while (!tree.getObjectsAtDepth(i).isEmpty());
+
+ assertEquals("result has expected number of values", actualResult.size(),
+ expectedResult.size());
int size = actualResult.size() == expectedResult.size() ? expectedResult.size() : 0;
- for(i = 0; i < size; i++) {
- assertTrue("result has node " + expectedResult.get(i), actualResult.contains(expectedResult.get(i)));
+ for (i = 0; i < size; i++) {
+ assertTrue("result has node " + expectedResult.get(i),
+ actualResult.contains(expectedResult.get(i)));
}
-
+
}
@Override
protected String getQueryName() {
- return "getServiceTopology";
+ return "getServiceTopology";
}
@Override
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "service-instance").has("service-instance-id", "service-instance-id-1");
+ g.has("aai-node-type", "service-instance").has("service-instance-id",
+ "service-instance-id-1");
}
@Override
protected void addParam(Map<String, Object> params) {
- return;
+ return;
}
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetTenantInfoAtSvcInstanceQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetTenantInfoAtSvcInstanceQueryTest.java
index 71e2f18..81255b4 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetTenantInfoAtSvcInstanceQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetTenantInfoAtSvcInstanceQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,72 +30,84 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class GetTenantInfoAtSvcInstanceQueryTest extends QueryTest {
- public GetTenantInfoAtSvcInstanceQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public GetTenantInfoAtSvcInstanceQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
-
- Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1");
- Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserver-id-1","vserver-name","vserver-name-1");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "4", "aai-node-type", "tenant", "tenant-id", "tenantid01", "tenant-name", "tenantName01");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1");
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "6", "aai-node-type", "complex", "complex-id", "complex-1");
-
- Vertex serviceInstance1 = graph.addVertex(T.label, "service-instance", T.id, "7", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2");
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-2");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "9", "aai-node-type", "vserver", "vserver-id", "vserver-id-2","vserver-name","vserver-name-2");
- Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "10", "aai-node-type", "tenant", "tenant-id", "tenantid02", "tenant-name", "tenantName02");
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "11", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-2");
- Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "12", "aai-node-type", "complex", "complex-id", "complex-2");
-
-
-
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, serviceInstance, gnvf);
- rules.addEdge(g, gnvf, vserver);
- rules.addTreeEdge(g, vserver,tenant);
- rules.addTreeEdge(g, tenant,cloudregion);
- rules.addEdge(g, cloudregion, complex);
-
- //Not expected in result
- rules.addEdge(g, serviceInstance1, gnvf1);
- rules.addEdge(g, gnvf1, vserver1);
- rules.addTreeEdge(g, vserver1,tenant1);
- rules.addTreeEdge(g, tenant1,cloudregion1);
- rules.addEdge(g, cloudregion1, complex1);
- //Not expected in result
-
- expectedResult.add(serviceInstance);
- expectedResult.add(gnvf);
- expectedResult.add(vserver);
- expectedResult.add(tenant);
- expectedResult.add(cloudregion);
- expectedResult.add(complex);
-
-
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- @Override
- protected String getQueryName() {
- return "getTenantInfoAtSvcInstance";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "service-instance").has("service-instance-id", "service-instance-id-1");
-
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1");
+ Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "4", "aai-node-type", "tenant",
+ "tenant-id", "tenantid01", "tenant-name", "tenantName01");
+ Vertex cloudregion =
+ graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1");
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "6", "aai-node-type", "complex",
+ "complex-id", "complex-1");
+
+ Vertex serviceInstance1 = graph.addVertex(T.label, "service-instance", T.id, "7",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2");
+ Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-2");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "9", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-2", "vserver-name", "vserver-name-2");
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "10", "aai-node-type", "tenant",
+ "tenant-id", "tenantid02", "tenant-name", "tenantName02");
+ Vertex cloudregion1 =
+ graph.addVertex(T.label, "cloud-region", T.id, "11", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-2");
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "12", "aai-node-type",
+ "complex", "complex-id", "complex-2");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, serviceInstance, gnvf);
+ rules.addEdge(g, gnvf, vserver);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addTreeEdge(g, tenant, cloudregion);
+ rules.addEdge(g, cloudregion, complex);
+
+ // Not expected in result
+ rules.addEdge(g, serviceInstance1, gnvf1);
+ rules.addEdge(g, gnvf1, vserver1);
+ rules.addTreeEdge(g, vserver1, tenant1);
+ rules.addTreeEdge(g, tenant1, cloudregion1);
+ rules.addEdge(g, cloudregion1, complex1);
+ // Not expected in result
+
+ expectedResult.add(serviceInstance);
+ expectedResult.add(gnvf);
+ expectedResult.add(vserver);
+ expectedResult.add(tenant);
+ expectedResult.add(cloudregion);
+ expectedResult.add(complex);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "getTenantInfoAtSvcInstance";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "service-instance").has("service-instance-id",
+ "service-instance-id-1");
+
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetTenantInfoAtSvcSubscriptionTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetTenantInfoAtSvcSubscriptionTest.java
index 8ceab5e..2366d10 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetTenantInfoAtSvcSubscriptionTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetTenantInfoAtSvcSubscriptionTest.java
@@ -9,7 +9,7 @@ package org.onap.aai.rest.search;
* 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
+ * 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,
@@ -20,6 +20,7 @@ package org.onap.aai.rest.search;
*/
import java.util.Map;
+
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.T;
@@ -28,62 +29,69 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
+public class GetTenantInfoAtSvcSubscriptionTest extends QueryTest {
+
+ public GetTenantInfoAtSvcSubscriptionTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void test() {
+ super.run();
+ }
-public class GetTenantInfoAtSvcSubscriptionTest extends QueryTest{
-
- public GetTenantInfoAtSvcSubscriptionTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex servicesubscription = graph.addVertex(T.label, "service-subscription", T.id, "0",
+ "aai-node-type", "service-subscription", "service-type", "service-type-0");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "1", "aai-node-type", "tenant",
+ "tenant-id", "tenant-id-0", "tenant-name", "tenant-name-0");
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "2", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloud-owner-0", "cloud-region-id", "cloud-region-id-0");
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-0", "physical-location-type",
+ "physical-location-type-0", "street1", "street1-0", "city", "city-0", "postal-code",
+ "postal-code-0", "country", "country-0", "region", "region-0");
+ Vertex servicesubscription1 = graph.addVertex(T.label, "service-subscription", T.id, "5",
+ "aai-node-type", "service-subscription", "service-type", "service-type-1");
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "6", "aai-node-type", "tenant",
+ "tenant-id", "tenant-id-1", "tenant-name", "tenant-name-1");
+ Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "7", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloud-owner-1", "cloud-region-id", "cloud-region-id-1");
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "8", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-1", "physical-location-type",
+ "physical-location-type-1", "street1", "street1-1", "city", "city-1", "postal-code",
+ "postal-code-1", "country", "country-1", "region", "region-1");
- @Test
- public void test() {
- super.run();
- }
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, servicesubscription, tenant);
+ rules.addTreeEdge(g, tenant, cloudregion);
+ rules.addEdge(g, cloudregion, complex);
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex servicesubscription = graph.addVertex(T.label, "service-subscription",T.id, "0", "aai-node-type", "service-subscription", "service-type", "service-type-0");
- Vertex tenant = graph.addVertex(T.label, "tenant",T.id, "1", "aai-node-type", "tenant", "tenant-id", "tenant-id-0", "tenant-name", "tenant-name-0");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region",T.id, "2", "aai-node-type", "cloud-region", "cloud-owner", "cloud-owner-0", "cloud-region-id", "cloud-region-id-0");
- Vertex complex = graph.addVertex(T.label, "complex",T.id, "3", "aai-node-type", "complex", "physical-location-id", "physical-location-id-0", "physical-location-type",
- "physical-location-type-0", "street1", "street1-0", "city", "city-0", "postal-code", "postal-code-0", "country", "country-0", "region", "region-0");
- Vertex servicesubscription1 = graph.addVertex(T.label, "service-subscription",T.id, "5", "aai-node-type", "service-subscription", "service-type", "service-type-1");
- Vertex tenant1 = graph.addVertex(T.label, "tenant",T.id, "6", "aai-node-type", "tenant", "tenant-id", "tenant-id-1", "tenant-name", "tenant-name-1");
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region",T.id, "7", "aai-node-type", "cloud-region", "cloud-owner", "cloud-owner-1", "cloud-region-id", "cloud-region-id-1");
- Vertex complex1 = graph.addVertex(T.label, "complex",T.id, "8", "aai-node-type", "complex", "physical-location-id", "physical-location-id-1", "physical-location-type",
- "physical-location-type-1", "street1", "street1-1", "city", "city-1", "postal-code", "postal-code-1", "country", "country-1", "region", "region-1");
+ rules.addEdge(g, servicesubscription1, tenant1);
+ rules.addTreeEdge(g, tenant1, cloudregion1);
+ rules.addEdge(g, cloudregion1, complex1);
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, servicesubscription, tenant);
- rules.addTreeEdge(g, tenant, cloudregion);
- rules.addEdge(g, cloudregion, complex);
-
- rules.addEdge(g, servicesubscription1, tenant1);
- rules.addTreeEdge(g, tenant1, cloudregion1);
- rules.addEdge(g, cloudregion1, complex1);
-
-
- expectedResult.add(servicesubscription);
- expectedResult.add(tenant);
- expectedResult.add(cloudregion);
- expectedResult.add(complex);
- }
+ expectedResult.add(servicesubscription);
+ expectedResult.add(tenant);
+ expectedResult.add(cloudregion);
+ expectedResult.add(complex);
+ }
- @Override
- protected String getQueryName() {
- return "getTenantInfoAtSvcSubscription";
- }
+ @Override
+ protected String getQueryName() {
+ return "getTenantInfoAtSvcSubscription";
+ }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "service-subscription").has("service-type", "service-type-0");
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "service-subscription").has("service-type", "service-type-0");
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetVNFVpnBondingServiceDetailsTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetVNFVpnBondingServiceDetailsTest.java
index b859b84..d6e1f54 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetVNFVpnBondingServiceDetailsTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetVNFVpnBondingServiceDetailsTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -27,7 +27,6 @@ import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Ignore;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
@@ -47,39 +46,55 @@ public class GetVNFVpnBondingServiceDetailsTest extends QueryTest {
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
-
-
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "1", "aai-node-type", "vserver", "vserver-name1", "vservername1");
- Vertex linter1 = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id-1", "l-interface-name", "l-interface-name1");
- Vertex linter2 = graph.addVertex(T.label, "l-interface", T.id, "3", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id-2", "l-interface-name", "l-interface-name2");
- Vertex vlan1 = graph.addVertex(T.label, "vlan", T.id, "4", "aai-node-type", "vlan","vlan-interface", "vlan11");
- Vertex config1 = graph.addVertex(T.label, "configuration", T.id, "5", "aai-node-type", "configuration", "configuration-id", "configuration1");
- Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "6", "aai-node-type", "l3-network", "ll3-network-id", "l3-network-id-1", "l3-network-name", "l3-network-name1");
- Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "7", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address-list-id", "l3-interface-ipv4-address-list-id-1", "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
- Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "8", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-1", "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
- Vertex configVpnBinding = graph.addVertex(T.label, "vpn-binding", T.id, "9", "aai-node-type", "vpn-binding",
- "vpn-id", "test-binding-config", "vpn-name", "test");
- Vertex customer = graph.addVertex(T.label, "customer", T.id, "10", "aai-node-type", "customer", "customer-id", "customer-id-1", "customer-name", "customer-name1");
- Vertex subnet1 = graph.addVertex(T.label, "subnet", T.id, "11", "aai-node-type", "subnet", "subnet-id", "subnet-id-11");
- Vertex routeTarget1 = graph.addVertex(T.label, "route-target", T.id, "12", "aai-node-type", "route-target", "global-route-target", "111");
-
+ // Set up the test graph
+
+ Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "1", "aai-node-type", "vserver",
+ "vserver-name1", "vservername1");
+ Vertex linter1 =
+ graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id-1", "l-interface-name", "l-interface-name1");
+ Vertex linter2 =
+ graph.addVertex(T.label, "l-interface", T.id, "3", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id-2", "l-interface-name", "l-interface-name2");
+ Vertex vlan1 = graph.addVertex(T.label, "vlan", T.id, "4", "aai-node-type", "vlan",
+ "vlan-interface", "vlan11");
+ Vertex config1 = graph.addVertex(T.label, "configuration", T.id, "5", "aai-node-type",
+ "configuration", "configuration-id", "configuration1");
+ Vertex l3network1 =
+ graph.addVertex(T.label, "l3-network", T.id, "6", "aai-node-type", "l3-network",
+ "ll3-network-id", "l3-network-id-1", "l3-network-name", "l3-network-name1");
+ Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "7", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address-list-id", "l3-interface-ipv4-address-list-id-1",
+ "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
+ Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "8", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-1",
+ "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
+ Vertex configVpnBinding = graph.addVertex(T.label, "vpn-binding", T.id, "9",
+ "aai-node-type", "vpn-binding", "vpn-id", "test-binding-config", "vpn-name", "test");
+ Vertex customer = graph.addVertex(T.label, "customer", T.id, "10", "aai-node-type",
+ "customer", "customer-id", "customer-id-1", "customer-name", "customer-name1");
+ Vertex subnet1 = graph.addVertex(T.label, "subnet", T.id, "11", "aai-node-type", "subnet",
+ "subnet-id", "subnet-id-11");
+ Vertex routeTarget1 = graph.addVertex(T.label, "route-target", T.id, "12", "aai-node-type",
+ "route-target", "global-route-target", "111");
GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, gnvf1, vserver);//false
- rules.addEdge(g, gnvf1, config1);//false
- rules.addTreeEdge(g, vserver, linter1);//true
- rules.addTreeEdge(g, linter1, linter2);//true
- rules.addTreeEdge(g, linter2, vlan1);//true
- rules.addEdge(g, config1, l3network1 );//false
- rules.addTreeEdge(g, l3network1, subnet1);//true
- rules.addEdge(g, subnet1, l3inter1ipv4addresslist );//false
- rules.addEdge(g, subnet1, l3inter1ipv6addresslist );//false
- rules.addEdge(g, l3network1, configVpnBinding );//false
- rules.addEdge(g, configVpnBinding, customer );//false
- rules.addTreeEdge(g, configVpnBinding, routeTarget1);//true
-
+ rules.addEdge(g, gnvf1, vserver);// false
+ rules.addEdge(g, gnvf1, config1);// false
+ rules.addTreeEdge(g, vserver, linter1);// true
+ rules.addTreeEdge(g, linter1, linter2);// true
+ rules.addTreeEdge(g, linter2, vlan1);// true
+ rules.addEdge(g, config1, l3network1);// false
+ rules.addTreeEdge(g, l3network1, subnet1);// true
+ rules.addEdge(g, subnet1, l3inter1ipv4addresslist);// false
+ rules.addEdge(g, subnet1, l3inter1ipv6addresslist);// false
+ rules.addEdge(g, l3network1, configVpnBinding);// false
+ rules.addEdge(g, configVpnBinding, customer);// false
+ rules.addTreeEdge(g, configVpnBinding, routeTarget1);// true
expectedResult.add(vserver);
expectedResult.add(config1);
@@ -98,13 +113,15 @@ public class GetVNFVpnBondingServiceDetailsTest extends QueryTest {
@Override
protected String getQueryName() {
- return "getVNFVpnBondingServiceDetails";
+ return "getVNFVpnBondingServiceDetails";
}
+
@Override
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
g.has("vnf-name", "vnf-name-1");
}
+
@Override
protected void addParam(Map<String, Object> params) {
params.put("vnf-name", "vnf-name-1");
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetVnfVlanByCircuitIdTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetVnfVlanByCircuitIdTest.java
index 74e4875..861ce57 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetVnfVlanByCircuitIdTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetVnfVlanByCircuitIdTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,64 +26,74 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class GetVnfVlanByCircuitIdTest extends QueryTest {
- public GetVnfVlanByCircuitIdTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
-
- //Set up the test graph
- Vertex logicallink1 = graph.addVertex(T.label, "logical-link", T.id, "1", "aai-node-type", "logical-link", "link-name", "linkName1", "link-type", "linkType1", "circuit-id", "circuitId1");
- Vertex logicallink2 = graph.addVertex(T.label, "logical-link", T.id, "2", "aai-node-type", "logical-link", "link-name", "linkName2", "link-type", "linkType2", "circuit-id", "circuitId2");
-
- Vertex vlan1 = graph.addVertex(T.label, "vlan", T.id, "3", "aai-node-type", "vlan", "vlan-interface", "vlanInterface1");
- Vertex vlan2 = graph.addVertex(T.label, "vlan", T.id, "4", "aai-node-type", "vlan", "vlan-interface", "vlanInterface2");
-
- Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "5", "aai-node-type", "l-interface", "interface-name", "interfaceName1");
- Vertex linterface2 = graph.addVertex(T.label, "l-interface", T.id, "6", "aai-node-type", "l-interface", "interface-name", "interfaceName2");
-
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "7", "aai-node-type", "generic-vnf", "vnf-id", "vnfId1", "vnf-type", "vnfType1");
- Vertex genericvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type", "generic-vnf", "vnf-id", "vnfId2", "vnf-type", "vnfType2");
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addEdge(g, logicallink1, vlan1);
- rules.addTreeEdge(g, vlan1, linterface1);
- rules.addTreeEdge(g, linterface1, genericvnf1);
-
- rules.addEdge(g, logicallink2, vlan2);//false
- rules.addTreeEdge(g, vlan2, linterface2);//false
- rules.addTreeEdge(g, linterface2, genericvnf2);//false
-
- expectedResult.add(logicallink1);
- expectedResult.add(vlan1);
- expectedResult.add(linterface1);
- expectedResult.add(genericvnf1);
-
- }
-
- @Override
- protected String getQueryName() {
- return "getVnfVlanByCircuitId";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("link-name","linkName1");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("circuit-id","circuitId1");
- }
-} \ No newline at end of file
+ public GetVnfVlanByCircuitIdTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+
+ // Set up the test graph
+ Vertex logicallink1 =
+ graph.addVertex(T.label, "logical-link", T.id, "1", "aai-node-type", "logical-link",
+ "link-name", "linkName1", "link-type", "linkType1", "circuit-id", "circuitId1");
+ Vertex logicallink2 =
+ graph.addVertex(T.label, "logical-link", T.id, "2", "aai-node-type", "logical-link",
+ "link-name", "linkName2", "link-type", "linkType2", "circuit-id", "circuitId2");
+
+ Vertex vlan1 = graph.addVertex(T.label, "vlan", T.id, "3", "aai-node-type", "vlan",
+ "vlan-interface", "vlanInterface1");
+ Vertex vlan2 = graph.addVertex(T.label, "vlan", T.id, "4", "aai-node-type", "vlan",
+ "vlan-interface", "vlanInterface2");
+
+ Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "5", "aai-node-type",
+ "l-interface", "interface-name", "interfaceName1");
+ Vertex linterface2 = graph.addVertex(T.label, "l-interface", T.id, "6", "aai-node-type",
+ "l-interface", "interface-name", "interfaceName2");
+
+ Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "7", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfId1", "vnf-type", "vnfType1");
+ Vertex genericvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfId2", "vnf-type", "vnfType2");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addEdge(g, logicallink1, vlan1);
+ rules.addTreeEdge(g, vlan1, linterface1);
+ rules.addTreeEdge(g, linterface1, genericvnf1);
+
+ rules.addEdge(g, logicallink2, vlan2);// false
+ rules.addTreeEdge(g, vlan2, linterface2);// false
+ rules.addTreeEdge(g, linterface2, genericvnf2);// false
+
+ expectedResult.add(logicallink1);
+ expectedResult.add(vlan1);
+ expectedResult.add(linterface1);
+ expectedResult.add(genericvnf1);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "getVnfVlanByCircuitId";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("link-name", "linkName1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("circuit-id", "circuitId1");
+ }
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetVserverDetailTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetVserverDetailTest.java
index 094439b..c6b9239 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetVserverDetailTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetVserverDetailTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -32,91 +32,120 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class GetVserverDetailTest extends QueryTest {
- public GetVserverDetailTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- //set up test graph
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserverid0");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type", "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "2", "aai-node-type", "tenant", "tenant-id", "tenantid0", "tenant-name", "tenantName0");
- Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type", "generic-vnf", "vnf-id", "vnfid0");
- Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "5", "aai-node-type", "vf-module", "vf-module-id", "vfmoduleid0");
- Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "6", "aai-node-type", "service-instance", "service-intsance-id", "serviceinstanceid0");
- Vertex modelver0 = graph.addVertex(T.label, "model-ver", T.id, "7", "aai-node-type", "model-ver", "model-version-id", "modelversionid0");
- Vertex modelver1 = graph.addVertex(T.label, "model-ver", T.id, "8", "aai-node-type", "model-ver", "model-version-id", "modelversionid1");
- Vertex modelver2 = graph.addVertex(T.label, "model-ver", T.id, "9", "aai-node-type", "model-ver", "model-version-id", "modelversionid2");
- Vertex model0 = graph.addVertex(T.label, "model", T.id, "10", "aai-node-type", "model", "model-invariant-id", "modelinvariantid0");
- Vertex model1 = graph.addVertex(T.label, "model", T.id, "11", "aai-node-type", "model", "model-invariant-id", "modelinvariantid1");
- Vertex model2 = graph.addVertex(T.label, "model", T.id, "12", "aai-node-type", "model", "model-invariant-id", "modelinvariantid2");
-
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "13", "aai-node-type", "vserver", "vserver-id", "vserverid1");
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "14", "aai-node-type", "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
- Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "15", "aai-node-type", "tenant", "tenant-id", "tenantid0", "tenant-name", "tenantName0");
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "16", "aai-node-type", "generic-vnf", "vnf-id", "vnfid0");
- Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "17", "aai-node-type", "vf-module", "vf-module-id", "vfmoduleid0");
- Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "18", "aai-node-type", "service-instance", "service-intsance-id", "serviceinstanceid0");
- Vertex modelver3 = graph.addVertex(T.label, "model-ver", T.id, "19", "aai-node-type", "model-ver", "model-version-id", "modelversionid0");
- Vertex modelver4 = graph.addVertex(T.label, "model-ver", T.id, "20", "aai-node-type", "model-ver", "model-version-id", "modelversionid1");
- Vertex modelver5 = graph.addVertex(T.label, "model-ver", T.id, "21", "aai-node-type", "model-ver", "model-version-id", "modelversionid2");
- Vertex model3 = graph.addVertex(T.label, "model", T.id, "22", "aai-node-type", "model", "model-invariant-id", "modelinvariantid0");
- Vertex model4 = graph.addVertex(T.label, "model", T.id, "23", "aai-node-type", "model", "model-invariant-id", "modelinvariantid1");
- Vertex model5 = graph.addVertex(T.label, "model", T.id, "24", "aai-node-type", "model", "model-invariant-id", "modelinvariantid2");
- GraphTraversalSource g = graph.traversal();
-
- rules.addTreeEdge(g, vserver, tenant);
- rules.addTreeEdge(g, tenant, cloudregion);
- rules.addEdge(g, vserver, genericvnf);
- rules.addPrivateEdge(g, genericvnf, modelver0, null);
- rules.addTreeEdge(g, modelver0, model0);
- rules.addTreeEdge(g, genericvnf, vfmodule);
- rules.addPrivateEdge(g, vfmodule, modelver1, null);
- rules.addTreeEdge(g, modelver1, model1);
- rules.addEdge(g, genericvnf, serviceinstance);
- rules.addPrivateEdge(g, serviceinstance, modelver2, null);
- rules.addTreeEdge(g, modelver2, model2);
-
- rules.addTreeEdge(g, vserver1, tenant1);//false
- rules.addTreeEdge(g, tenant1, cloudregion1);//false
- rules.addEdge(g, vserver1, genericvnf1);//false
- rules.addPrivateEdge(g, genericvnf1, modelver3, null);//false
- rules.addTreeEdge(g, modelver3, model3);//false
- rules.addTreeEdge(g, genericvnf1, vfmodule1);//false
- rules.addPrivateEdge(g, vfmodule1, modelver4, null);//false
- rules.addTreeEdge(g, modelver4, model4);//false
- rules.addEdge(g, genericvnf1, serviceinstance1);
- rules.addPrivateEdge(g, serviceinstance1, modelver5, null);//false
- rules.addTreeEdge(g, modelver5, model5);//false
-
- expectedResult.add(vserver);
- expectedResult.add(tenant);
- expectedResult.add(cloudregion);
- expectedResult.add(genericvnf);
- expectedResult.add(modelver0);
- expectedResult.add(model0);
- expectedResult.add(vfmodule);
- expectedResult.add(modelver1);
- expectedResult.add(model1);
- expectedResult.add(serviceinstance);
- expectedResult.add(modelver2);
- expectedResult.add(model2);
- }
- @Override
- protected String getQueryName() {
- return "getVserverDetail";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "vserver").has("vserver-id", "vserverid0");
- }
+ public GetVserverDetailTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
-} \ No newline at end of file
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException,
+ EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+ // set up test graph
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver",
+ "vserver-id", "vserverid0");
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "2", "aai-node-type", "tenant",
+ "tenant-id", "tenantid0", "tenant-name", "tenantName0");
+ Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid0");
+ Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "5", "aai-node-type",
+ "vf-module", "vf-module-id", "vfmoduleid0");
+ Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "6",
+ "aai-node-type", "service-instance", "service-intsance-id", "serviceinstanceid0");
+ Vertex modelver0 = graph.addVertex(T.label, "model-ver", T.id, "7", "aai-node-type",
+ "model-ver", "model-version-id", "modelversionid0");
+ Vertex modelver1 = graph.addVertex(T.label, "model-ver", T.id, "8", "aai-node-type",
+ "model-ver", "model-version-id", "modelversionid1");
+ Vertex modelver2 = graph.addVertex(T.label, "model-ver", T.id, "9", "aai-node-type",
+ "model-ver", "model-version-id", "modelversionid2");
+ Vertex model0 = graph.addVertex(T.label, "model", T.id, "10", "aai-node-type", "model",
+ "model-invariant-id", "modelinvariantid0");
+ Vertex model1 = graph.addVertex(T.label, "model", T.id, "11", "aai-node-type", "model",
+ "model-invariant-id", "modelinvariantid1");
+ Vertex model2 = graph.addVertex(T.label, "model", T.id, "12", "aai-node-type", "model",
+ "model-invariant-id", "modelinvariantid2");
+
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "13", "aai-node-type",
+ "vserver", "vserver-id", "vserverid1");
+ Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "14", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "15", "aai-node-type", "tenant",
+ "tenant-id", "tenantid0", "tenant-name", "tenantName0");
+ Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "16", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid0");
+ Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "17", "aai-node-type",
+ "vf-module", "vf-module-id", "vfmoduleid0");
+ Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "18",
+ "aai-node-type", "service-instance", "service-intsance-id", "serviceinstanceid0");
+ Vertex modelver3 = graph.addVertex(T.label, "model-ver", T.id, "19", "aai-node-type",
+ "model-ver", "model-version-id", "modelversionid0");
+ Vertex modelver4 = graph.addVertex(T.label, "model-ver", T.id, "20", "aai-node-type",
+ "model-ver", "model-version-id", "modelversionid1");
+ Vertex modelver5 = graph.addVertex(T.label, "model-ver", T.id, "21", "aai-node-type",
+ "model-ver", "model-version-id", "modelversionid2");
+ Vertex model3 = graph.addVertex(T.label, "model", T.id, "22", "aai-node-type", "model",
+ "model-invariant-id", "modelinvariantid0");
+ Vertex model4 = graph.addVertex(T.label, "model", T.id, "23", "aai-node-type", "model",
+ "model-invariant-id", "modelinvariantid1");
+ Vertex model5 = graph.addVertex(T.label, "model", T.id, "24", "aai-node-type", "model",
+ "model-invariant-id", "modelinvariantid2");
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addTreeEdge(g, tenant, cloudregion);
+ rules.addEdge(g, vserver, genericvnf);
+ rules.addPrivateEdge(g, genericvnf, modelver0, null);
+ rules.addTreeEdge(g, modelver0, model0);
+ rules.addTreeEdge(g, genericvnf, vfmodule);
+ rules.addPrivateEdge(g, vfmodule, modelver1, null);
+ rules.addTreeEdge(g, modelver1, model1);
+ rules.addEdge(g, genericvnf, serviceinstance);
+ rules.addPrivateEdge(g, serviceinstance, modelver2, null);
+ rules.addTreeEdge(g, modelver2, model2);
+
+ rules.addTreeEdge(g, vserver1, tenant1);// false
+ rules.addTreeEdge(g, tenant1, cloudregion1);// false
+ rules.addEdge(g, vserver1, genericvnf1);// false
+ rules.addPrivateEdge(g, genericvnf1, modelver3, null);// false
+ rules.addTreeEdge(g, modelver3, model3);// false
+ rules.addTreeEdge(g, genericvnf1, vfmodule1);// false
+ rules.addPrivateEdge(g, vfmodule1, modelver4, null);// false
+ rules.addTreeEdge(g, modelver4, model4);// false
+ rules.addEdge(g, genericvnf1, serviceinstance1);
+ rules.addPrivateEdge(g, serviceinstance1, modelver5, null);// false
+ rules.addTreeEdge(g, modelver5, model5);// false
+
+ expectedResult.add(vserver);
+ expectedResult.add(tenant);
+ expectedResult.add(cloudregion);
+ expectedResult.add(genericvnf);
+ expectedResult.add(modelver0);
+ expectedResult.add(model0);
+ expectedResult.add(vfmodule);
+ expectedResult.add(modelver1);
+ expectedResult.add(model1);
+ expectedResult.add(serviceinstance);
+ expectedResult.add(modelver2);
+ expectedResult.add(model2);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "getVserverDetail";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "vserver").has("vserver-id", "vserverid0");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetWlBundleIdQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetWlBundleIdQueryTest.java
index 2831315..f2b0a2e 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GetWlBundleIdQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GetWlBundleIdQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,71 +30,83 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class GetWlBundleIdQueryTest extends QueryTest {
- public GetWlBundleIdQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public GetWlBundleIdQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
-
-
- Vertex lagLink = graph.addVertex(T.label, "lag-link", T.id, "1", "aai-node-type", "lag-link", "lag-link-id", "lag-link-id-1","link-name", "link-name-1");
- Vertex logicalLink = graph.addVertex(T.label, "logical-link", T.id, "2", "aai-node-type", "logical-link", "logical-link-id", "logical-link-id-1");
- Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "3", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1");
- Vertex serviceSubcription = graph.addVertex(T.label, "service-subscription", T.id, "4", "aai-node-type", "service-subscription", "service-subscription-id", "service-subscription-id-1");
- Vertex customer = graph.addVertex(T.label, "customer", T.id, "5", "aai-node-type", "customer", "customer-id", "customer-id-1");
- Vertex logicalLink1 = graph.addVertex(T.label, "logical-link", T.id, "6", "aai-node-type", "logical-link", "logical-link-id", "logical-link-id-2");
-
- Vertex lagLink1 = graph.addVertex(T.label, "lag-link", T.id, "7", "aai-node-type", "lag-link", "lag-link-id", "lag-link-id-2","link-name", "link-name-2");
- Vertex logicalLink2 = graph.addVertex(T.label, "logical-link", T.id, "8", "aai-node-type", "logical-link", "logical-link-id", "logical-link-id-3");
- Vertex serviceInstance1 = graph.addVertex(T.label, "service-instance", T.id, "9", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2");
- Vertex serviceSubcription1 = graph.addVertex(T.label, "service-subscription", T.id, "10", "aai-node-type", "service-subscription", "service-subscription-id", "service-subscription-id-2");
- Vertex customer1 = graph.addVertex(T.label, "customer", T.id, "11", "aai-node-type", "customer", "customer-id", "customer-id-2");
- Vertex logicalLink3 = graph.addVertex(T.label, "logical-link", T.id, "12", "aai-node-type", "logical-link", "logical-link-id", "logical-link-id-4");
-
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, lagLink, logicalLink);
- rules.addEdge(g, logicalLink, serviceInstance);
- rules.addTreeEdge(g, serviceInstance,serviceSubcription);
- rules.addTreeEdge(g, serviceSubcription,customer);
- rules.addEdge(g, logicalLink, logicalLink1);
-
- //Not expected in result
- rules.addEdge(g, lagLink1, logicalLink2);
- rules.addEdge(g, logicalLink2, serviceInstance1);
- rules.addTreeEdge(g, serviceInstance1,serviceSubcription1);
- rules.addTreeEdge(g, serviceSubcription1,customer1);
- rules.addEdge(g, logicalLink2, logicalLink3);
- //Not expected in result
-
- expectedResult.add(lagLink);
- expectedResult.add(logicalLink);
- expectedResult.add(serviceInstance);
- expectedResult.add(serviceSubcription);
- expectedResult.add(customer);
- expectedResult.add(logicalLink1);
-
-
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- @Override
- protected String getQueryName() {
- return "getWlBundleId";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "lag-link").has("link-name", "link-name-1");
-
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ Vertex lagLink = graph.addVertex(T.label, "lag-link", T.id, "1", "aai-node-type",
+ "lag-link", "lag-link-id", "lag-link-id-1", "link-name", "link-name-1");
+ Vertex logicalLink = graph.addVertex(T.label, "logical-link", T.id, "2", "aai-node-type",
+ "logical-link", "logical-link-id", "logical-link-id-1");
+ Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "3",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1");
+ Vertex serviceSubcription =
+ graph.addVertex(T.label, "service-subscription", T.id, "4", "aai-node-type",
+ "service-subscription", "service-subscription-id", "service-subscription-id-1");
+ Vertex customer = graph.addVertex(T.label, "customer", T.id, "5", "aai-node-type",
+ "customer", "customer-id", "customer-id-1");
+ Vertex logicalLink1 = graph.addVertex(T.label, "logical-link", T.id, "6", "aai-node-type",
+ "logical-link", "logical-link-id", "logical-link-id-2");
+
+ Vertex lagLink1 = graph.addVertex(T.label, "lag-link", T.id, "7", "aai-node-type",
+ "lag-link", "lag-link-id", "lag-link-id-2", "link-name", "link-name-2");
+ Vertex logicalLink2 = graph.addVertex(T.label, "logical-link", T.id, "8", "aai-node-type",
+ "logical-link", "logical-link-id", "logical-link-id-3");
+ Vertex serviceInstance1 = graph.addVertex(T.label, "service-instance", T.id, "9",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2");
+ Vertex serviceSubcription1 =
+ graph.addVertex(T.label, "service-subscription", T.id, "10", "aai-node-type",
+ "service-subscription", "service-subscription-id", "service-subscription-id-2");
+ Vertex customer1 = graph.addVertex(T.label, "customer", T.id, "11", "aai-node-type",
+ "customer", "customer-id", "customer-id-2");
+ Vertex logicalLink3 = graph.addVertex(T.label, "logical-link", T.id, "12", "aai-node-type",
+ "logical-link", "logical-link-id", "logical-link-id-4");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, lagLink, logicalLink);
+ rules.addEdge(g, logicalLink, serviceInstance);
+ rules.addTreeEdge(g, serviceInstance, serviceSubcription);
+ rules.addTreeEdge(g, serviceSubcription, customer);
+ rules.addEdge(g, logicalLink, logicalLink1);
+
+ // Not expected in result
+ rules.addEdge(g, lagLink1, logicalLink2);
+ rules.addEdge(g, logicalLink2, serviceInstance1);
+ rules.addTreeEdge(g, serviceInstance1, serviceSubcription1);
+ rules.addTreeEdge(g, serviceSubcription1, customer1);
+ rules.addEdge(g, logicalLink2, logicalLink3);
+ // Not expected in result
+
+ expectedResult.add(lagLink);
+ expectedResult.add(logicalLink);
+ expectedResult.add(serviceInstance);
+ expectedResult.add(serviceSubcription);
+ expectedResult.add(customer);
+ expectedResult.add(logicalLink1);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "getWlBundleId";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "lag-link").has("link-name", "link-name-1");
+
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GfpVserverDataQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GfpVserverDataQueryTest.java
index 8724785..49f41f5 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GfpVserverDataQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GfpVserverDataQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,58 +26,72 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class GfpVserverDataQueryTest extends QueryTest {
- public GfpVserverDataQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //set up test graph
- Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf", "vnf-id", "vnfid0", "nf-type", "sample-nf-type");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type", "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "2", "aai-node-type", "tenant", "tenant-id", "tenantid0", "tenant-name", "tenantName0");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserverid0");
- Vertex linterface = graph.addVertex(T.label, "l-interface", T.id, "4", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0");
- Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "5", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "l3-interface-ipv4-address-0");
- Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "8", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "l3-interface-ipv6-address-0");
- Vertex vlan = graph.addVertex(T.label, "vlan", T.id, "9", "aai-node-type", "vlan", "vlan-interface", "vlan-interface0");
- Vertex sriovVf = graph.addVertex(T.label, "sriov-vf", T.id, "10", "aai-node-type", "sriov-vf", "pci-id", "pci-id0");
-
- GraphTraversalSource g = graph.traversal();
-
-
- rules.addTreeEdge(g, tenant, cloudregion);
- rules.addTreeEdge(g, vserver, tenant);
- rules.addEdge(g, genericvnf, vserver);
- rules.addTreeEdge(g, linterface, vserver);
- rules.addTreeEdge(g, l3inter1ipv4addresslist, linterface);
+ public GfpVserverDataQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // set up test graph
+ Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid0", "nf-type", "sample-nf-type");
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "2", "aai-node-type", "tenant",
+ "tenant-id", "tenantid0", "tenant-name", "tenantName0");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver",
+ "vserver-id", "vserverid0");
+ Vertex linterface =
+ graph.addVertex(T.label, "l-interface", T.id, "4", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0");
+ Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "5", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-0");
+ Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "8", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-0");
+ Vertex vlan = graph.addVertex(T.label, "vlan", T.id, "9", "aai-node-type", "vlan",
+ "vlan-interface", "vlan-interface0");
+ Vertex sriovVf = graph.addVertex(T.label, "sriov-vf", T.id, "10", "aai-node-type",
+ "sriov-vf", "pci-id", "pci-id0");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addTreeEdge(g, tenant, cloudregion);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addEdge(g, genericvnf, vserver);
+ rules.addTreeEdge(g, linterface, vserver);
+ rules.addTreeEdge(g, l3inter1ipv4addresslist, linterface);
rules.addTreeEdge(g, l3inter1ipv6addresslist, linterface);
rules.addTreeEdge(g, vlan, linterface);
rules.addTreeEdge(g, sriovVf, linterface);
-
- expectedResult.add(l3inter1ipv4addresslist);
- expectedResult.add(l3inter1ipv6addresslist);
- expectedResult.add(vlan);
- }
- @Override
- protected String getQueryName() {
- return "gfp-vserver-data";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "vserver");
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
-} \ No newline at end of file
+ expectedResult.add(l3inter1ipv4addresslist);
+ expectedResult.add(l3inter1ipv6addresslist);
+ expectedResult.add(vlan);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "gfp-vserver-data";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "vserver");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GfpVserverQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GfpVserverQueryTest.java
index 286319f..e287f40 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GfpVserverQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GfpVserverQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,44 +26,52 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class GfpVserverQueryTest extends QueryTest {
- public GfpVserverQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //set up test graph
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type", "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "2", "aai-node-type", "tenant", "tenant-id", "tenantid0", "tenant-name", "tenantName0");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserverid0");
- Vertex linterface = graph.addVertex(T.label, "l-interface", T.id, "4", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0");
- GraphTraversalSource g = graph.traversal();
-
- rules.addTreeEdge(g, tenant, cloudregion);
- rules.addTreeEdge(g, vserver, tenant);
- rules.addTreeEdge(g, linterface, vserver);
-
- expectedResult.add(vserver);
- }
- @Override
- protected String getQueryName() {
- return "gfp-vserver";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "vserver");
- }
+ public GfpVserverQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // set up test graph
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "2", "aai-node-type", "tenant",
+ "tenant-id", "tenantid0", "tenant-name", "tenantName0");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver",
+ "vserver-id", "vserverid0");
+ Vertex linterface =
+ graph.addVertex(T.label, "l-interface", T.id, "4", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0");
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addTreeEdge(g, tenant, cloudregion);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addTreeEdge(g, linterface, vserver);
+
+ expectedResult.add(vserver);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "gfp-vserver";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "vserver");
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
-} \ No newline at end of file
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/GroovyShellImplTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/GroovyShellImplTest.java
index b489a83..b7291d6 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/GroovyShellImplTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/GroovyShellImplTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,7 +19,17 @@
*/
package org.onap.aai.rest.search;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
import groovy.lang.MissingPropertyException;
+
+import java.net.URI;
+import java.util.*;
+
+import javax.ws.rs.core.*;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Before;
@@ -33,17 +43,9 @@ import org.onap.aai.serialization.engines.QueryStyle;
import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.setup.SchemaVersion;
-import javax.ws.rs.core.*;
-import java.net.URI;
-import java.util.*;
+public class GroovyShellImplTest extends AAISetup {
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class GroovyShellImplTest extends AAISetup{
-
- GroovyShellImpl groovyShellImpl ;
+ GroovyShellImpl groovyShellImpl;
protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
@@ -78,11 +80,11 @@ public class GroovyShellImplTest extends AAISetup{
public void setup() {
version = schemaVersions.getDefaultVersion();
- httpHeaders = mock(HttpHeaders.class);
- uriInfo = mock(UriInfo.class);
+ httpHeaders = mock(HttpHeaders.class);
+ uriInfo = mock(UriInfo.class);
- headersMultiMap = new MultivaluedHashMap<>();
- queryParameters = Mockito.spy(new MultivaluedHashMap<>());
+ headersMultiMap = new MultivaluedHashMap<>();
+ queryParameters = Mockito.spy(new MultivaluedHashMap<>());
headersMultiMap.add("X-FromAppId", "JUNIT");
headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
@@ -103,19 +105,18 @@ public class GroovyShellImplTest extends AAISetup{
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
+ // 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);
loader = loaderFactory.createLoaderForVersion(introspectorFactoryType, version);
- dbEngine = new JanusGraphDBEngine(
- queryStyle,
- loader);
- GenericQueryProcessor.Builder builder = new GenericQueryProcessor.Builder(dbEngine, gremlinServerSingleton);
+ dbEngine = new JanusGraphDBEngine(queryStyle, loader);
+ GenericQueryProcessor.Builder builder =
+ new GenericQueryProcessor.Builder(dbEngine, gremlinServerSingleton);
builder.queryFrom(URI.create("te"));
builder.queryFrom("te", "gremlin");
builder.create();
@@ -130,7 +131,8 @@ public class GroovyShellImplTest extends AAISetup{
GraphTraversal<Vertex, Vertex> g = Mockito.mock(GraphTraversal.class);
g.has("cloud-region-id", "cloud-region-id-1");
Map<String, Object> params = new HashMap<>();
- groovyShellImpl.runQuery("vnfs-fromServiceInstance", params, dbEngine.asAdmin().getTraversalSource());
+ groovyShellImpl.runQuery("vnfs-fromServiceInstance", params,
+ dbEngine.asAdmin().getTraversalSource());
}
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/ImageFromCloudRegionNfTypeTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/ImageFromCloudRegionNfTypeTest.java
index 04f4433..7ea2678 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/ImageFromCloudRegionNfTypeTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/ImageFromCloudRegionNfTypeTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -31,78 +31,99 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class ImageFromCloudRegionNfTypeTest extends QueryTest {
- public ImageFromCloudRegionNfTypeTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "10", "aai-node-type", "cloud-region", "cloud-region-id", "cloudreg1", "cloud-region-owner", "cloudOwnername00");
- Vertex cloudregion2 = graph.addVertex(T.label, "cloud-region", T.id, "11", "aai-node-type", "cloud-region", "cloud-region-id", "cloudregWrong", "cloud-region-owner", "cloudOwnername01");
-
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "20", "aai-node-type", "generic-vnf", "vnf-id", "genvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
- Vertex genericvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "21", "aai-node-type", "generic-vnf", "vnf-id", "genvnf2", "vnf-name", "genvnfname2", "nf-type", "wrong-nf-type");
- Vertex genericvnf3 = graph.addVertex(T.label, "generic-vnf", T.id, "22", "aai-node-type", "generic-vnf", "vnf-id", "genvnf3", "vnf-name", "genvnfname3", "nf-type", "sample-nf-type");
-
- Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "30", "aai-node-type", "tenant", "tenant-id", "tenantid01", "tenant-name", "tenantName01");
- Vertex tenant2 = graph.addVertex(T.label, "tenant", T.id, "31", "aai-node-type", "tenant", "tenant-id", "tenantid02", "tenant-name", "tenantName02");
-
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "40", "aai-node-type", "vserver", "vserver-id", "vserverid01");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "41", "aai-node-type", "vserver", "vserver-id", "vserverid02");
- Vertex vserver3 = graph.addVertex(T.label, "vserver", T.id, "42", "aai-node-type", "vserver", "vserver-id", "vserverid03");
- Vertex vserver4 = graph.addVertex(T.label, "vserver", T.id, "43", "aai-node-type", "vserver", "vserver-id", "vserverid04");
- Vertex vserver5 = graph.addVertex(T.label, "vserver", T.id, "44", "aai-node-type", "vserver", "vserver-id", "vserverid05");
-
- Vertex image1 = graph.addVertex(T.label, "image", T.id, "50", "aai-node-type", "image",
- "image-id", "image1", "image-name", "imageName1", "image-os-distro", "boopOS", "image-os-version", "1.0", "image-selflink", "self/link");
- Vertex image2 = graph.addVertex(T.label, "image", T.id, "51", "aai-node-type", "image",
- "image-id", "image2", "image-name", "imageName2", "image-os-distro", "beepOS", "image-os-version", "1.0", "image-selflink", "self/link");
- Vertex image3 = graph.addVertex(T.label, "image", T.id, "52", "aai-node-type", "image",
- "image-id", "image3", "image-name", "imageName3", "image-os-distro", "beepOS", "image-os-version", "1.1", "image-selflink", "self/link");
- Vertex image4 = graph.addVertex(T.label, "image", T.id, "53", "aai-node-type", "image",
- "image-id", "image4", "image-name", "imageName4", "image-os-distro", "beepOS", "image-os-version", "1.1", "image-selflink", "self/link");
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addTreeEdge(g, cloudregion1, tenant1);
- rules.addTreeEdge(g, cloudregion2, tenant2);
- rules.addTreeEdge(g, tenant1, vserver1);
- rules.addTreeEdge(g, tenant1, vserver2);
- rules.addTreeEdge(g, tenant2, vserver3);
- rules.addTreeEdge(g, tenant1, vserver4);
- rules.addTreeEdge(g, tenant1, vserver5);
- rules.addEdge(g, vserver1, image1);
- rules.addEdge(g, vserver2, image2);
- rules.addEdge(g, vserver3, image3);
- rules.addEdge(g, vserver4, image4);
- rules.addEdge(g, vserver5, image1);
- rules.addEdge(g, genericvnf1, vserver1);
- rules.addEdge(g, genericvnf2, vserver2);
- rules.addEdge(g, genericvnf1, vserver3);
- rules.addEdge(g, genericvnf3, vserver4);
-
- expectedResult.add(image1);
- expectedResult.add(image4);
- }
-
- @Override
- protected String getQueryName() {
- return "images-fromCloudRegionNfType";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type","cloud-region").has("cloud-region-id","cloudreg1");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("nfType", "sample-nf-type");
- }
+ public ImageFromCloudRegionNfTypeTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex cloudregion1 =
+ graph.addVertex(T.label, "cloud-region", T.id, "10", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloudreg1", "cloud-region-owner", "cloudOwnername00");
+ Vertex cloudregion2 =
+ graph.addVertex(T.label, "cloud-region", T.id, "11", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloudregWrong", "cloud-region-owner", "cloudOwnername01");
+
+ Vertex genericvnf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "20", "aai-node-type", "generic-vnf",
+ "vnf-id", "genvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
+ Vertex genericvnf2 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "21", "aai-node-type", "generic-vnf",
+ "vnf-id", "genvnf2", "vnf-name", "genvnfname2", "nf-type", "wrong-nf-type");
+ Vertex genericvnf3 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "22", "aai-node-type", "generic-vnf",
+ "vnf-id", "genvnf3", "vnf-name", "genvnfname3", "nf-type", "sample-nf-type");
+
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "30", "aai-node-type", "tenant",
+ "tenant-id", "tenantid01", "tenant-name", "tenantName01");
+ Vertex tenant2 = graph.addVertex(T.label, "tenant", T.id, "31", "aai-node-type", "tenant",
+ "tenant-id", "tenantid02", "tenant-name", "tenantName02");
+
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "40", "aai-node-type",
+ "vserver", "vserver-id", "vserverid01");
+ Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "41", "aai-node-type",
+ "vserver", "vserver-id", "vserverid02");
+ Vertex vserver3 = graph.addVertex(T.label, "vserver", T.id, "42", "aai-node-type",
+ "vserver", "vserver-id", "vserverid03");
+ Vertex vserver4 = graph.addVertex(T.label, "vserver", T.id, "43", "aai-node-type",
+ "vserver", "vserver-id", "vserverid04");
+ Vertex vserver5 = graph.addVertex(T.label, "vserver", T.id, "44", "aai-node-type",
+ "vserver", "vserver-id", "vserverid05");
+
+ Vertex image1 = graph.addVertex(T.label, "image", T.id, "50", "aai-node-type", "image",
+ "image-id", "image1", "image-name", "imageName1", "image-os-distro", "boopOS",
+ "image-os-version", "1.0", "image-selflink", "self/link");
+ Vertex image2 = graph.addVertex(T.label, "image", T.id, "51", "aai-node-type", "image",
+ "image-id", "image2", "image-name", "imageName2", "image-os-distro", "beepOS",
+ "image-os-version", "1.0", "image-selflink", "self/link");
+ Vertex image3 = graph.addVertex(T.label, "image", T.id, "52", "aai-node-type", "image",
+ "image-id", "image3", "image-name", "imageName3", "image-os-distro", "beepOS",
+ "image-os-version", "1.1", "image-selflink", "self/link");
+ Vertex image4 = graph.addVertex(T.label, "image", T.id, "53", "aai-node-type", "image",
+ "image-id", "image4", "image-name", "imageName4", "image-os-distro", "beepOS",
+ "image-os-version", "1.1", "image-selflink", "self/link");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addTreeEdge(g, cloudregion1, tenant1);
+ rules.addTreeEdge(g, cloudregion2, tenant2);
+ rules.addTreeEdge(g, tenant1, vserver1);
+ rules.addTreeEdge(g, tenant1, vserver2);
+ rules.addTreeEdge(g, tenant2, vserver3);
+ rules.addTreeEdge(g, tenant1, vserver4);
+ rules.addTreeEdge(g, tenant1, vserver5);
+ rules.addEdge(g, vserver1, image1);
+ rules.addEdge(g, vserver2, image2);
+ rules.addEdge(g, vserver3, image3);
+ rules.addEdge(g, vserver4, image4);
+ rules.addEdge(g, vserver5, image1);
+ rules.addEdge(g, genericvnf1, vserver1);
+ rules.addEdge(g, genericvnf2, vserver2);
+ rules.addEdge(g, genericvnf1, vserver3);
+ rules.addEdge(g, genericvnf3, vserver4);
+
+ expectedResult.add(image1);
+ expectedResult.add(image4);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "images-fromCloudRegionNfType";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "cloud-region").has("cloud-region-id", "cloudreg1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("nfType", "sample-nf-type");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/InstanceGroupsByCloudRegionQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/InstanceGroupsByCloudRegionQueryTest.java
index 0dbb911..2cf93b7 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/InstanceGroupsByCloudRegionQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/InstanceGroupsByCloudRegionQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -31,48 +31,60 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class InstanceGroupsByCloudRegionQueryTest extends QueryTest {
- public InstanceGroupsByCloudRegionQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public InstanceGroupsByCloudRegionQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void test() {
- super.run();
- }
+ @Test
+ public void test() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-0", "cloud-region-owner", "cloud-owner-name-0","cloud-region-version","cloud-region-version-0");
- Vertex instancegroup = graph.addVertex(T.label, "instance-group", T.id, "2", "aai-node-type", "instance-group", "id", "id-0", "instance-group-type", "instance-group-type-0","instance-group-role","instance-group-role-0","instance-group-function","instance-group-function-0","instance-group-description","instance-group-description-0");
-
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1","cloud-region-version","cloud-region-version-1");
- Vertex instancegroup1 = graph.addVertex(T.label, "instance-group", T.id, "4", "aai-node-type", "instance-group", "id", "id-1", "instance-group-type", "instance-group-type-1","instance-group-role","instance-group-role-1","instance-group-function","instance-group-function-1","instance-group-description","instance-group-description-1");
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region-id-0", "cloud-region-owner",
+ "cloud-owner-name-0", "cloud-region-version", "cloud-region-version-0");
+ Vertex instancegroup =
+ graph.addVertex(T.label, "instance-group", T.id, "2", "aai-node-type", "instance-group",
+ "id", "id-0", "instance-group-type", "instance-group-type-0", "instance-group-role",
+ "instance-group-role-0", "instance-group-function", "instance-group-function-0",
+ "instance-group-description", "instance-group-description-0");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, cloudregion, instancegroup);
-
- rules.addEdge(g, cloudregion1, instancegroup1); //false
-
- expectedResult.add(instancegroup);
- }
+ Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner",
+ "cloud-owner-name-1", "cloud-region-version", "cloud-region-version-1");
+ Vertex instancegroup1 =
+ graph.addVertex(T.label, "instance-group", T.id, "4", "aai-node-type", "instance-group",
+ "id", "id-1", "instance-group-type", "instance-group-type-1", "instance-group-role",
+ "instance-group-role-1", "instance-group-function", "instance-group-function-1",
+ "instance-group-description", "instance-group-description-1");
- @Override
- protected String getQueryName() {
- return "instance-groups-byCloudRegion";
- }
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, cloudregion, instancegroup);
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "cloud-region").has("cloud-region-owner", "cloud-owner-name-0").has("cloud-region-id", "cloud-region-id-0");
- }
+ rules.addEdge(g, cloudregion1, instancegroup1); // false
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("role", "instance-group-role-0");
- params.put("type", "instance-group-type-0");
- params.put("function", "instance-group-function-0");
- }
+ expectedResult.add(instancegroup);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "instance-groups-byCloudRegion";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "cloud-region").has("cloud-region-owner", "cloud-owner-name-0")
+ .has("cloud-region-id", "cloud-region-id-0");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("role", "instance-group-role-0");
+ params.put("type", "instance-group-type-0");
+ params.put("function", "instance-group-function-0");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/IpsNetworksFromVnfTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/IpsNetworksFromVnfTest.java
index 0d26300..c9c76e6 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/IpsNetworksFromVnfTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/IpsNetworksFromVnfTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -25,177 +25,223 @@ 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.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.junit.Test;
import org.junit.Ignore;
+import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class IpsNetworksFromVnfTest extends QueryTest {
- public IpsNetworksFromVnfTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Ignore
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex genericVnf = graph.addVertex(T.label, "generic-vnf",T.id, "0", "aai-node-type", "generic-vnf", "generic-vnf-id", "serviceinstanceid0");
- Vertex vnfc = graph.addVertex(T.label, "vnfc",T.id, "1", "aai-node-type", "vnfc","vnfc-id", "vnfcId1");
- Vertex cp = graph.addVertex(T.label, "cp",T.id, "30", "aai-node-type", "cp","cp-id", "cpId1");
- Vertex vipIpv4AddressList = graph.addVertex(T.label, "vip-ipv4-address-list",T.id, "2", "aai-node-type", "vip-ipv4-address-list","vip-ipv4-address-list-id", "vip-ipv4-address-listId2");
- Vertex vipIpv6AddressList = graph.addVertex(T.label, "vip-ipv6-address-list",T.id, "3", "aai-node-type", "vip-ipv6-address-list","vip-ipv6-address-list-id", "vip-ipv6-address-listId3");
-
-
- Vertex subnetIpv4 = graph.addVertex(T.label, "subnet",T.id, "7", "aai-node-type", "subnet","subnet-id", "subnetId7");
- Vertex l3Network1Ipv4 = graph.addVertex(T.label, "l3-network",T.id, "8", "aai-node-type", "l3-network","l3-network-id", "l3-networkId8");
-
- Vertex subnetIpv6 = graph.addVertex(T.label, "subnet",T.id, "10", "aai-node-type", "subnet","subnet-id", "subnetId10");
- Vertex l3Network1Ipv6 = graph.addVertex(T.label, "l3-network",T.id, "11", "aai-node-type", "l3-network","l3-network-id", "l3-networkId11");
-
- Vertex vserver = graph.addVertex(T.label, "vserver",T.id, "18", "aai-node-type", "vserver","vserver-id", "vserverId18");
- Vertex linterface = graph.addVertex(T.label, "l-interface",T.id, "19", "aai-node-type", "l-interface","l-interface-id", "l-interfaceId19");
- Vertex pserver = graph.addVertex(T.label, "pserver",T.id, "20", "aai-node-type", "pserver","pserver-id", "pserverId20");
-
-
- Vertex l3NetworklintIpv4 = graph.addVertex(T.label, "l3-network",T.id, "21", "aai-node-type", "l3-network","l3-network-id", "l3-networkId21");
- Vertex subnetlintIpv4 = graph.addVertex(T.label, "subnet",T.id, "22", "aai-node-type", "subnet","subnet-id", "subnetId22");
- Vertex l3Network1lintIpv4 = graph.addVertex(T.label, "l3-network",T.id, "23", "aai-node-type", "l3-network","l3-network-id", "l3-networkId23");
-
- Vertex l3NetworklintIpv6 = graph.addVertex(T.label, "l3-network",T.id, "24", "aai-node-type", "l3-network","l3-network-id", "l3-networkId24");
- Vertex subnetlintIpv6 = graph.addVertex(T.label, "subnet",T.id, "25", "aai-node-type", "subnet","subnet-id", "subnetId25");
- Vertex l3Network1lintIpv6 = graph.addVertex(T.label, "l3-network",T.id, "26", "aai-node-type", "l3-network","l3-network-id", "l3-networkId26");
-
-
- Vertex l3InterfaceIpv4AddressListLint = graph.addVertex(T.label, "l3-interface-ipv4-address-list",T.id, "27", "aai-node-type", "l3-interface-ipv4-address-list","l3-interface-ipv4-address-list-id", "l3-interface-ipv4-address-listId27");
- Vertex l3InterfaceIpv6AddressListlInt = graph.addVertex(T.label, "l3-interface-ipv6-address-list",T.id, "28", "aai-node-type", "l3-interface-ipv6-address-list","l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-listId28");
-
-
- Vertex complex = graph.addVertex(T.label, "complex",T.id, "29", "aai-node-type", "complex","complex-id", "complexId29");
-
-
-
- Vertex genericVnf1 = graph.addVertex(T.label, "generic-vnf",T.id, "31", "aai-node-type", "generic-vnf", "generic-vnf-id", "serviceinstanceid1");
- Vertex vnfc1 = graph.addVertex(T.label, "vnfc",T.id, "32", "aai-node-type", "vnfc","vnfc-id", "vnfcId2");
- Vertex cp1 = graph.addVertex(T.label, "cp",T.id, "33", "aai-node-type", "cp","cp-id", "cpId3");
- Vertex vipIpv4AddressList1 = graph.addVertex(T.label, "vip-ipv4-address-list",T.id, "34", "aai-node-type", "vip-ipv4-address-list","vip-ipv4-address-list-id", "vip-ipv4-address-listId4");
- Vertex vipIpv6AddressList1 = graph.addVertex(T.label, "vip-ipv6-address-list",T.id, "35", "aai-node-type", "vip-ipv6-address-list","vip-ipv6-address-list-id", "vip-ipv6-address-listId5");
- Vertex subnetIpv41 = graph.addVertex(T.label, "subnet",T.id, "36", "aai-node-type", "subnet","subnet-id", "subnetId6");
- Vertex l3Network1Ipv41 = graph.addVertex(T.label, "l3-network",T.id, "37", "aai-node-type", "l3-network","l3-network-id", "l3-networkId7");
- Vertex subnetIpv61 = graph.addVertex(T.label, "subnet",T.id, "38", "aai-node-type", "subnet","subnet-id", "subnetId8");
- Vertex l3Network1Ipv61 = graph.addVertex(T.label, "l3-network",T.id, "39", "aai-node-type", "l3-network","l3-network-id", "l3-networkId9");
- Vertex vserver1 = graph.addVertex(T.label, "vserver",T.id, "40", "aai-node-type", "vserver","vserver-id", "vserverId10");
- Vertex linterface1 = graph.addVertex(T.label, "l-interface",T.id, "41", "aai-node-type", "l-interface","l-interface-id", "l-interfaceId11");
- Vertex pserver1 = graph.addVertex(T.label, "pserver",T.id, "42", "aai-node-type", "pserver","pserver-id", "pserverId12");
- Vertex l3NetworklintIpv41 = graph.addVertex(T.label, "l3-network",T.id, "43", "aai-node-type", "l3-network","l3-network-id", "l3-networkId13");
- Vertex subnetlintIpv41 = graph.addVertex(T.label, "subnet",T.id, "44", "aai-node-type", "subnet","subnet-id", "subnetId14");
- Vertex l3Network1lintIpv41 = graph.addVertex(T.label, "l3-network",T.id, "45", "aai-node-type", "l3-network","l3-network-id", "l3-networkId15");
- Vertex l3NetworklintIpv61 = graph.addVertex(T.label, "l3-network",T.id, "46", "aai-node-type", "l3-network","l3-network-id", "l3-networkId16");
- Vertex subnetlintIpv61 = graph.addVertex(T.label, "subnet",T.id, "47", "aai-node-type", "subnet","subnet-id", "subnetId17");
- Vertex l3Network1lintIpv61 = graph.addVertex(T.label, "l3-network",T.id, "48", "aai-node-type", "l3-network","l3-network-id", "l3-networkId18");
- Vertex l3InterfaceIpv4AddressListLint1 = graph.addVertex(T.label, "l3-interface-ipv4-address-list",T.id, "49", "aai-node-type", "l3-interface-ipv4-address-list","l3-interface-ipv4-address-list-id", "l3-interface-ipv4-address-listId19");
- Vertex l3InterfaceIpv6AddressListlInt1 = graph.addVertex(T.label, "l3-interface-ipv6-address-list",T.id, "50", "aai-node-type", "l3-interface-ipv6-address-list","l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-listId20");
- Vertex complex1 = graph.addVertex(T.label, "complex",T.id, "51", "aai-node-type", "complex","complex-id", "complexId21");
-
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addEdge(g, genericVnf,vnfc);
- rules.addTreeEdge(g, vnfc,cp);
- rules.addEdge(g, cp,vipIpv4AddressList);
- rules.addEdge(g, cp,vipIpv6AddressList);
-
- rules.addEdge(g, vipIpv4AddressList,subnetIpv4);
- rules.addTreeEdge(g, subnetIpv4,l3Network1Ipv4);
-
- rules.addEdge(g, vipIpv6AddressList,subnetIpv6);
- rules.addTreeEdge(g, subnetIpv6,l3Network1Ipv6);
-
- rules.addEdge(g, genericVnf,vserver);
- rules.addEdge(g, vserver,pserver);
-
- rules.addTreeEdge(g, cp,l3InterfaceIpv4AddressListLint);
- rules.addTreeEdge(g, cp,l3InterfaceIpv6AddressListlInt);
-
- rules.addEdge(g, l3InterfaceIpv4AddressListLint,l3NetworklintIpv4);
- rules.addEdge(g, l3InterfaceIpv4AddressListLint,subnetlintIpv4);
- rules.addTreeEdge(g, subnetlintIpv4,l3Network1lintIpv4);
-
- rules.addEdge(g, l3InterfaceIpv6AddressListlInt,l3NetworklintIpv6);
- rules.addEdge(g, l3InterfaceIpv6AddressListlInt,subnetlintIpv6);
- rules.addTreeEdge(g, subnetlintIpv6,l3Network1lintIpv6);
-
- rules.addEdge(g, pserver,complex);
-
- //false
- rules.addEdge(g, genericVnf1,vnfc1);
- rules.addTreeEdge(g, vnfc1,cp1);
- rules.addEdge(g, cp1,vipIpv4AddressList1);
- rules.addEdge(g, cp1,vipIpv6AddressList1);
- rules.addEdge(g, vipIpv4AddressList1,subnetIpv41);
- rules.addTreeEdge(g, subnetIpv41,l3Network1Ipv41);
- rules.addEdge(g, vipIpv6AddressList1,subnetIpv61);
- rules.addTreeEdge(g, subnetIpv61,l3Network1Ipv61);
- rules.addEdge(g, genericVnf1,vserver1);
- rules.addEdge(g, vserver1,pserver1);
- rules.addTreeEdge(g, cp1,l3InterfaceIpv4AddressListLint1);
- rules.addTreeEdge(g, cp1,l3InterfaceIpv6AddressListlInt1);
- rules.addEdge(g, l3InterfaceIpv4AddressListLint1,l3NetworklintIpv41);
- rules.addEdge(g, l3InterfaceIpv4AddressListLint1,subnetlintIpv41);
- rules.addTreeEdge(g, subnetlintIpv41,l3Network1lintIpv41);
- rules.addEdge(g, l3InterfaceIpv6AddressListlInt1,l3NetworklintIpv61);
- rules.addEdge(g, l3InterfaceIpv6AddressListlInt1,subnetlintIpv61);
- rules.addTreeEdge(g, subnetlintIpv61,l3Network1lintIpv61);
- rules.addEdge(g, pserver1,complex1);
- //false
-
- expectedResult.add(genericVnf);
- expectedResult.add(vnfc);
- expectedResult.add(cp);
- expectedResult.add(vipIpv4AddressList);
- expectedResult.add(vipIpv6AddressList);
-
- expectedResult.add(subnetIpv4);
- expectedResult.add(l3Network1Ipv4);
-
- expectedResult.add(subnetIpv6);
- expectedResult.add(l3Network1Ipv6);
-
- expectedResult.add(l3InterfaceIpv4AddressListLint);
- expectedResult.add(l3InterfaceIpv6AddressListlInt);
-
- expectedResult.add(l3NetworklintIpv4);
- expectedResult.add(subnetlintIpv4);
- expectedResult.add(l3Network1lintIpv4);
-
- expectedResult.add(l3NetworklintIpv6);
- expectedResult.add(subnetlintIpv6);
- expectedResult.add(l3Network1lintIpv6);
-
- expectedResult.add(vserver);
- expectedResult.add(pserver);
- expectedResult.add(complex);
-
- }
-
- @Override
- protected String getQueryName() {
- return "ips-networks-fromVnf";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "generic-vnf").has("generic-vnf-id", "serviceinstanceid0");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
-
-
+ public IpsNetworksFromVnfTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Ignore
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex genericVnf = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type",
+ "generic-vnf", "generic-vnf-id", "serviceinstanceid0");
+ Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "1", "aai-node-type", "vnfc",
+ "vnfc-id", "vnfcId1");
+ Vertex cp =
+ graph.addVertex(T.label, "cp", T.id, "30", "aai-node-type", "cp", "cp-id", "cpId1");
+ Vertex vipIpv4AddressList =
+ graph.addVertex(T.label, "vip-ipv4-address-list", T.id, "2", "aai-node-type",
+ "vip-ipv4-address-list", "vip-ipv4-address-list-id", "vip-ipv4-address-listId2");
+ Vertex vipIpv6AddressList =
+ graph.addVertex(T.label, "vip-ipv6-address-list", T.id, "3", "aai-node-type",
+ "vip-ipv6-address-list", "vip-ipv6-address-list-id", "vip-ipv6-address-listId3");
+
+ Vertex subnetIpv4 = graph.addVertex(T.label, "subnet", T.id, "7", "aai-node-type", "subnet",
+ "subnet-id", "subnetId7");
+ Vertex l3Network1Ipv4 = graph.addVertex(T.label, "l3-network", T.id, "8", "aai-node-type",
+ "l3-network", "l3-network-id", "l3-networkId8");
+
+ Vertex subnetIpv6 = graph.addVertex(T.label, "subnet", T.id, "10", "aai-node-type",
+ "subnet", "subnet-id", "subnetId10");
+ Vertex l3Network1Ipv6 = graph.addVertex(T.label, "l3-network", T.id, "11", "aai-node-type",
+ "l3-network", "l3-network-id", "l3-networkId11");
+
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "18", "aai-node-type", "vserver",
+ "vserver-id", "vserverId18");
+ Vertex linterface = graph.addVertex(T.label, "l-interface", T.id, "19", "aai-node-type",
+ "l-interface", "l-interface-id", "l-interfaceId19");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "20", "aai-node-type", "pserver",
+ "pserver-id", "pserverId20");
+
+ Vertex l3NetworklintIpv4 = graph.addVertex(T.label, "l3-network", T.id, "21",
+ "aai-node-type", "l3-network", "l3-network-id", "l3-networkId21");
+ Vertex subnetlintIpv4 = graph.addVertex(T.label, "subnet", T.id, "22", "aai-node-type",
+ "subnet", "subnet-id", "subnetId22");
+ Vertex l3Network1lintIpv4 = graph.addVertex(T.label, "l3-network", T.id, "23",
+ "aai-node-type", "l3-network", "l3-network-id", "l3-networkId23");
+
+ Vertex l3NetworklintIpv6 = graph.addVertex(T.label, "l3-network", T.id, "24",
+ "aai-node-type", "l3-network", "l3-network-id", "l3-networkId24");
+ Vertex subnetlintIpv6 = graph.addVertex(T.label, "subnet", T.id, "25", "aai-node-type",
+ "subnet", "subnet-id", "subnetId25");
+ Vertex l3Network1lintIpv6 = graph.addVertex(T.label, "l3-network", T.id, "26",
+ "aai-node-type", "l3-network", "l3-network-id", "l3-networkId26");
+
+ Vertex l3InterfaceIpv4AddressListLint =
+ graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "27", "aai-node-type",
+ "l3-interface-ipv4-address-list", "l3-interface-ipv4-address-list-id",
+ "l3-interface-ipv4-address-listId27");
+ Vertex l3InterfaceIpv6AddressListlInt =
+ graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "28", "aai-node-type",
+ "l3-interface-ipv6-address-list", "l3-interface-ipv6-address-list-id",
+ "l3-interface-ipv6-address-listId28");
+
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "29", "aai-node-type", "complex",
+ "complex-id", "complexId29");
+
+ Vertex genericVnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "31", "aai-node-type",
+ "generic-vnf", "generic-vnf-id", "serviceinstanceid1");
+ Vertex vnfc1 = graph.addVertex(T.label, "vnfc", T.id, "32", "aai-node-type", "vnfc",
+ "vnfc-id", "vnfcId2");
+ Vertex cp1 =
+ graph.addVertex(T.label, "cp", T.id, "33", "aai-node-type", "cp", "cp-id", "cpId3");
+ Vertex vipIpv4AddressList1 =
+ graph.addVertex(T.label, "vip-ipv4-address-list", T.id, "34", "aai-node-type",
+ "vip-ipv4-address-list", "vip-ipv4-address-list-id", "vip-ipv4-address-listId4");
+ Vertex vipIpv6AddressList1 =
+ graph.addVertex(T.label, "vip-ipv6-address-list", T.id, "35", "aai-node-type",
+ "vip-ipv6-address-list", "vip-ipv6-address-list-id", "vip-ipv6-address-listId5");
+ Vertex subnetIpv41 = graph.addVertex(T.label, "subnet", T.id, "36", "aai-node-type",
+ "subnet", "subnet-id", "subnetId6");
+ Vertex l3Network1Ipv41 = graph.addVertex(T.label, "l3-network", T.id, "37", "aai-node-type",
+ "l3-network", "l3-network-id", "l3-networkId7");
+ Vertex subnetIpv61 = graph.addVertex(T.label, "subnet", T.id, "38", "aai-node-type",
+ "subnet", "subnet-id", "subnetId8");
+ Vertex l3Network1Ipv61 = graph.addVertex(T.label, "l3-network", T.id, "39", "aai-node-type",
+ "l3-network", "l3-network-id", "l3-networkId9");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "40", "aai-node-type",
+ "vserver", "vserver-id", "vserverId10");
+ Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "41", "aai-node-type",
+ "l-interface", "l-interface-id", "l-interfaceId11");
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "42", "aai-node-type",
+ "pserver", "pserver-id", "pserverId12");
+ Vertex l3NetworklintIpv41 = graph.addVertex(T.label, "l3-network", T.id, "43",
+ "aai-node-type", "l3-network", "l3-network-id", "l3-networkId13");
+ Vertex subnetlintIpv41 = graph.addVertex(T.label, "subnet", T.id, "44", "aai-node-type",
+ "subnet", "subnet-id", "subnetId14");
+ Vertex l3Network1lintIpv41 = graph.addVertex(T.label, "l3-network", T.id, "45",
+ "aai-node-type", "l3-network", "l3-network-id", "l3-networkId15");
+ Vertex l3NetworklintIpv61 = graph.addVertex(T.label, "l3-network", T.id, "46",
+ "aai-node-type", "l3-network", "l3-network-id", "l3-networkId16");
+ Vertex subnetlintIpv61 = graph.addVertex(T.label, "subnet", T.id, "47", "aai-node-type",
+ "subnet", "subnet-id", "subnetId17");
+ Vertex l3Network1lintIpv61 = graph.addVertex(T.label, "l3-network", T.id, "48",
+ "aai-node-type", "l3-network", "l3-network-id", "l3-networkId18");
+ Vertex l3InterfaceIpv4AddressListLint1 =
+ graph.addVertex(T.label, "l3-interface-ipv4-address-list", T.id, "49", "aai-node-type",
+ "l3-interface-ipv4-address-list", "l3-interface-ipv4-address-list-id",
+ "l3-interface-ipv4-address-listId19");
+ Vertex l3InterfaceIpv6AddressListlInt1 =
+ graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "50", "aai-node-type",
+ "l3-interface-ipv6-address-list", "l3-interface-ipv6-address-list-id",
+ "l3-interface-ipv6-address-listId20");
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "51", "aai-node-type",
+ "complex", "complex-id", "complexId21");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addEdge(g, genericVnf, vnfc);
+ rules.addTreeEdge(g, vnfc, cp);
+ rules.addEdge(g, cp, vipIpv4AddressList);
+ rules.addEdge(g, cp, vipIpv6AddressList);
+
+ rules.addEdge(g, vipIpv4AddressList, subnetIpv4);
+ rules.addTreeEdge(g, subnetIpv4, l3Network1Ipv4);
+
+ rules.addEdge(g, vipIpv6AddressList, subnetIpv6);
+ rules.addTreeEdge(g, subnetIpv6, l3Network1Ipv6);
+
+ rules.addEdge(g, genericVnf, vserver);
+ rules.addEdge(g, vserver, pserver);
+
+ rules.addTreeEdge(g, cp, l3InterfaceIpv4AddressListLint);
+ rules.addTreeEdge(g, cp, l3InterfaceIpv6AddressListlInt);
+
+ rules.addEdge(g, l3InterfaceIpv4AddressListLint, l3NetworklintIpv4);
+ rules.addEdge(g, l3InterfaceIpv4AddressListLint, subnetlintIpv4);
+ rules.addTreeEdge(g, subnetlintIpv4, l3Network1lintIpv4);
+
+ rules.addEdge(g, l3InterfaceIpv6AddressListlInt, l3NetworklintIpv6);
+ rules.addEdge(g, l3InterfaceIpv6AddressListlInt, subnetlintIpv6);
+ rules.addTreeEdge(g, subnetlintIpv6, l3Network1lintIpv6);
+
+ rules.addEdge(g, pserver, complex);
+
+ // false
+ rules.addEdge(g, genericVnf1, vnfc1);
+ rules.addTreeEdge(g, vnfc1, cp1);
+ rules.addEdge(g, cp1, vipIpv4AddressList1);
+ rules.addEdge(g, cp1, vipIpv6AddressList1);
+ rules.addEdge(g, vipIpv4AddressList1, subnetIpv41);
+ rules.addTreeEdge(g, subnetIpv41, l3Network1Ipv41);
+ rules.addEdge(g, vipIpv6AddressList1, subnetIpv61);
+ rules.addTreeEdge(g, subnetIpv61, l3Network1Ipv61);
+ rules.addEdge(g, genericVnf1, vserver1);
+ rules.addEdge(g, vserver1, pserver1);
+ rules.addTreeEdge(g, cp1, l3InterfaceIpv4AddressListLint1);
+ rules.addTreeEdge(g, cp1, l3InterfaceIpv6AddressListlInt1);
+ rules.addEdge(g, l3InterfaceIpv4AddressListLint1, l3NetworklintIpv41);
+ rules.addEdge(g, l3InterfaceIpv4AddressListLint1, subnetlintIpv41);
+ rules.addTreeEdge(g, subnetlintIpv41, l3Network1lintIpv41);
+ rules.addEdge(g, l3InterfaceIpv6AddressListlInt1, l3NetworklintIpv61);
+ rules.addEdge(g, l3InterfaceIpv6AddressListlInt1, subnetlintIpv61);
+ rules.addTreeEdge(g, subnetlintIpv61, l3Network1lintIpv61);
+ rules.addEdge(g, pserver1, complex1);
+ // false
+
+ expectedResult.add(genericVnf);
+ expectedResult.add(vnfc);
+ expectedResult.add(cp);
+ expectedResult.add(vipIpv4AddressList);
+ expectedResult.add(vipIpv6AddressList);
+
+ expectedResult.add(subnetIpv4);
+ expectedResult.add(l3Network1Ipv4);
+
+ expectedResult.add(subnetIpv6);
+ expectedResult.add(l3Network1Ipv6);
+
+ expectedResult.add(l3InterfaceIpv4AddressListLint);
+ expectedResult.add(l3InterfaceIpv6AddressListlInt);
+
+ expectedResult.add(l3NetworklintIpv4);
+ expectedResult.add(subnetlintIpv4);
+ expectedResult.add(l3Network1lintIpv4);
+
+ expectedResult.add(l3NetworklintIpv6);
+ expectedResult.add(subnetlintIpv6);
+ expectedResult.add(l3Network1lintIpv6);
+
+ expectedResult.add(vserver);
+ expectedResult.add(pserver);
+ expectedResult.add(complex);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "ips-networks-fromVnf";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "generic-vnf").has("generic-vnf-id", "serviceinstanceid0");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
+
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedDevices_ComplicatedGVtoGV.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedDevices_ComplicatedGVtoGV.java
index 42cf635..026c722 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedDevices_ComplicatedGVtoGV.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedDevices_ComplicatedGVtoGV.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -31,67 +31,71 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class LinkedDevices_ComplicatedGVtoGV extends QueryTest {
- public LinkedDevices_ComplicatedGVtoGV() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "00", "aai-node-type", "generic-vnf",
- "vnf-id", "gvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
-
- Vertex lint1 = graph.addVertex(T.label, "l-interface", T.id, "10", "aai-node-type", "l-interface",
- "interface-name", "lint1", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false");
-
- Vertex loglink1 = graph.addVertex(T.label, "logical-link", T.id, "20", "aai-node-type", "logical-link",
- "link-name", "loglink1", "in-maint", "false", "link-type", "sausage");
-
- Vertex lint2 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type", "l-interface",
- "interface-name", "lint2", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false");
-
- Vertex vlan = graph.addVertex(T.label, "vlan", T.id, "30", "aai-node-type", "vlan",
- "vlan-interface", "vlan1");
-
- Vertex loglink2 = graph.addVertex(T.label, "logical-link", T.id, "21", "aai-node-type", "logical-link",
- "link-name", "loglink2", "in-maint", "false", "link-type", "sausage");
-
- Vertex lagint = graph.addVertex(T.label, "lag-interface", T.id, "40", "aai-node-type", "lag-interface",
- "interface-name", "lagint1");
-
- Vertex gvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "01", "aai-node-type", "generic-vnf",
- "vnf-id", "gvnf2", "vnf-name", "genvnfname2", "nf-type", "sample-nf-type");
-
- GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, gvnf1, lint1);
- rules.addEdge(g, lint1, loglink1);
- rules.addEdge(g, lint2, loglink1);
- rules.addTreeEdge(g, lint2, vlan);
- rules.addEdge(g, vlan, loglink2);
- rules.addEdge(g, loglink2, lagint);
- rules.addTreeEdge(g, gvnf2, lagint);
-
- expectedResult.add(gvnf1);
- expectedResult.add(gvnf2);
- }
-
- @Override
- protected String getQueryName() {
- return "linked-devices";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "generic-vnf").has("vnf-id", "gvnf1");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- // n/a for this query
- }
+ public LinkedDevices_ComplicatedGVtoGV() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex gvnf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "00", "aai-node-type", "generic-vnf",
+ "vnf-id", "gvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
+
+ Vertex lint1 = graph.addVertex(T.label, "l-interface", T.id, "10", "aai-node-type",
+ "l-interface", "interface-name", "lint1", "is-port-mirrored", "true", "in-maint",
+ "true", "is-ip-unnumbered", "false");
+
+ Vertex loglink1 = graph.addVertex(T.label, "logical-link", T.id, "20", "aai-node-type",
+ "logical-link", "link-name", "loglink1", "in-maint", "false", "link-type", "sausage");
+
+ Vertex lint2 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type",
+ "l-interface", "interface-name", "lint2", "is-port-mirrored", "true", "in-maint",
+ "true", "is-ip-unnumbered", "false");
+
+ Vertex vlan = graph.addVertex(T.label, "vlan", T.id, "30", "aai-node-type", "vlan",
+ "vlan-interface", "vlan1");
+
+ Vertex loglink2 = graph.addVertex(T.label, "logical-link", T.id, "21", "aai-node-type",
+ "logical-link", "link-name", "loglink2", "in-maint", "false", "link-type", "sausage");
+
+ Vertex lagint = graph.addVertex(T.label, "lag-interface", T.id, "40", "aai-node-type",
+ "lag-interface", "interface-name", "lagint1");
+
+ Vertex gvnf2 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "01", "aai-node-type", "generic-vnf",
+ "vnf-id", "gvnf2", "vnf-name", "genvnfname2", "nf-type", "sample-nf-type");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addTreeEdge(g, gvnf1, lint1);
+ rules.addEdge(g, lint1, loglink1);
+ rules.addEdge(g, lint2, loglink1);
+ rules.addTreeEdge(g, lint2, vlan);
+ rules.addEdge(g, vlan, loglink2);
+ rules.addEdge(g, loglink2, lagint);
+ rules.addTreeEdge(g, gvnf2, lagint);
+
+ expectedResult.add(gvnf1);
+ expectedResult.add(gvnf2);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "linked-devices";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "generic-vnf").has("vnf-id", "gvnf1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ // n/a for this query
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedDevices_NewvceVserverTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedDevices_NewvceVserverTest.java
index c828c67..7866237 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedDevices_NewvceVserverTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedDevices_NewvceVserverTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -22,8 +22,8 @@ package org.onap.aai.rest.search;
import static org.junit.Assert.*;
import java.util.ArrayList;
-import java.util.Map;
import java.util.List;
+import java.util.Map;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSource;
@@ -35,76 +35,80 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class LinkedDevices_NewvceVserverTest extends QueryTest {
- public LinkedDevices_NewvceVserverTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Note: I don't know if this topology is realistic, but it doesn't really matter bc we're just testing functionality
- Vertex newvce1 = graph.addVertex(T.label, "newvce", T.id, "00", "aai-node-type", "newvce",
- "vnf-id2", "newvce1", "vnf-name", "bob", "vnf-type", "new");
-
- Vertex lint1 = graph.addVertex(T.label, "l-interface", T.id, "10", "aai-node-type", "l-interface",
- "interface-name", "lint1", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false");
- Vertex loglink1 = graph.addVertex(T.label, "logical-link", T.id, "20", "aai-node-type", "logical-link",
- "link-name", "loglink1", "in-maint", "false", "link-type", "sausage");
- Vertex lint2 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type", "l-interface",
- "interface-name", "lint2", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false");
- Vertex vlan = graph.addVertex(T.label, "vlan", T.id, "40", "aai-node-type", "vlan",
- "vlan-interface", "vlan1");
-
- Vertex newvce2 = graph.addVertex(T.label, "newvce", T.id, "01", "aai-node-type", "newvce",
- "vnf-id2", "newvce2", "vnf-name", "bob", "vnf-type", "new");
-
- Vertex loglink2 = graph.addVertex(T.label, "logical-link", T.id, "21", "aai-node-type", "logical-link",
- "link-name", "loglink2", "in-maint", "false", "link-type", "sausage");
- Vertex lint3 = graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type", "l-interface",
- "interface-name", "lint3", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false");
-
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "50", "aai-node-type", "cloud-region",
- "cloud-owner", "att", "cloud-region-id", "crId");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "60", "aai-node-type", "tenant",
- "tenant-id", "tenId", "tenant-name", "verity");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "30", "aai-node-type", "vserver",
- "vserver-id", "vserv1", "vserver-name", "frank");
-
- GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, newvce1, lint1);
- rules.addTreeEdge(g, lint1, vlan);
- rules.addEdge(g, lint1, loglink1);
- rules.addEdge(g, lint2, loglink1);
-
- rules.addTreeEdge(g, cloudregion, tenant);
- rules.addTreeEdge(g, tenant, vserver);
- rules.addTreeEdge(g, vserver, lint2);
-
- rules.addEdge(g, vlan, loglink2);
- rules.addTreeEdge(g, newvce2, lint3);
- rules.addEdge(g, loglink2, lint3);
-
- expectedResult.add(newvce1);
- expectedResult.add(newvce2);
- expectedResult.add(vserver);
- }
-
- @Override
- protected String getQueryName() {
- return "linked-devices";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "newvce").has("vnf-id2", "newvce1");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- // n/a for this query
- }
+ public LinkedDevices_NewvceVserverTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Note: I don't know if this topology is realistic, but it doesn't really matter bc we're
+ // just testing functionality
+ Vertex newvce1 = graph.addVertex(T.label, "newvce", T.id, "00", "aai-node-type", "newvce",
+ "vnf-id2", "newvce1", "vnf-name", "bob", "vnf-type", "new");
+
+ Vertex lint1 = graph.addVertex(T.label, "l-interface", T.id, "10", "aai-node-type",
+ "l-interface", "interface-name", "lint1", "is-port-mirrored", "true", "in-maint",
+ "true", "is-ip-unnumbered", "false");
+ Vertex loglink1 = graph.addVertex(T.label, "logical-link", T.id, "20", "aai-node-type",
+ "logical-link", "link-name", "loglink1", "in-maint", "false", "link-type", "sausage");
+ Vertex lint2 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type",
+ "l-interface", "interface-name", "lint2", "is-port-mirrored", "true", "in-maint",
+ "true", "is-ip-unnumbered", "false");
+ Vertex vlan = graph.addVertex(T.label, "vlan", T.id, "40", "aai-node-type", "vlan",
+ "vlan-interface", "vlan1");
+
+ Vertex newvce2 = graph.addVertex(T.label, "newvce", T.id, "01", "aai-node-type", "newvce",
+ "vnf-id2", "newvce2", "vnf-name", "bob", "vnf-type", "new");
+
+ Vertex loglink2 = graph.addVertex(T.label, "logical-link", T.id, "21", "aai-node-type",
+ "logical-link", "link-name", "loglink2", "in-maint", "false", "link-type", "sausage");
+ Vertex lint3 = graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type",
+ "l-interface", "interface-name", "lint3", "is-port-mirrored", "true", "in-maint",
+ "true", "is-ip-unnumbered", "false");
+
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "50", "aai-node-type",
+ "cloud-region", "cloud-owner", "att", "cloud-region-id", "crId");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "60", "aai-node-type", "tenant",
+ "tenant-id", "tenId", "tenant-name", "verity");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "30", "aai-node-type", "vserver",
+ "vserver-id", "vserv1", "vserver-name", "frank");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addTreeEdge(g, newvce1, lint1);
+ rules.addTreeEdge(g, lint1, vlan);
+ rules.addEdge(g, lint1, loglink1);
+ rules.addEdge(g, lint2, loglink1);
+
+ rules.addTreeEdge(g, cloudregion, tenant);
+ rules.addTreeEdge(g, tenant, vserver);
+ rules.addTreeEdge(g, vserver, lint2);
+
+ rules.addEdge(g, vlan, loglink2);
+ rules.addTreeEdge(g, newvce2, lint3);
+ rules.addEdge(g, loglink2, lint3);
+
+ expectedResult.add(newvce1);
+ expectedResult.add(newvce2);
+ expectedResult.add(vserver);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "linked-devices";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "newvce").has("vnf-id2", "newvce1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ // n/a for this query
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedDevices_SimpleGVtoGVQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedDevices_SimpleGVtoGVQueryTest.java
index 57967a6..6c4409e 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedDevices_SimpleGVtoGVQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedDevices_SimpleGVtoGVQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -31,55 +31,59 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class LinkedDevices_SimpleGVtoGVQueryTest extends QueryTest {
- public LinkedDevices_SimpleGVtoGVQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "00", "aai-node-type", "generic-vnf",
- "vnf-id", "gvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
-
- Vertex lint1 = graph.addVertex(T.label, "l-interface", T.id, "10", "aai-node-type", "l-interface",
- "interface-name", "lint1", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false");
-
- Vertex loglink = graph.addVertex(T.label, "logical-link", T.id, "20", "aai-node-type", "logical-link",
- "link-name", "loglink1", "in-maint", "false", "link-type", "sausage");
-
- Vertex lint2 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type", "l-interface",
- "interface-name", "lint2", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false");
-
- Vertex gvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "01", "aai-node-type", "generic-vnf",
- "vnf-id", "gvnf2", "vnf-name", "genvnfname2", "nf-type", "sample-nf-type");
-
- GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, gvnf1, lint1);
- rules.addTreeEdge(g, gvnf2, lint2);
- rules.addEdge(g, lint1, loglink);
- rules.addEdge(g, lint2, loglink);
-
- expectedResult.add(gvnf1);
- expectedResult.add(gvnf2);
- }
-
- @Override
- protected String getQueryName() {
- return "linked-devices";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type","generic-vnf").has("vnf-id","gvnf1");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- // n/a for this test
- }
+ public LinkedDevices_SimpleGVtoGVQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex gvnf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "00", "aai-node-type", "generic-vnf",
+ "vnf-id", "gvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
+
+ Vertex lint1 = graph.addVertex(T.label, "l-interface", T.id, "10", "aai-node-type",
+ "l-interface", "interface-name", "lint1", "is-port-mirrored", "true", "in-maint",
+ "true", "is-ip-unnumbered", "false");
+
+ Vertex loglink = graph.addVertex(T.label, "logical-link", T.id, "20", "aai-node-type",
+ "logical-link", "link-name", "loglink1", "in-maint", "false", "link-type", "sausage");
+
+ Vertex lint2 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type",
+ "l-interface", "interface-name", "lint2", "is-port-mirrored", "true", "in-maint",
+ "true", "is-ip-unnumbered", "false");
+
+ Vertex gvnf2 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "01", "aai-node-type", "generic-vnf",
+ "vnf-id", "gvnf2", "vnf-name", "genvnfname2", "nf-type", "sample-nf-type");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addTreeEdge(g, gvnf1, lint1);
+ rules.addTreeEdge(g, gvnf2, lint2);
+ rules.addEdge(g, lint1, loglink);
+ rules.addEdge(g, lint2, loglink);
+
+ expectedResult.add(gvnf1);
+ expectedResult.add(gvnf2);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "linked-devices";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "generic-vnf").has("vnf-id", "gvnf1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ // n/a for this test
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedHashMapQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedHashMapQueryTest.java
index 6488cae..b549183 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedHashMapQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/LinkedHashMapQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,21 +19,21 @@
*/
package org.onap.aai.rest.search;
-import org.onap.aai.exceptions.AAIException;
-
import java.util.LinkedHashMap;
import java.util.List;
+import org.onap.aai.exceptions.AAIException;
+
public abstract class LinkedHashMapQueryTest extends QueryTest {
- protected List<LinkedHashMap> hashMapList;
+ protected List<LinkedHashMap> hashMapList;
- public LinkedHashMapQueryTest() throws AAIException {
- super();
- }
+ public LinkedHashMapQueryTest() throws AAIException {
+ super();
+ }
- @Override
- public void run() {
- hashMapList = (List<LinkedHashMap>) shell.executeTraversal(query, params).toList();
- }
+ @Override
+ public void run() {
+ hashMapList = (List<LinkedHashMap>) shell.executeTraversal(query, params).toList();
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/LinterfacesCPFromVnfcTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/LinterfacesCPFromVnfcTest.java
index e911634..6821f78 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/LinterfacesCPFromVnfcTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/LinterfacesCPFromVnfcTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -31,71 +31,85 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class LinterfacesCPFromVnfcTest extends QueryTest {
- public LinterfacesCPFromVnfcTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public LinterfacesCPFromVnfcTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex vnfc = graph.addVertex(T.label, "vnfc",T.id, "0", "aai-node-type", "vnfc",
- "vnfc-name", "vnfcName1", "nfc-naming-code", "blue", "nfc-function", "correct-function","model-invariant-id","modelinvariantid","model-customization-id","modelcustomizationid");
- Vertex cp = graph.addVertex(T.label, "cp",T.id, "1", "aai-node-type", "cp","cp-id", "cpId");
- Vertex vlanTag = graph.addVertex(T.label, "vlan-tag",T.id, "2", "aai-node-type", "vlan-tag","vlan-tag-id", "vlanTagId");
- Vertex l3Network = graph.addVertex(T.label, "l3-network",T.id, "3", "aai-node-type", "l3-network","network-id", "networkId","is-provider-network",true);
- Vertex vserv = graph.addVertex(T.label, "vserver",T.id, "4", "aai-node-type", "vserver",
- "vserver-id", "vservId", "vserver-name", "vservName", "vserver-selflink", "me/self");
- Vertex linterface = graph.addVertex(T.label, "l-interface", T.id, "5", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0","network-name","networkName0");
-
- Vertex vnfc1 = graph.addVertex(T.label, "vnfc",T.id, "6", "aai-node-type", "vnfc",
- "vnfc-name", "vnfcName1", "nfc-naming-code", "blue", "nfc-function", "correct-function","model-invariant-id","modelinvariantid1","model-customization-id","modelcustomizationid1");
- Vertex cp1 = graph.addVertex(T.label, "cp",T.id, "7", "aai-node-type", "cp","cp-id", "cpId");
- Vertex vlanTag1 = graph.addVertex(T.label, "vlan-tag",T.id, "8", "aai-node-type", "vlan-tag","vlan-tag-id", "vlanTagId");
- Vertex l3Network1 = graph.addVertex(T.label, "l3-network",T.id, "9", "aai-node-type", "l3-network","network-id", "networkId","is-provider-network",false);
- Vertex vserv1 = graph.addVertex(T.label, "vserver",T.id, "10", "aai-node-type", "vserver",
- "vserver-id", "vservId", "vserver-name", "vservName", "vserver-selflink", "me/self");
- Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0","network-name","networkName0");
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "0", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfcName1", "nfc-naming-code", "blue", "nfc-function", "correct-function",
+ "model-invariant-id", "modelinvariantid", "model-customization-id",
+ "modelcustomizationid");
+ Vertex cp =
+ graph.addVertex(T.label, "cp", T.id, "1", "aai-node-type", "cp", "cp-id", "cpId");
+ Vertex vlanTag = graph.addVertex(T.label, "vlan-tag", T.id, "2", "aai-node-type",
+ "vlan-tag", "vlan-tag-id", "vlanTagId");
+ Vertex l3Network = graph.addVertex(T.label, "l3-network", T.id, "3", "aai-node-type",
+ "l3-network", "network-id", "networkId", "is-provider-network", true);
+ Vertex vserv = graph.addVertex(T.label, "vserver", T.id, "4", "aai-node-type", "vserver",
+ "vserver-id", "vservId", "vserver-name", "vservName", "vserver-selflink", "me/self");
+ Vertex linterface = graph.addVertex(T.label, "l-interface", T.id, "5", "aai-node-type",
+ "l-interface", "l-interface-id", "l-interface-id0", "l-interface-name",
+ "l-interface-name0", "network-name", "networkName0");
- GraphTraversalSource g = graph.traversal();
-
- rules.addTreeEdge(g, vnfc,cp);
- rules.addEdge(g, cp,vlanTag);
- rules.addEdge(g, cp,l3Network);
- rules.addEdge(g, vnfc,vserv);
- rules.addTreeEdge(g, vserv, linterface);
-
- rules.addTreeEdge(g, vnfc1,cp1);
- rules.addEdge(g, cp1,vlanTag1);
- rules.addEdge(g, cp1,l3Network1);
- rules.addEdge(g, vnfc1,vserv1);
- rules.addTreeEdge(g, vserv1, linterface1);
-
- expectedResult.add(vlanTag);
- expectedResult.add(l3Network);
- expectedResult.add(linterface);
- //expectedResult.add(vlanTag1);//false
- //expectedResult.add(l3Network1);//false
- //expectedResult.add(linterface1);//false
- }
+ Vertex vnfc1 = graph.addVertex(T.label, "vnfc", T.id, "6", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfcName1", "nfc-naming-code", "blue", "nfc-function", "correct-function",
+ "model-invariant-id", "modelinvariantid1", "model-customization-id",
+ "modelcustomizationid1");
+ Vertex cp1 =
+ graph.addVertex(T.label, "cp", T.id, "7", "aai-node-type", "cp", "cp-id", "cpId");
+ Vertex vlanTag1 = graph.addVertex(T.label, "vlan-tag", T.id, "8", "aai-node-type",
+ "vlan-tag", "vlan-tag-id", "vlanTagId");
+ Vertex l3Network1 = graph.addVertex(T.label, "l3-network", T.id, "9", "aai-node-type",
+ "l3-network", "network-id", "networkId", "is-provider-network", false);
+ Vertex vserv1 = graph.addVertex(T.label, "vserver", T.id, "10", "aai-node-type", "vserver",
+ "vserver-id", "vservId", "vserver-name", "vservName", "vserver-selflink", "me/self");
+ Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type",
+ "l-interface", "l-interface-id", "l-interface-id0", "l-interface-name",
+ "l-interface-name0", "network-name", "networkName0");
- @Override
- protected String getQueryName() {
- return "l-interface-to-CP";
- }
+ GraphTraversalSource g = graph.traversal();
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "vnfc").has("model-invariant-id", "modelinvariantid").has("model-customization-id", "modelcustomizationid");
- }
+ rules.addTreeEdge(g, vnfc, cp);
+ rules.addEdge(g, cp, vlanTag);
+ rules.addEdge(g, cp, l3Network);
+ rules.addEdge(g, vnfc, vserv);
+ rules.addTreeEdge(g, vserv, linterface);
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("isProviderNetwork", true);
- }
+ rules.addTreeEdge(g, vnfc1, cp1);
+ rules.addEdge(g, cp1, vlanTag1);
+ rules.addEdge(g, cp1, l3Network1);
+ rules.addEdge(g, vnfc1, vserv1);
+ rules.addTreeEdge(g, vserv1, linterface1);
+
+ expectedResult.add(vlanTag);
+ expectedResult.add(l3Network);
+ expectedResult.add(linterface);
+ // expectedResult.add(vlanTag1);//false
+ // expectedResult.add(l3Network1);//false
+ // expectedResult.add(linterface1);//false
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "l-interface-to-CP";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "vnfc").has("model-invariant-id", "modelinvariantid")
+ .has("model-customization-id", "modelcustomizationid");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("isProviderNetwork", true);
+ }
-
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/LocationNetTypeNetRolefromCloudRegionQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/LocationNetTypeNetRolefromCloudRegionQueryTest.java
index c73a4c6..56dbf79 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/LocationNetTypeNetRolefromCloudRegionQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/LocationNetTypeNetRolefromCloudRegionQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,56 +26,65 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class LocationNetTypeNetRolefromCloudRegionQueryTest extends QueryTest {
- public LocationNetTypeNetRolefromCloudRegionQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public LocationNetTypeNetRolefromCloudRegionQueryTest()
+ throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+
+ Vertex cloudregion =
+ graph.addVertex(T.label, "cloud-region", T.id, "0", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1");
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "1", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-1");
+ Vertex l3network = graph.addVertex(T.label, "l3-network", T.id, "2", "aai-node-type",
+ "l3-network", "network-id", "network-id-1");
+
+ Vertex cloudregion1 =
+ graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-2");
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "4", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-2");
+ Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "5", "aai-node-type",
+ "l3-network", "network-id", "network-id-2");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, cloudregion, complex);
+ rules.addEdge(g, complex, l3network);
+
+ rules.addEdge(g, cloudregion1, complex1);
+ rules.addEdge(g, complex1, l3network1);
+
+ expectedResult.add(cloudregion);
+ expectedResult.add(complex);
+ expectedResult.add(l3network);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "locationNetTypeNetRole-fromCloudRegion";
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("cloud-region-id", "cloud-region-id-1");
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "0", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1");
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "1", "aai-node-type", "complex", "physical-location-id", "physical-location-id-1");
- Vertex l3network = graph.addVertex(T.label, "l3-network", T.id, "2", "aai-node-type", "l3-network", "network-id", "network-id-1");
-
-
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-2");
- Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "4", "aai-node-type", "complex", "physical-location-id", "physical-location-id-2");
- Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "5", "aai-node-type", "l3-network", "network-id", "network-id-2");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, cloudregion,complex);
- rules.addEdge(g, complex,l3network);
-
- rules.addEdge(g, cloudregion1,complex1);
- rules.addEdge(g, complex1,l3network1);
-
- expectedResult.add(cloudregion);
- expectedResult.add(complex);
- expectedResult.add(l3network);
-
- }
+ }
- @Override
- protected String getQueryName() {
- return "locationNetTypeNetRole-fromCloudRegion";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("cloud-region-id", "cloud-region-id-1");
-
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/LogicalLinkByCloudRegionIdTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/LogicalLinkByCloudRegionIdTest.java
index a231ccd..224a6b7 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/LogicalLinkByCloudRegionIdTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/LogicalLinkByCloudRegionIdTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,8 @@
*/
package org.onap.aai.rest.search;
+import java.util.Map;
+
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.T;
@@ -27,10 +29,8 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-
public class LogicalLinkByCloudRegionIdTest extends QueryTest {
- public LogicalLinkByCloudRegionIdTest () throws AAIException, NoEdgeRuleFoundException {
+ public LogicalLinkByCloudRegionIdTest() throws AAIException, NoEdgeRuleFoundException {
super();
}
@@ -43,12 +43,18 @@ public class LogicalLinkByCloudRegionIdTest extends QueryTest {
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
// Set up the test graph
- Vertex cloudRegion1 = graph.addVertex(T.label, "cloud-region", T.id, "0", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner1", "cloud-region-id", "cloudRegionId1");
- Vertex logicalLink1 = graph.addVertex(T.label, "logical-link", T.id, "1", "aai-node-type", "logical-link", "link-name", "linkName1", "in-maint", "false", "link-type","linkType1");
+ Vertex cloudRegion1 = graph.addVertex(T.label, "cloud-region", T.id, "0", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloudOwner1", "cloud-region-id", "cloudRegionId1");
+ Vertex logicalLink1 =
+ graph.addVertex(T.label, "logical-link", T.id, "1", "aai-node-type", "logical-link",
+ "link-name", "linkName1", "in-maint", "false", "link-type", "linkType1");
// adding extra vertices and edges which shouldn't be picked.
- Vertex cloudRegion2 = graph.addVertex(T.label, "cloud-region", T.id, "2", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner2", "cloud-region-id", "cloudRegionId3");
- Vertex logicalLink2 = graph.addVertex(T.label, "logical-link", T.id, "3", "aai-node-type", "logical-link", "link-name", "linkName2", "in-maint", "false", "link-type","linkType4");
+ Vertex cloudRegion2 = graph.addVertex(T.label, "cloud-region", T.id, "2", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloudOwner2", "cloud-region-id", "cloudRegionId3");
+ Vertex logicalLink2 =
+ graph.addVertex(T.label, "logical-link", T.id, "3", "aai-node-type", "logical-link",
+ "link-name", "linkName2", "in-maint", "false", "link-type", "linkType4");
GraphTraversalSource g = graph.traversal();
rules.addEdge(g, cloudRegion1, logicalLink1);
@@ -72,4 +78,4 @@ public class LogicalLinkByCloudRegionIdTest extends QueryTest {
protected void addParam(Map<String, Object> params) {
return;
}
-} \ No newline at end of file
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/ModelAndNamedQueryRestProviderTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/ModelAndNamedQueryRestProviderTest.java
index b4a3dcd..5d2002e 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/ModelAndNamedQueryRestProviderTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/ModelAndNamedQueryRestProviderTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,19 @@
*/
package org.onap.aai.rest.search;
+import static org.junit.Assert.assertEquals;
+import static org.junit.Assert.assertNotNull;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.io.IOException;
+import java.io.InputStream;
+import java.util.*;
+
+import javax.servlet.http.HttpServletRequest;
+import javax.ws.rs.core.*;
+
import org.apache.commons.io.IOUtils;
import org.junit.Before;
import org.junit.Ignore;
@@ -30,19 +43,7 @@ import org.onap.aai.setup.SchemaVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.servlet.http.HttpServletRequest;
-import javax.ws.rs.core.*;
-import java.io.IOException;
-import java.io.InputStream;
-import java.util.*;
-
-import static org.junit.Assert.assertEquals;
-import static org.junit.Assert.assertNotNull;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class ModelAndNamedQueryRestProviderTest extends AAISetup{
+public class ModelAndNamedQueryRestProviderTest extends AAISetup {
protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
@@ -70,21 +71,23 @@ public class ModelAndNamedQueryRestProviderTest extends AAISetup{
private List<MediaType> outputMediaTypes;
- private static final Logger logger = LoggerFactory.getLogger(ModelAndNamedQueryRestProviderTest.class.getName());
+ private static final Logger logger =
+ LoggerFactory.getLogger(ModelAndNamedQueryRestProviderTest.class.getName());
@Before
- public void setup(){
+ public void setup() {
version = schemaVersions.getDefaultVersion();
logger.info("Starting the setup for the integration tests of Rest Endpoints");
-
- modelAndNamedQueryRestProvider = new ModelAndNamedQueryRestProvider(searchGraph, schemaVersions);
- httpHeaders = mock(HttpHeaders.class);
- uriInfo = mock(UriInfo.class);
+
+ modelAndNamedQueryRestProvider =
+ new ModelAndNamedQueryRestProvider(searchGraph, schemaVersions);
+ httpHeaders = mock(HttpHeaders.class);
+ uriInfo = mock(UriInfo.class);
when(uriInfo.getPath()).thenReturn("JUNITURI");
- headersMultiMap = new MultivaluedHashMap<>();
- queryParameters = Mockito.spy(new MultivaluedHashMap<>());
+ headersMultiMap = new MultivaluedHashMap<>();
+ queryParameters = Mockito.spy(new MultivaluedHashMap<>());
headersMultiMap.add("X-FromAppId", "JUNIT");
headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
@@ -100,16 +103,18 @@ public class ModelAndNamedQueryRestProviderTest extends AAISetup{
when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
- when(httpHeaders.getRequestHeader("X-FromAppId")).thenReturn(Collections.singletonList("JUNIT"));
- when(httpHeaders.getRequestHeader("X-TransactionId")).thenReturn(Collections.singletonList("JUNIT"));
+ when(httpHeaders.getRequestHeader("X-FromAppId"))
+ .thenReturn(Collections.singletonList("JUNIT"));
+ when(httpHeaders.getRequestHeader("X-TransactionId"))
+ .thenReturn(Collections.singletonList("JUNIT"));
when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);
-
when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters);
- // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be very unreasonable
+ // 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);
@@ -123,12 +128,8 @@ public class ModelAndNamedQueryRestProviderTest extends AAISetup{
when(request.getContentType()).thenReturn("application/json");
- Response response = modelAndNamedQueryRestProvider.getNamedQueryResponse(
- httpHeaders,
- request,
- queryParameters,
- uriInfo
- );
+ Response response = modelAndNamedQueryRestProvider.getNamedQueryResponse(httpHeaders,
+ request, queryParameters, uriInfo);
assertNotNull(response);
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
@@ -142,12 +143,8 @@ public class ModelAndNamedQueryRestProviderTest extends AAISetup{
when(httpHeaders.getRequestHeader("X-FromAppId")).thenThrow(IllegalArgumentException.class);
when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
- Response response = modelAndNamedQueryRestProvider.getNamedQueryResponse(
- httpHeaders,
- null,
- "cloud-region",
- uriInfo
- );
+ Response response = modelAndNamedQueryRestProvider.getNamedQueryResponse(httpHeaders, null,
+ "cloud-region", uriInfo);
assertNotNull(response);
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
@@ -165,12 +162,8 @@ public class ModelAndNamedQueryRestProviderTest extends AAISetup{
when(request.getContentType()).thenReturn("application/json");
- Response response = modelAndNamedQueryRestProvider.getNamedQueryResponse(
- httpHeaders,
- request,
- queryParameters,
- uriInfo
- );
+ Response response = modelAndNamedQueryRestProvider.getNamedQueryResponse(httpHeaders,
+ request, queryParameters, uriInfo);
assertNotNull(response);
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
@@ -187,12 +180,8 @@ public class ModelAndNamedQueryRestProviderTest extends AAISetup{
when(request.getContentType()).thenReturn("application/json");
- Response response = modelAndNamedQueryRestProvider.getNamedQueryResponse(
- httpHeaders,
- request,
- queryParameters,
- uriInfo
- );
+ Response response = modelAndNamedQueryRestProvider.getNamedQueryResponse(httpHeaders,
+ request, queryParameters, uriInfo);
assertNotNull(response);
assertEquals(Response.Status.NOT_FOUND.getStatusCode(), response.getStatus());
@@ -200,9 +189,7 @@ public class ModelAndNamedQueryRestProviderTest extends AAISetup{
public String getPayload(String filename) throws IOException {
- InputStream inputStream = getClass()
- .getClassLoader()
- .getResourceAsStream(filename);
+ InputStream inputStream = getClass().getClassLoader().getResourceAsStream(filename);
String message = String.format("Unable to find the %s in src/test/resources", filename);
assertNotNull(message, inputStream);
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/MsoRequestVfModuleTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/MsoRequestVfModuleTest.java
index dfaf3c3..e1edfd6 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/MsoRequestVfModuleTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/MsoRequestVfModuleTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,66 +30,91 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class MsoRequestVfModuleTest extends QueryTest {
- public MsoRequestVfModuleTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //set up test graph
- Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "0", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
- Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf", "vnf-id", "vnfid0","vnf-name", "vnf-name-1", "nf-type", "sample-nf-type");
- Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "2", "aai-node-type","service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name","service-instance-name-1");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserverid0");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "4", "aai-node-type", "tenant", "tenant-id", "tenantid0", "tenant-name", "tenantName0");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type", "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
- Vertex volumegroup = graph.addVertex(T.label, "volume-group", T.id, "6", "aai-node-type", "volume-group", "volume-group-id", "volume-group-id-1", "volume-group-name", "volume-group-name1");
-
-
- Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "10", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-10", "vf-module-name", "vf-module-name10");
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "11", "aai-node-type", "generic-vnf", "vnf-id", "vnfid0","vnf-name", "vnf-name-10", "nf-type", "sample-nf-type1");
- Vertex serviceInstance1 = graph.addVertex(T.label, "service-instance", T.id, "12", "aai-node-type","service-instance", "service-instance-id", "service-instance-id-10", "service-instance-name","service-instance-name-10");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "13", "aai-node-type", "vserver", "vserver-id", "vserverid10");
- Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "14", "aai-node-type", "tenant", "tenant-id", "tenantid10", "tenant-name", "tenantName10");
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "15", "aai-node-type", "cloud-region", "cloud-region-id", "regionid10", "cloud-owner", "cloudOwnername10");
- Vertex volumegroup1 = graph.addVertex(T.label, "volume-group", T.id, "16", "aai-node-type", "volume-group", "volume-group-id", "volume-group-id-10", "volume-group-name", "volume-group-name10");
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addTreeEdge(g, genericvnf,vfmodule);
- rules.addEdge(g, genericvnf, serviceInstance);
- rules.addEdge(g, vserver,vfmodule);
- rules.addTreeEdge(g, vserver,tenant);
- rules.addTreeEdge(g, tenant, cloudregion);
- rules.addEdge(g, vfmodule, volumegroup);
-
- //false
- rules.addTreeEdge(g, genericvnf1, vfmodule1);
- rules.addEdge(g, genericvnf1, serviceInstance1);
- rules.addEdge(g, vserver1,vfmodule1);
- rules.addTreeEdge(g, vserver1, tenant1);
- rules.addTreeEdge(g, tenant1, cloudregion1);
- rules.addEdge(g, vfmodule1, volumegroup1);
+ public MsoRequestVfModuleTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- expectedResult.add(vfmodule);
- expectedResult.add(genericvnf);
- expectedResult.add(serviceInstance);
- expectedResult.add(cloudregion);
- expectedResult.add(volumegroup);
+ @Test
+ public void run() {
+ super.run();
+ }
- }
- @Override
- protected String getQueryName() {
- return "so-request-vfModule";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "vf-module").has("vf-module-id", "vf-module-id-1").has("vf-module-name", "vf-module-name1");
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // set up test graph
+ Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "0", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
+ Vertex genericvnf =
+ graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnfid0", "vnf-name", "vnf-name-1", "nf-type", "sample-nf-type");
+ Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "2",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver",
+ "vserver-id", "vserverid0");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "4", "aai-node-type", "tenant",
+ "tenant-id", "tenantid0", "tenant-name", "tenantName0");
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
+ Vertex volumegroup =
+ graph.addVertex(T.label, "volume-group", T.id, "6", "aai-node-type", "volume-group",
+ "volume-group-id", "volume-group-id-1", "volume-group-name", "volume-group-name1");
+
+ Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "10", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-10", "vf-module-name", "vf-module-name10");
+ Vertex genericvnf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "11", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnfid0", "vnf-name", "vnf-name-10", "nf-type", "sample-nf-type1");
+ Vertex serviceInstance1 = graph.addVertex(T.label, "service-instance", T.id, "12",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-10",
+ "service-instance-name", "service-instance-name-10");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "13", "aai-node-type",
+ "vserver", "vserver-id", "vserverid10");
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "14", "aai-node-type", "tenant",
+ "tenant-id", "tenantid10", "tenant-name", "tenantName10");
+ Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "15", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionid10", "cloud-owner", "cloudOwnername10");
+ Vertex volumegroup1 = graph.addVertex(T.label, "volume-group", T.id, "16", "aai-node-type",
+ "volume-group", "volume-group-id", "volume-group-id-10", "volume-group-name",
+ "volume-group-name10");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addTreeEdge(g, genericvnf, vfmodule);
+ rules.addEdge(g, genericvnf, serviceInstance);
+ rules.addEdge(g, vserver, vfmodule);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addTreeEdge(g, tenant, cloudregion);
+ rules.addEdge(g, vfmodule, volumegroup);
+
+ // false
+ rules.addTreeEdge(g, genericvnf1, vfmodule1);
+ rules.addEdge(g, genericvnf1, serviceInstance1);
+ rules.addEdge(g, vserver1, vfmodule1);
+ rules.addTreeEdge(g, vserver1, tenant1);
+ rules.addTreeEdge(g, tenant1, cloudregion1);
+ rules.addEdge(g, vfmodule1, volumegroup1);
+
+ expectedResult.add(vfmodule);
+ expectedResult.add(genericvnf);
+ expectedResult.add(serviceInstance);
+ expectedResult.add(cloudregion);
+ expectedResult.add(volumegroup);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "so-request-vfModule";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "vf-module").has("vf-module-id", "vf-module-id-1")
+ .has("vf-module-name", "vf-module-name1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/NetworkCollectionByServiceInstanceTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/NetworkCollectionByServiceInstanceTest.java
index bb44704..fee5896 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/NetworkCollectionByServiceInstanceTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/NetworkCollectionByServiceInstanceTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -29,7 +29,7 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-public class NetworkCollectionByServiceInstanceTest extends QueryTest{
+public class NetworkCollectionByServiceInstanceTest extends QueryTest {
public NetworkCollectionByServiceInstanceTest() throws AAIException, NoEdgeRuleFoundException {
super();
}
@@ -38,36 +38,42 @@ public class NetworkCollectionByServiceInstanceTest extends QueryTest{
public void run() {
super.run();
}
+
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "0",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
- //Set up the test graph
- Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "0", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name",
- "service-instance-name-1");
-
- Vertex collection1 = graph.addVertex(T.label, "collection", T.id, "1", "aai-node-type", "collection");
-
- Vertex instancegroup1 = graph.addVertex(T.label, "instance-group", T.id, "2", "aai-node-type", "instance-group",
- "id", "id-0", "instance-group-type", "instance-group-type-0","instance-group-role","instance-group-role-0",
- "instance-group-function","instance-group-function-0","instance-group-description","instance-group-description-0");
-
- Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "3", "aai-node-type", "l3-network");
+ Vertex collection1 =
+ graph.addVertex(T.label, "collection", T.id, "1", "aai-node-type", "collection");
+ Vertex instancegroup1 =
+ graph.addVertex(T.label, "instance-group", T.id, "2", "aai-node-type", "instance-group",
+ "id", "id-0", "instance-group-type", "instance-group-type-0", "instance-group-role",
+ "instance-group-role-0", "instance-group-function", "instance-group-function-0",
+ "instance-group-description", "instance-group-description-0");
+ Vertex l3network1 =
+ graph.addVertex(T.label, "l3-network", T.id, "3", "aai-node-type", "l3-network");
- Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "4", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id-2", "service-instance-name",
- "service-instance-name-1");
+ Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "4",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2",
+ "service-instance-name", "service-instance-name-1");
- Vertex collection2 = graph.addVertex(T.label, "collection", T.id, "5", "aai-node-type", "collection");
+ Vertex collection2 =
+ graph.addVertex(T.label, "collection", T.id, "5", "aai-node-type", "collection");
- Vertex instancegroup2 = graph.addVertex(T.label, "instance-group", T.id, "6", "aai-node-type", "instance-group",
- "id", "id-0", "instance-group-type", "instance-group-type-0","instance-group-role","instance-group-role-0",
- "instance-group-function","instance-group-function-0","instance-group-description","instance-group-description-0");
+ Vertex instancegroup2 =
+ graph.addVertex(T.label, "instance-group", T.id, "6", "aai-node-type", "instance-group",
+ "id", "id-0", "instance-group-type", "instance-group-type-0", "instance-group-role",
+ "instance-group-role-0", "instance-group-function", "instance-group-function-0",
+ "instance-group-description", "instance-group-description-0");
- Vertex l3network2 = graph.addVertex(T.label, "l3-network", T.id, "7", "aai-node-type", "l3-network");
+ Vertex l3network2 =
+ graph.addVertex(T.label, "l3-network", T.id, "7", "aai-node-type", "l3-network");
GraphTraversalSource g = graph.traversal();
@@ -85,13 +91,16 @@ public class NetworkCollectionByServiceInstanceTest extends QueryTest{
expectedResult.add(l3network1);
}
+
@Override
protected String getQueryName() {
return "network-collection-ByServiceInstance";
}
+
@Override
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "service-instance").has("service-instance-id", "service-instance-id-1");
+ g.has("aai-node-type", "service-instance").has("service-instance-id",
+ "service-instance-id-1");
}
@Override
@@ -99,5 +108,3 @@ public class NetworkCollectionByServiceInstanceTest extends QueryTest{
return;
}
}
-
-
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/NetworkNameFromNetworkRoleQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/NetworkNameFromNetworkRoleQueryTest.java
index 9f9dcdf..e4acc25 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/NetworkNameFromNetworkRoleQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/NetworkNameFromNetworkRoleQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -33,55 +33,61 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class NetworkNameFromNetworkRoleQueryTest extends QueryTest {
- public NetworkNameFromNetworkRoleQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public NetworkNameFromNetworkRoleQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex cr1 = graph.addVertex(T.id, "00", "aai-node-type", "cloud-region", "cloud-owner", "foo", "cloud-region-id", "cr1");
- Vertex cr2 = graph.addVertex(T.id, "01", "aai-node-type", "cloud-region", "cloud-owner", "bar", "cloud-region-id", "cr2");
-
- Vertex l3net1 = graph.addVertex(T.id, "10", "aai-node-type", "l3-network",
- "network-id", "net1", "network-name", "netname1", "network-role", "correct-role");
- Vertex l3net2 = graph.addVertex(T.id, "11", "aai-node-type", "l3-network",
- "network-id", "net2", "network-name", "netname2", "network-role", "wrong-role");
- Vertex l3net3 = graph.addVertex(T.id, "12", "aai-node-type", "l3-network",
- "network-id", "net3", "network-name", "netname3", "network-role", "correct-role");
-
- Vertex np1 = graph.addVertex(T.id, "20", "aai-node-type", "network-policy", "network-policy-id", "npId1");
- Vertex np2 = graph.addVertex(T.id, "21", "aai-node-type", "network-policy", "network-policy-id", "npId2");
- Vertex np3 = graph.addVertex(T.id, "22", "aai-node-type", "network-policy", "network-policy-id", "npId3");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, cr1, l3net1);
- rules.addEdge(g, l3net1, np1);
- rules.addEdge(g, cr1, l3net2);
- rules.addEdge(g, l3net2, np2);
- rules.addEdge(g, cr2, l3net3);
- rules.addEdge(g, l3net3, np3);
-
- expectedResult.add(l3net1);
- expectedResult.add(np1);
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex cr1 = graph.addVertex(T.id, "00", "aai-node-type", "cloud-region", "cloud-owner",
+ "foo", "cloud-region-id", "cr1");
+ Vertex cr2 = graph.addVertex(T.id, "01", "aai-node-type", "cloud-region", "cloud-owner",
+ "bar", "cloud-region-id", "cr2");
- @Override
- protected String getQueryName() {
- return "network-name-fromNetwork-role";
- }
+ Vertex l3net1 = graph.addVertex(T.id, "10", "aai-node-type", "l3-network", "network-id",
+ "net1", "network-name", "netname1", "network-role", "correct-role");
+ Vertex l3net2 = graph.addVertex(T.id, "11", "aai-node-type", "l3-network", "network-id",
+ "net2", "network-name", "netname2", "network-role", "wrong-role");
+ Vertex l3net3 = graph.addVertex(T.id, "12", "aai-node-type", "l3-network", "network-id",
+ "net3", "network-name", "netname3", "network-role", "correct-role");
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "cloud-region").has("cloud-owner", "foo").has("cloud-region-id", "cr1");
- }
+ Vertex np1 = graph.addVertex(T.id, "20", "aai-node-type", "network-policy",
+ "network-policy-id", "npId1");
+ Vertex np2 = graph.addVertex(T.id, "21", "aai-node-type", "network-policy",
+ "network-policy-id", "npId2");
+ Vertex np3 = graph.addVertex(T.id, "22", "aai-node-type", "network-policy",
+ "network-policy-id", "npId3");
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("networkRole", "correct-role");
- }
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, cr1, l3net1);
+ rules.addEdge(g, l3net1, np1);
+ rules.addEdge(g, cr1, l3net2);
+ rules.addEdge(g, l3net2, np2);
+ rules.addEdge(g, cr2, l3net3);
+ rules.addEdge(g, l3net3, np3);
+
+ expectedResult.add(l3net1);
+ expectedResult.add(np1);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "network-name-fromNetwork-role";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "cloud-region").has("cloud-owner", "foo").has("cloud-region-id",
+ "cr1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("networkRole", "correct-role");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/NfTypefromCloudRegionQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/NfTypefromCloudRegionQueryTest.java
index 08a52f1..1093fb7 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/NfTypefromCloudRegionQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/NfTypefromCloudRegionQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,53 +30,64 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class NfTypefromCloudRegionQueryTest extends QueryTest {
- public NfTypefromCloudRegionQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public NfTypefromCloudRegionQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "0", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "1", "aai-node-type", "tenant", "tenant-id", "tenantid01", "tenant-name", "tenantName01");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "2", "aai-node-type", "vserver", "vserver-id", "vserver-id-1","vserver-name","vserver-name-1");
- Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1");
-
-
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "4", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-2");
- Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "5", "aai-node-type", "tenant", "tenant-id", "tenantid2", "tenant-name", "tenantName-2");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "6", "aai-node-type", "vserver", "vserver-id", "vserver-id-1","vserver-name","vserver-name-1");
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "7", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1");
-
- GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, tenant,cloudregion);
- rules.addTreeEdge(g, vserver,tenant);
- rules.addEdge(g, vserver, gnvf);
-
- rules.addTreeEdge(g, tenant1,cloudregion1);
- rules.addTreeEdge(g, vserver1,tenant1);
- rules.addEdge(g, vserver1, gnvf1);
-
- expectedResult.add(gnvf);
-
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- @Override
- protected String getQueryName() {
- return "nfType-fromCloudRegion";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("cloud-region-id", "cloud-region-id-1");
-
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ Vertex cloudregion =
+ graph.addVertex(T.label, "cloud-region", T.id, "0", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "1", "aai-node-type", "tenant",
+ "tenant-id", "tenantid01", "tenant-name", "tenantName01");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "2", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
+ Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1");
+
+ Vertex cloudregion1 =
+ graph.addVertex(T.label, "cloud-region", T.id, "4", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-2");
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "5", "aai-node-type", "tenant",
+ "tenant-id", "tenantid2", "tenant-name", "tenantName-2");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "6", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
+ Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "7", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addTreeEdge(g, tenant, cloudregion);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addEdge(g, vserver, gnvf);
+
+ rules.addTreeEdge(g, tenant1, cloudregion1);
+ rules.addTreeEdge(g, vserver1, tenant1);
+ rules.addEdge(g, vserver1, gnvf1);
+
+ expectedResult.add(gnvf);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "nfType-fromCloudRegion";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("cloud-region-id", "cloud-region-id-1");
+
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/OnapQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/OnapQueryTest.java
index 138892c..c137d6f 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/OnapQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/OnapQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,9 +19,15 @@
*/
package org.onap.aai.rest.search;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.when;
+
import com.att.eelf.configuration.EELFManager;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
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.Graph;
@@ -47,167 +53,152 @@ import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.LoaderFactory;
import org.onap.aai.introspection.ModelType;
import org.onap.aai.nodes.NodeIngestor;
+import org.onap.aai.query.builder.GremlinTraversal;
+import org.onap.aai.restcore.search.GremlinGroovyShell;
+import org.onap.aai.restcore.search.GroovyQueryBuilder;
+import org.onap.aai.serialization.db.EdgeSerializer;
+import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
+import org.onap.aai.serialization.engines.QueryStyle;
+import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.setup.AAIConfigTranslator;
import org.onap.aai.setup.SchemaLocationsBean;
import org.onap.aai.setup.SchemaVersion;
import org.onap.aai.setup.SchemaVersions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.onap.aai.query.builder.GremlinTraversal;
-import org.onap.aai.restcore.search.GremlinGroovyShell;
-import org.onap.aai.restcore.search.GroovyQueryBuilder;
-import org.onap.aai.serialization.db.EdgeSerializer;
-import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import java.util.*;
-import java.util.stream.Collectors;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.when;
@RunWith(Parameterized.class)
-@ContextConfiguration(classes = {
- ConfigConfiguration.class,
- AAIConfigTranslator.class,
- EdgeIngestor.class,
- EdgeSerializer.class,
- NodeIngestor.class,
- SpringContextAware.class,
- SearchConfiguration.class,
- IntrospectionConfig.class
-})
-@TestPropertySource(properties = {
- "schema.uri.base.path = /aai",
- "schema.ingest.file = src/test/resources/application-onap-test.properties"
-})
+@ContextConfiguration(
+ classes = {ConfigConfiguration.class, AAIConfigTranslator.class, EdgeIngestor.class,
+ EdgeSerializer.class, NodeIngestor.class, SpringContextAware.class,
+ SearchConfiguration.class, IntrospectionConfig.class})
+@TestPropertySource(
+ properties = {"schema.uri.base.path = /aai",
+ "schema.ingest.file = src/test/resources/application-onap-test.properties"})
public abstract class OnapQueryTest {
- @ClassRule
+ @ClassRule
public static final SpringClassRule springClassRule = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
- protected Logger logger;
- protected Graph graph;
- protected GremlinGroovyShell shell;
- @Mock protected TransactionalGraphEngine dbEngine;
- protected final List<Vertex> expectedResult = new ArrayList<>();
-
- @Autowired
- protected EdgeIngestor edgeRules;
-
- @Autowired
- protected EdgeSerializer rules;
-
- @Autowired
- protected LoaderFactory loaderFactory;
-
- @Autowired
- protected SchemaVersions schemaVersions;
-
- @Autowired
- protected GremlinServerSingleton gremlinServerSingleton;
-
- protected Loader loader;
- protected GraphTraversalSource gts;
-
- @Parameterized.Parameter(value = 0)
- public SchemaVersion version;
-
- @Parameterized.Parameters(name = "Version.{0}")
- public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {new SchemaVersion("v11")},
- {new SchemaVersion("v12")},
- {new SchemaVersion("v13")},
- {new SchemaVersion("v14")}
- });
- }
-
- protected String query;
-
- LinkedHashMap <String, Object> params;
-
- @BeforeClass
- public static void setupBundleconfig() {
- System.setProperty("AJSC_HOME", "./");
- System.setProperty("BUNDLECONFIG_DIR", "src/main/resources/");
- }
-
- @Before
- public void setUp() throws AAIException, NoEdgeRuleFoundException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- System.setProperty("AJSC_HOME", ".");
- System.setProperty("BUNDLECONFIG_DIR", "src/main/resources");
- logger = LoggerFactory.getLogger(getClass());
- MockitoAnnotations.initMocks(this);
- graph = TinkerGraph.open();
- gts = graph.traversal();
- createGraph();
- shell = new GremlinGroovyShell();
- loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, version);
- setUpQuery();
- }
-
-
- protected void setUpQuery() {
- query = gremlinServerSingleton.getStoredQueryFromConfig(getQueryName());
- params = new LinkedHashMap <>();
- addParam(params);
- when(dbEngine.getQueryBuilder(any(QueryStyle.class))).thenReturn(new GremlinTraversal<>(loader, graph.traversal()));
- logger.info("Stored query in abstraction form {}", query);
- query = new GroovyQueryBuilder().executeTraversal(dbEngine, query, params);
- logger.info("After converting to gremlin query {}", query);
- query = "g" + query;
- GraphTraversal<Vertex, Vertex> g = graph.traversal().V();
- addStartNode(g);
- params.put("g", g);
- }
-
- public void run() {
-
- GraphTraversal<Vertex, Vertex> result = (GraphTraversal<Vertex, Vertex>)shell.executeTraversal(query, params);
-
- List<Vertex> vertices = result.toList();
-
- logger.info("Expected result set of vertexes [{}]", convert(expectedResult));
- logger.info("Actual Result set of vertexes [{}]", convert(vertices));
-
- List<Vertex> nonDuplicateExpectedResult = new ArrayList<>(new HashSet<>(expectedResult));
- vertices = new ArrayList<>(new HashSet<>(vertices));
-
- nonDuplicateExpectedResult.sort(Comparator.comparing(vertex -> vertex.id().toString()));
- vertices.sort(Comparator.comparing(vertex -> vertex.id().toString()));
-
-
- // Use this instead of the assertTrue as this provides more useful
- // debugging information such as this when expected and actual differ:
- // java.lang.AssertionError: Expected all the vertices to be found
- // Expected :[v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
- // Actual :[v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
- assertEquals("Expected all the vertices to be found", nonDuplicateExpectedResult, vertices);
-
- }
-
- protected String convert(List<Vertex> vertices){
- return vertices
- .stream()
- .map(vertex -> vertex.property("aai-node-type").value().toString())
- .collect(Collectors.joining(","));
- }
-
- protected abstract void createGraph() throws AAIException, NoEdgeRuleFoundException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException;
-
- protected abstract String getQueryName();
-
- protected abstract void addStartNode(GraphTraversal<Vertex, Vertex> g);
+ protected Logger logger;
+ protected Graph graph;
+ protected GremlinGroovyShell shell;
+ @Mock
+ protected TransactionalGraphEngine dbEngine;
+ protected final List<Vertex> expectedResult = new ArrayList<>();
+
+ @Autowired
+ protected EdgeIngestor edgeRules;
+
+ @Autowired
+ protected EdgeSerializer rules;
+
+ @Autowired
+ protected LoaderFactory loaderFactory;
+
+ @Autowired
+ protected SchemaVersions schemaVersions;
+
+ @Autowired
+ protected GremlinServerSingleton gremlinServerSingleton;
+
+ protected Loader loader;
+ protected GraphTraversalSource gts;
+
+ @Parameterized.Parameter(value = 0)
+ public SchemaVersion version;
+
+ @Parameterized.Parameters(name = "Version.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][] {{new SchemaVersion("v11")}, {new SchemaVersion("v12")},
+ {new SchemaVersion("v13")}, {new SchemaVersion("v14")}});
+ }
+
+ protected String query;
+
+ LinkedHashMap<String, Object> params;
+
+ @BeforeClass
+ public static void setupBundleconfig() {
+ System.setProperty("AJSC_HOME", "./");
+ System.setProperty("BUNDLECONFIG_DIR", "src/main/resources/");
+ }
+
+ @Before
+ public void setUp() throws AAIException, NoEdgeRuleFoundException, EdgeRuleNotFoundException,
+ AmbiguousRuleChoiceException {
+ System.setProperty("AJSC_HOME", ".");
+ System.setProperty("BUNDLECONFIG_DIR", "src/main/resources");
+ logger = LoggerFactory.getLogger(getClass());
+ MockitoAnnotations.initMocks(this);
+ graph = TinkerGraph.open();
+ gts = graph.traversal();
+ createGraph();
+ shell = new GremlinGroovyShell();
+ loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, version);
+ setUpQuery();
+ }
+
+ protected void setUpQuery() {
+ query = gremlinServerSingleton.getStoredQueryFromConfig(getQueryName());
+ params = new LinkedHashMap<>();
+ addParam(params);
+ when(dbEngine.getQueryBuilder(any(QueryStyle.class)))
+ .thenReturn(new GremlinTraversal<>(loader, graph.traversal()));
+ logger.info("Stored query in abstraction form {}", query);
+ query = new GroovyQueryBuilder().executeTraversal(dbEngine, query, params);
+ logger.info("After converting to gremlin query {}", query);
+ query = "g" + query;
+ GraphTraversal<Vertex, Vertex> g = graph.traversal().V();
+ addStartNode(g);
+ params.put("g", g);
+ }
+
+ public void run() {
+
+ GraphTraversal<Vertex, Vertex> result =
+ (GraphTraversal<Vertex, Vertex>) shell.executeTraversal(query, params);
+
+ List<Vertex> vertices = result.toList();
+
+ logger.info("Expected result set of vertexes [{}]", convert(expectedResult));
+ logger.info("Actual Result set of vertexes [{}]", convert(vertices));
+
+ List<Vertex> nonDuplicateExpectedResult = new ArrayList<>(new HashSet<>(expectedResult));
+ vertices = new ArrayList<>(new HashSet<>(vertices));
+
+ nonDuplicateExpectedResult.sort(Comparator.comparing(vertex -> vertex.id().toString()));
+ vertices.sort(Comparator.comparing(vertex -> vertex.id().toString()));
+
+ // Use this instead of the assertTrue as this provides more useful
+ // debugging information such as this when expected and actual differ:
+ // java.lang.AssertionError: Expected all the vertices to be found
+ // Expected :[v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
+ // Actual :[v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
+ assertEquals("Expected all the vertices to be found", nonDuplicateExpectedResult, vertices);
+
+ }
+
+ protected String convert(List<Vertex> vertices) {
+ return vertices.stream().map(vertex -> vertex.property("aai-node-type").value().toString())
+ .collect(Collectors.joining(","));
+ }
+
+ protected abstract void createGraph() throws AAIException, NoEdgeRuleFoundException,
+ EdgeRuleNotFoundException, AmbiguousRuleChoiceException;
- protected abstract void addParam(Map<String, Object> params);
+ protected abstract String getQueryName();
+
+ protected abstract void addStartNode(GraphTraversal<Vertex, Vertex> g);
+
+ protected abstract void addParam(Map<String, Object> params);
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/OwningEntityfromServiceInstance.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/OwningEntityfromServiceInstance.java
index 39e29ec..c4f36dc 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/OwningEntityfromServiceInstance.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/OwningEntityfromServiceInstance.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,8 @@
*/
package org.onap.aai.rest.search;
+import java.util.Map;
+
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.T;
@@ -27,48 +29,52 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-
public class OwningEntityfromServiceInstance extends QueryTest {
- public OwningEntityfromServiceInstance () throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public OwningEntityfromServiceInstance() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- // Set up the test graph
- Vertex service_instance = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id", "service-instance-1");
- Vertex owning_entity = graph.addVertex(T.label, "owning-entity", T.id, "2", "aai-node-type", "owning-entity", "owning-entity-id", "owning-entity-id-1", "owning-entity-name", "owning-entity-name1");
+ // Set up the test graph
+ Vertex service_instance = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-1");
+ Vertex owning_entity = graph.addVertex(T.label, "owning-entity", T.id, "2", "aai-node-type",
+ "owning-entity", "owning-entity-id", "owning-entity-id-1", "owning-entity-name",
+ "owning-entity-name1");
- // adding extra vertices and edges which shouldn't be picked.
- Vertex service_instance2 = graph.addVertex(T.label, "service-instance", T.id, "3", "aai-node-type", "service-instance", "service-instance-id", "service-instance-2");
- Vertex owning_entity2 = graph.addVertex(T.label, "owning-entity", T.id, "4", "aai-node-type", "owning-entity", "owning-entity-id", "owning-entity-id-2", "owning-entity-name", "owning-entity-name2");
+ // adding extra vertices and edges which shouldn't be picked.
+ Vertex service_instance2 = graph.addVertex(T.label, "service-instance", T.id, "3",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-2");
+ Vertex owning_entity2 = graph.addVertex(T.label, "owning-entity", T.id, "4",
+ "aai-node-type", "owning-entity", "owning-entity-id", "owning-entity-id-2",
+ "owning-entity-name", "owning-entity-name2");
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, owning_entity, service_instance);
- rules.addEdge(g, owning_entity2, service_instance2);
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, owning_entity, service_instance);
+ rules.addEdge(g, owning_entity2, service_instance2);
- expectedResult.add(owning_entity);
- }
+ expectedResult.add(owning_entity);
+ }
- @Override
- protected String getQueryName() {
- return "owning-entity-fromService-instance";
- }
+ @Override
+ protected String getQueryName() {
+ return "owning-entity-fromService-instance";
+ }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("service-instance-id", "service-instance-1");
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("service-instance-id", "service-instance-1");
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/PathQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/PathQueryTest.java
index 84d7a59..f405728 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/PathQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/PathQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,21 +19,21 @@
*/
package org.onap.aai.rest.search;
+import java.util.List;
+
import org.apache.tinkerpop.gremlin.process.traversal.Path;
import org.onap.aai.exceptions.AAIException;
-import java.util.List;
-
public abstract class PathQueryTest extends QueryTest {
- protected List<Path> pathList;
+ protected List<Path> pathList;
- public PathQueryTest() throws AAIException {
- super();
- }
+ public PathQueryTest() throws AAIException {
+ super();
+ }
- @Override
- public void run() {
- pathList = (List<Path>)shell.executeTraversal(query, params).toList();
- }
+ @Override
+ public void run() {
+ pathList = (List<Path>) shell.executeTraversal(query, params).toList();
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/PendingTopologyDetailTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/PendingTopologyDetailTest.java
index 9de2607..28dbcb8 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/PendingTopologyDetailTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/PendingTopologyDetailTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,7 +26,6 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
@@ -42,121 +41,158 @@ public class PendingTopologyDetailTest extends QueryTest {
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
-
- Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-0", "vnf-name", "vnf-name-0");
- Vertex platform = graph.addVertex(T.label, "platform", T.id, "2", "aai-node-type", "platform", "platform-name", "platform0");
- Vertex lineofbusiness = graph.addVertex(T.label, "line-of-business", T.id, "3", "aai-node-type", "line-of-business", "line-of-business-name", "business0");
- Vertex servinst = graph.addVertex(T.label, "service-instance", T.id, "4", "aai-node-type", "service-instance", "service-instance-id", "servInstId0", "service-type", "servType0");
- Vertex owningentity = graph.addVertex(T.label, "owning-entity", T.id, "5", "aai-node-type", "owning-entity", "owning-entity-id", "entityId0", "owning-entity-name", "entityName0");
- Vertex project = graph.addVertex(T.label, "project", T.id, "6", "aai-node-type", "project", "project-name", "project0");
- Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "38", "aai-node-type", "vf-module", "vf-module-id", "1");
- Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "7", "aai-node-type", "vnfc", "vnfc-name", "vnfc0", "nfc-naming-code", "namingCode0", "nfc-function", "function0");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "8", "aai-node-type", "vserver", "vserver-id", "vserverid0");
- Vertex linterface = graph.addVertex(T.label, "l-interface", T.id, "9", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0");
- Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "10", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "l3-interface-ipv4-address0");
- Vertex subnet4 = graph.addVertex(T.label, "subnet", T.id, "11", "aai-node-type", "subnet", "subnet-id", "subnet4-id0");
- Vertex l3network4 = graph.addVertex(T.label, "l3-network", T.id, "12", "aai-node-type", "l3-network", "network-id", "network4-id0", "network-name", "network4-name0");
- Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "13", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "l3-interface-ipv6-address0");
- Vertex subnet6 = graph.addVertex(T.label, "subnet", T.id, "14", "aai-node-type", "subnet", "subnet-id", "subnet6-id0");
- Vertex l3network6 = graph.addVertex(T.label, "l3-network", T.id, "15", "aai-node-type", "l3-network", "network-id", "network6-id0", "network-name", "network6-name0");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "16", "aai-node-type", "tenant", "tenant-id", "tenantid0", "tenant-name", "tenantName0");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "17", "aai-node-type", "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "18", "aai-node-type", "pserver", "hostname", "pservername1");
- Vertex complex = graph.addVertex(T.label, "pserver", T.id, "19", "aai-node-type", "complex", "physical-location-id", "locationId", "physical-location-type", "locationType", "physical-location-id", "locationId",
- "city", "cityName", "state", "stateName", "postal-code", "zip", "country", "countryName");
- Vertex vipipv4addresslist = graph.addVertex(T.label, "vip-ipv4-address-list", T.id, "20", "aai-node-type", "vip-ipv4-address-list", "vip-ipv4-address", "vip-ipv4-address0");
- Vertex vipipv6addresslist = graph.addVertex(T.label, "vip-ipv6-address-list", T.id, "21", "aai-node-type", "vip-ipv6-address-list", "vip-ipv6-address", "vip-ipv6-address0");
-
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "40", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
- Vertex platform1 = graph.addVertex(T.label, "platform", T.id, "41", "aai-node-type", "platform", "platform-name", "platform1");
-
- Vertex vfmodule2 = graph.addVertex(T.label, "vf-module", T.id, "39", "aai-node-type", "vf-module", "vf-module-id", "2");
- Vertex genericvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "30", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-2", "vnf-name", "vnf-name2");
- Vertex vnfc2 = graph.addVertex(T.label, "vnfc", T.id, "31", "aai-node-type", "vnfc", "vnfc-name", "vnfc2", "nfc-naming-code", "namingCode2", "nfc-function", "function2");
- Vertex vipipv4addresslist2 = graph.addVertex(T.label, "vip-ipv4-address-list", T.id, "32", "aai-node-type", "vip-ipv4-address-list", "vip-ipv4-addres", "vip-ipv4-address2");
- Vertex vipipv6addresslist2 = graph.addVertex(T.label, "vip-ipv6-address-list", T.id, "33", "aai-node-type", "vip-ipv6-address-list", "vip-ipv6-address", "vip-ipv6-address2");
- Vertex subnet42 = graph.addVertex(T.label, "subnet", T.id, "34", "aai-node-type", "subnet", "subnet-id", "subnet4-id-0");
- Vertex l3network42 = graph.addVertex(T.label, "l3-network", T.id, "35", "aai-node-type", "l3-network", "network-id", "network4-id2", "network-name", "network4-name2");
- Vertex subnet62 = graph.addVertex(T.label, "subnet", T.id, "36", "aai-node-type", "subnet", "subnet-id", "subnet6-id2");
- Vertex l3network62 = graph.addVertex(T.label, "l3-network", T.id, "37", "aai-node-type", "l3-network", "network-id", "network6-id2", "network-name", "network6-name2");
-
+ // Set up the test graph
+
+ Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-0", "vnf-name", "vnf-name-0");
+ Vertex platform = graph.addVertex(T.label, "platform", T.id, "2", "aai-node-type",
+ "platform", "platform-name", "platform0");
+ Vertex lineofbusiness = graph.addVertex(T.label, "line-of-business", T.id, "3",
+ "aai-node-type", "line-of-business", "line-of-business-name", "business0");
+ Vertex servinst = graph.addVertex(T.label, "service-instance", T.id, "4", "aai-node-type",
+ "service-instance", "service-instance-id", "servInstId0", "service-type", "servType0");
+ Vertex owningentity = graph.addVertex(T.label, "owning-entity", T.id, "5", "aai-node-type",
+ "owning-entity", "owning-entity-id", "entityId0", "owning-entity-name", "entityName0");
+ Vertex project = graph.addVertex(T.label, "project", T.id, "6", "aai-node-type", "project",
+ "project-name", "project0");
+ Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "38", "aai-node-type",
+ "vf-module", "vf-module-id", "1");
+ Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "7", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfc0", "nfc-naming-code", "namingCode0", "nfc-function", "function0");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "8", "aai-node-type", "vserver",
+ "vserver-id", "vserverid0");
+ Vertex linterface =
+ graph.addVertex(T.label, "l-interface", T.id, "9", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0");
+ Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "10", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address0");
+ Vertex subnet4 = graph.addVertex(T.label, "subnet", T.id, "11", "aai-node-type", "subnet",
+ "subnet-id", "subnet4-id0");
+ Vertex l3network4 = graph.addVertex(T.label, "l3-network", T.id, "12", "aai-node-type",
+ "l3-network", "network-id", "network4-id0", "network-name", "network4-name0");
+ Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "13", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address0");
+ Vertex subnet6 = graph.addVertex(T.label, "subnet", T.id, "14", "aai-node-type", "subnet",
+ "subnet-id", "subnet6-id0");
+ Vertex l3network6 = graph.addVertex(T.label, "l3-network", T.id, "15", "aai-node-type",
+ "l3-network", "network-id", "network6-id0", "network-name", "network6-name0");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "16", "aai-node-type", "tenant",
+ "tenant-id", "tenantid0", "tenant-name", "tenantName0");
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "17", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "18", "aai-node-type", "pserver",
+ "hostname", "pservername1");
+ Vertex complex = graph.addVertex(T.label, "pserver", T.id, "19", "aai-node-type", "complex",
+ "physical-location-id", "locationId", "physical-location-type", "locationType",
+ "physical-location-id", "locationId", "city", "cityName", "state", "stateName",
+ "postal-code", "zip", "country", "countryName");
+ Vertex vipipv4addresslist = graph.addVertex(T.label, "vip-ipv4-address-list", T.id, "20",
+ "aai-node-type", "vip-ipv4-address-list", "vip-ipv4-address", "vip-ipv4-address0");
+ Vertex vipipv6addresslist = graph.addVertex(T.label, "vip-ipv6-address-list", T.id, "21",
+ "aai-node-type", "vip-ipv6-address-list", "vip-ipv6-address", "vip-ipv6-address0");
+
+ Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "40", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
+ Vertex platform1 = graph.addVertex(T.label, "platform", T.id, "41", "aai-node-type",
+ "platform", "platform-name", "platform1");
+
+ Vertex vfmodule2 = graph.addVertex(T.label, "vf-module", T.id, "39", "aai-node-type",
+ "vf-module", "vf-module-id", "2");
+ Vertex genericvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "30", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-2", "vnf-name", "vnf-name2");
+ Vertex vnfc2 = graph.addVertex(T.label, "vnfc", T.id, "31", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfc2", "nfc-naming-code", "namingCode2", "nfc-function", "function2");
+ Vertex vipipv4addresslist2 = graph.addVertex(T.label, "vip-ipv4-address-list", T.id, "32",
+ "aai-node-type", "vip-ipv4-address-list", "vip-ipv4-addres", "vip-ipv4-address2");
+ Vertex vipipv6addresslist2 = graph.addVertex(T.label, "vip-ipv6-address-list", T.id, "33",
+ "aai-node-type", "vip-ipv6-address-list", "vip-ipv6-address", "vip-ipv6-address2");
+ Vertex subnet42 = graph.addVertex(T.label, "subnet", T.id, "34", "aai-node-type", "subnet",
+ "subnet-id", "subnet4-id-0");
+ Vertex l3network42 = graph.addVertex(T.label, "l3-network", T.id, "35", "aai-node-type",
+ "l3-network", "network-id", "network4-id2", "network-name", "network4-name2");
+ Vertex subnet62 = graph.addVertex(T.label, "subnet", T.id, "36", "aai-node-type", "subnet",
+ "subnet-id", "subnet6-id2");
+ Vertex l3network62 = graph.addVertex(T.label, "l3-network", T.id, "37", "aai-node-type",
+ "l3-network", "network-id", "network6-id2", "network-name", "network6-name2");
+
GraphTraversalSource g = graph.traversal();
rules.addEdge(g, genericvnf, platform);
- rules.addEdge(g, genericvnf, lineofbusiness);
- rules.addEdge(g, genericvnf, servinst);
- rules.addEdge(g, owningentity, servinst);
- rules.addEdge(g, project, servinst);
- rules.addTreeEdge(g, genericvnf, vfmodule);
- rules.addEdge(g, vfmodule, vnfc);
- //rules.addEdge(g, genericvnf, vnfc);
- rules.addEdge(g, vnfc, vserver);
- rules.addTreeEdge(g, vserver, tenant);
- rules.addTreeEdge(g, tenant, cloudregion);
- rules.addEdge(g, pserver, vserver);
- rules.addEdge(g, complex, pserver);
- rules.addTreeEdge(g, linterface, vserver);
- rules.addTreeEdge(g, l3inter1ipv4addresslist, linterface);
- rules.addEdge(g, l3inter1ipv4addresslist, subnet4);
- rules.addTreeEdge(g, l3network4, subnet4);
- rules.addTreeEdge(g, vnfc, l3inter1ipv4addresslist);
- rules.addTreeEdge(g, l3inter1ipv6addresslist, linterface);
- rules.addEdge(g, l3inter1ipv6addresslist, subnet6);
- rules.addTreeEdge(g, l3network6, subnet6);
- rules.addTreeEdge(g, vnfc, l3inter1ipv6addresslist);
- rules.addTreeEdge(g, vipipv4addresslist, cloudregion);
- rules.addEdge(g, vipipv4addresslist, subnet4);
- rules.addEdge(g, vnfc, vipipv4addresslist);
- rules.addTreeEdge(g, vipipv6addresslist, cloudregion);
- rules.addEdge(g, vipipv6addresslist, subnet6);
- rules.addEdge(g, vnfc, vipipv6addresslist);
-
- rules.addEdge(g, genericvnf, platform1);
-
-
- // false
- rules.addTreeEdge(g, genericvnf2, vfmodule2);
+ rules.addEdge(g, genericvnf, lineofbusiness);
+ rules.addEdge(g, genericvnf, servinst);
+ rules.addEdge(g, owningentity, servinst);
+ rules.addEdge(g, project, servinst);
+ rules.addTreeEdge(g, genericvnf, vfmodule);
+ rules.addEdge(g, vfmodule, vnfc);
+ // rules.addEdge(g, genericvnf, vnfc);
+ rules.addEdge(g, vnfc, vserver);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addTreeEdge(g, tenant, cloudregion);
+ rules.addEdge(g, pserver, vserver);
+ rules.addEdge(g, complex, pserver);
+ rules.addTreeEdge(g, linterface, vserver);
+ rules.addTreeEdge(g, l3inter1ipv4addresslist, linterface);
+ rules.addEdge(g, l3inter1ipv4addresslist, subnet4);
+ rules.addTreeEdge(g, l3network4, subnet4);
+ rules.addTreeEdge(g, vnfc, l3inter1ipv4addresslist);
+ rules.addTreeEdge(g, l3inter1ipv6addresslist, linterface);
+ rules.addEdge(g, l3inter1ipv6addresslist, subnet6);
+ rules.addTreeEdge(g, l3network6, subnet6);
+ rules.addTreeEdge(g, vnfc, l3inter1ipv6addresslist);
+ rules.addTreeEdge(g, vipipv4addresslist, cloudregion);
+ rules.addEdge(g, vipipv4addresslist, subnet4);
+ rules.addEdge(g, vnfc, vipipv4addresslist);
+ rules.addTreeEdge(g, vipipv6addresslist, cloudregion);
+ rules.addEdge(g, vipipv6addresslist, subnet6);
+ rules.addEdge(g, vnfc, vipipv6addresslist);
+
+ rules.addEdge(g, genericvnf, platform1);
+
+ // false
+ rules.addTreeEdge(g, genericvnf2, vfmodule2);
rules.addEdge(g, vfmodule2, vnfc2);
- rules.addTreeEdge(g, vipipv4addresslist2, cloudregion);
- rules.addTreeEdge(g, vipipv6addresslist2, cloudregion);
- rules.addEdge(g, vnfc2, vipipv4addresslist2);
- rules.addEdge(g, vnfc2, vipipv6addresslist2);
- rules.addEdge(g, vipipv4addresslist2, subnet42);
- rules.addEdge(g, vipipv6addresslist2, subnet62);
- rules.addTreeEdge(g, l3network42, subnet42);
- rules.addTreeEdge(g, l3network62, subnet62);
-
- rules.addEdge(g, genericvnf1, lineofbusiness);
-
-
- expectedResult.add(genericvnf);
- expectedResult.add(platform);
- expectedResult.add(lineofbusiness);
- expectedResult.add(owningentity);
- expectedResult.add(project);
- expectedResult.add(vfmodule);
- expectedResult.add(vnfc);
- expectedResult.add(l3inter1ipv4addresslist);
- expectedResult.add(subnet4);
- expectedResult.add(l3network4);
- expectedResult.add(l3inter1ipv6addresslist);
- expectedResult.add(subnet6);
- expectedResult.add(l3network6);
- expectedResult.add(vipipv4addresslist);
- expectedResult.add(vipipv6addresslist);
-
- expectedResult.add(platform1);
+ rules.addTreeEdge(g, vipipv4addresslist2, cloudregion);
+ rules.addTreeEdge(g, vipipv6addresslist2, cloudregion);
+ rules.addEdge(g, vnfc2, vipipv4addresslist2);
+ rules.addEdge(g, vnfc2, vipipv6addresslist2);
+ rules.addEdge(g, vipipv4addresslist2, subnet42);
+ rules.addEdge(g, vipipv6addresslist2, subnet62);
+ rules.addTreeEdge(g, l3network42, subnet42);
+ rules.addTreeEdge(g, l3network62, subnet62);
+
+ rules.addEdge(g, genericvnf1, lineofbusiness);
+
+ expectedResult.add(genericvnf);
+ expectedResult.add(platform);
+ expectedResult.add(lineofbusiness);
+ expectedResult.add(owningentity);
+ expectedResult.add(project);
+ expectedResult.add(vfmodule);
+ expectedResult.add(vnfc);
+ expectedResult.add(l3inter1ipv4addresslist);
+ expectedResult.add(subnet4);
+ expectedResult.add(l3network4);
+ expectedResult.add(l3inter1ipv6addresslist);
+ expectedResult.add(subnet6);
+ expectedResult.add(l3network6);
+ expectedResult.add(vipipv4addresslist);
+ expectedResult.add(vipipv6addresslist);
+
+ expectedResult.add(platform1);
}
@Override
protected String getQueryName() {
- return "pending-topology-detail";
+ return "pending-topology-detail";
}
+
@Override
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "generic-vnf").has("vnf-id", "vnf-id-0");
+ g.has("aai-node-type", "generic-vnf").has("vnf-id", "vnf-id-0");
}
+
@Override
protected void addParam(Map<String, Object> params) {
return;
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/PnfTopologyQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/PnfTopologyQueryTest.java
index 21da962..b501ed6 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/PnfTopologyQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/PnfTopologyQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
package org.onap.aai.rest.search;
+
import java.util.Map;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
@@ -26,80 +27,94 @@ import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Ignore;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class PnfTopologyQueryTest extends QueryTest {
- public PnfTopologyQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "0", "aai-node-type", "pnf", "pnf-name", "pnf1name");
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "1", "aai-node-type", "complex", "physical-location-id", "clli");
- Vertex pnf1int1 = graph.addVertex(T.label, "p-interface", T.id, "2", "aai-node-type", "p-interface", "interface-name", "ge0/0/0");
- Vertex pnf1int2 = graph.addVertex(T.label, "p-interface", T.id, "3", "aai-node-type", "p-interface", "interface-name", "ge0/0/1");
- Vertex pnf1int3 = graph.addVertex(T.label, "p-interface", T.id, "4", "aai-node-type", "p-interface", "interface-name", "ge0/0/2");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver", "hostname", "pservername");
- Vertex pserverint = graph.addVertex(T.label, "p-interface", T.id, "6", "aai-node-type", "p-interface", "interface-name", "xe0/0/0");
- Vertex plink1 = graph.addVertex(T.label, "physical-link", T.id, "7", "aai-node-type", "physical-link", "link-name", "ge0/0/0-to-xe0/0/0");
- Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "8", "aai-node-type", "pnf", "pnf-name", "pnf2name");
- Vertex pnf2int = graph.addVertex(T.label, "p-interface", T.id, "9", "aai-node-type", "p-interface", "interface-name", "ge0/1/0");
- Vertex plink2 = graph.addVertex(T.label, "physical-link", T.id, "10", "aai-node-type", "physical-link", "link-name", "ge0/0/1-to-ge0/1/0");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type", "vserver", "vserver-name", "vservername");
- Vertex pserverint2 = graph.addVertex(T.label, "p-interface", T.id, "12", "aai-node-type", "p-interface", "interface-name", "xe0/0/1");
- Vertex pnf2int2 = graph.addVertex(T.label, "p-interface", T.id, "13", "aai-node-type", "p-interface", "interface-name", "ge0/1/0");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, pnf1, complex);
- rules.addTreeEdge(g, pnf1, pnf1int1);
- rules.addTreeEdge(g, pnf1, pnf1int2);
- rules.addTreeEdge(g, pnf1, pnf1int3);
- rules.addEdge(g, pserver, complex);
- rules.addTreeEdge(g, pserver, pserverint);
- rules.addEdge(g, pnf1int1, plink1);
- rules.addEdge(g, pserverint, plink1);
- rules.addEdge(g, pnf2, complex);
- rules.addTreeEdge(g, pnf2, pnf2int);
- rules.addEdge(g, pnf1int2, plink2);
- rules.addEdge(g, pnf2int, plink2);
- rules.addEdge(g, vserver, pserver);
- rules.addTreeEdge(g, pserver, pserverint2);
- rules.addTreeEdge(g, pnf2, pnf2int2);
+ public PnfTopologyQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "0", "aai-node-type", "pnf", "pnf-name",
+ "pnf1name");
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "1", "aai-node-type", "complex",
+ "physical-location-id", "clli");
+ Vertex pnf1int1 = graph.addVertex(T.label, "p-interface", T.id, "2", "aai-node-type",
+ "p-interface", "interface-name", "ge0/0/0");
+ Vertex pnf1int2 = graph.addVertex(T.label, "p-interface", T.id, "3", "aai-node-type",
+ "p-interface", "interface-name", "ge0/0/1");
+ Vertex pnf1int3 = graph.addVertex(T.label, "p-interface", T.id, "4", "aai-node-type",
+ "p-interface", "interface-name", "ge0/0/2");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver",
+ "hostname", "pservername");
+ Vertex pserverint = graph.addVertex(T.label, "p-interface", T.id, "6", "aai-node-type",
+ "p-interface", "interface-name", "xe0/0/0");
+ Vertex plink1 = graph.addVertex(T.label, "physical-link", T.id, "7", "aai-node-type",
+ "physical-link", "link-name", "ge0/0/0-to-xe0/0/0");
+ Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "8", "aai-node-type", "pnf", "pnf-name",
+ "pnf2name");
+ Vertex pnf2int = graph.addVertex(T.label, "p-interface", T.id, "9", "aai-node-type",
+ "p-interface", "interface-name", "ge0/1/0");
+ Vertex plink2 = graph.addVertex(T.label, "physical-link", T.id, "10", "aai-node-type",
+ "physical-link", "link-name", "ge0/0/1-to-ge0/1/0");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type", "vserver",
+ "vserver-name", "vservername");
+ Vertex pserverint2 = graph.addVertex(T.label, "p-interface", T.id, "12", "aai-node-type",
+ "p-interface", "interface-name", "xe0/0/1");
+ Vertex pnf2int2 = graph.addVertex(T.label, "p-interface", T.id, "13", "aai-node-type",
+ "p-interface", "interface-name", "ge0/1/0");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, pnf1, complex);
+ rules.addTreeEdge(g, pnf1, pnf1int1);
+ rules.addTreeEdge(g, pnf1, pnf1int2);
+ rules.addTreeEdge(g, pnf1, pnf1int3);
+ rules.addEdge(g, pserver, complex);
+ rules.addTreeEdge(g, pserver, pserverint);
+ rules.addEdge(g, pnf1int1, plink1);
+ rules.addEdge(g, pserverint, plink1);
+ rules.addEdge(g, pnf2, complex);
+ rules.addTreeEdge(g, pnf2, pnf2int);
+ rules.addEdge(g, pnf1int2, plink2);
+ rules.addEdge(g, pnf2int, plink2);
+ rules.addEdge(g, vserver, pserver);
+ rules.addTreeEdge(g, pserver, pserverint2);
+ rules.addTreeEdge(g, pnf2, pnf2int2);
+
+ expectedResult.add(pnf1);
+ expectedResult.add(complex);
+ expectedResult.add(pnf1int1);
+ expectedResult.add(pnf1int2);
+ expectedResult.add(pserver);
+ expectedResult.add(pserverint);
+ expectedResult.add(plink1);
+ expectedResult.add(pnf2);
+ expectedResult.add(pnf2int);
+ expectedResult.add(plink2);
+ }
- expectedResult.add(pnf1);
- expectedResult.add(complex);
- expectedResult.add(pnf1int1);
- expectedResult.add(pnf1int2);
- expectedResult.add(pserver);
- expectedResult.add(pserverint);
- expectedResult.add(plink1);
- expectedResult.add(pnf2);
- expectedResult.add(pnf2int);
- expectedResult.add(plink2);
- }
+ @Override
+ protected String getQueryName() {
+ // TODO Auto-generated method stub
+ return "pnf-topology";
+ }
- @Override
- protected String getQueryName() {
- // TODO Auto-generated method stub
- return "pnf-topology";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("pnf-name", "pnf1name");
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("pnf-name", "pnf1name");
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverFromFqdnFirstTokenTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverFromFqdnFirstTokenTest.java
index 6b3fcb2..6601e9a 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverFromFqdnFirstTokenTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverFromFqdnFirstTokenTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,7 +19,6 @@
*/
package org.onap.aai.rest.search;
-
import java.util.Map;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
@@ -31,44 +30,52 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class PserverFromFqdnFirstTokenTest extends QueryTest {
- public PserverFromFqdnFirstTokenTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public PserverFromFqdnFirstTokenTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void test() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver",
+ "hostname", "hostname-10", "fqdn", "fqdn-1.abc.com", "source-of-truth", "RCT");
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver",
+ "hostname", "hostname-20", "fqdn", "fqdn-2.abc.com", "source-of-truth", "RCT");
+ Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "6", "aai-node-type", "pserver",
+ "hostname", "hostname-30", "fqdn", "fqdn-13.abc.com", "source-of-truth", "AAIRctFeed");
+ Vertex pserver4 = graph.addVertex(T.label, "pserver", T.id, "7", "aai-node-type", "pserver",
+ "hostname", "hostname-40", "fqdn", "fqdn-12.abc.com", "source-of-truth", "RO");
+ Vertex pserver5 = graph.addVertex(T.label, "pserver", T.id, "8", "aai-node-type", "pserver",
+ "hostname", "hostname-50", "fqdn", "fqdn-20.abc.com", "source-of-truth", "RO");
- @Test
- public void test() {
- super.run();
- }
+ expectedResult.add(pserver1);
+ expectedResult.add(pserver3);
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver", "hostname", "hostname-10", "fqdn", "fqdn-1.abc.com", "source-of-truth", "RCT");
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver", "hostname", "hostname-20", "fqdn", "fqdn-2.abc.com", "source-of-truth", "RCT");
- Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "6", "aai-node-type", "pserver", "hostname", "hostname-30", "fqdn", "fqdn-13.abc.com", "source-of-truth", "AAIRctFeed");
- Vertex pserver4 = graph.addVertex(T.label, "pserver", T.id, "7", "aai-node-type", "pserver", "hostname", "hostname-40", "fqdn", "fqdn-12.abc.com", "source-of-truth", "RO");
- Vertex pserver5 = graph.addVertex(T.label, "pserver", T.id, "8", "aai-node-type", "pserver", "hostname", "hostname-50", "fqdn", "fqdn-20.abc.com", "source-of-truth", "RO");
-
- expectedResult.add(pserver1);
- expectedResult.add(pserver3);
+ }
- }
+ @Override
+ protected String getQueryName() {
+ return "pserver-fromFqdnFirstToken";
+ }
- @Override
- protected String getQueryName() {
- return "pserver-fromFqdnFirstToken";
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "pserver");
+ }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type","pserver");
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("fqdnFirstToken", "fqdn-1");
+ params.put("sourcesOfTruth", "RCT', 'AAIRctFeed"); // placement of single quotes is
+ // intentional, values between the first
+ // and last values must be in single
+ // quotes
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("fqdnFirstToken", "fqdn-1");
- params.put("sourcesOfTruth", "RCT', 'AAIRctFeed"); //placement of single quotes is intentional, values between the first and last values must be in single quotes
-
- }
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverFromHostnameFirstTokenTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverFromHostnameFirstTokenTest.java
index 9fe290b..680bba9 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverFromHostnameFirstTokenTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverFromHostnameFirstTokenTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,7 +19,6 @@
*/
package org.onap.aai.rest.search;
-
import java.util.Map;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
@@ -31,45 +30,52 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class PserverFromHostnameFirstTokenTest extends QueryTest {
- public PserverFromHostnameFirstTokenTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public PserverFromHostnameFirstTokenTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void test() {
+ super.run();
+ }
- @Test
- public void test() {
- super.run();
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver",
+ "hostname", "hostname-1.abc.com", "source-of-truth", "RO");
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver",
+ "hostname", "hostname-2.abc.com", "source-of-truth", "RO");
+ Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "6", "aai-node-type", "pserver",
+ "hostname", "hostname-13.abc.com", "source-of-truth", "AAI-EXTENSIONS");
+ Vertex pserver4 = graph.addVertex(T.label, "pserver", T.id, "7", "aai-node-type", "pserver",
+ "hostname", "hostname-12.abc.com", "source-of-truth", "RCT");
+ Vertex pserver5 = graph.addVertex(T.label, "pserver", T.id, "8", "aai-node-type", "pserver",
+ "hostname", "hostname-20.abc.com", "source-of-truth", "RO");
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver", "hostname", "hostname-1.abc.com", "source-of-truth", "RO");
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver", "hostname", "hostname-2.abc.com", "source-of-truth", "RO");
- Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "6", "aai-node-type", "pserver", "hostname", "hostname-13.abc.com", "source-of-truth", "AAI-EXTENSIONS");
- Vertex pserver4 = graph.addVertex(T.label, "pserver", T.id, "7", "aai-node-type", "pserver", "hostname", "hostname-12.abc.com", "source-of-truth", "RCT");
- Vertex pserver5 = graph.addVertex(T.label, "pserver", T.id, "8", "aai-node-type", "pserver", "hostname", "hostname-20.abc.com", "source-of-truth", "RO");
+ expectedResult.add(pserver1);
+ expectedResult.add(pserver3);
-
- expectedResult.add(pserver1);
- expectedResult.add(pserver3);
+ }
- }
+ @Override
+ protected String getQueryName() {
+ return "pserver-fromHostnameFirstToken";
+ }
- @Override
- protected String getQueryName() {
- return "pserver-fromHostnameFirstToken";
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "pserver");
+ }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type","pserver");
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("hostnameFirstToken", "hostname-1");
+ params.put("sourcesOfTruth", "RO', 'AAI-EXTENSIONS"); // placement of single quotes is
+ // intentional, values between the
+ // first and last values must be in
+ // single quotes
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("hostnameFirstToken", "hostname-1");
- params.put("sourcesOfTruth", "RO', 'AAI-EXTENSIONS"); //placement of single quotes is intentional, values between the first and last values must be in single quotes
-
- }
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverfromConfigurationFilterInterfaceIdTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverfromConfigurationFilterInterfaceIdTest.java
index eb0fd25..26f5005 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverfromConfigurationFilterInterfaceIdTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverfromConfigurationFilterInterfaceIdTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,83 +26,94 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class PserverfromConfigurationFilterInterfaceIdTest extends QueryTest {
- public PserverfromConfigurationFilterInterfaceIdTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public PserverfromConfigurationFilterInterfaceIdTest()
+ throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex config1 = graph.addVertex(T.label, "configuration", T.id, "1", "aai-node-type",
+ "configuration", "configuration-id", "configuration1");
+ Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid1");
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "3", "aai-node-type", "pserver",
+ "hostname", "pservername1");
+ Vertex loglink1 =
+ graph.addVertex(T.label, "logical-link", T.id, "4", "aai-node-type", "logical-link",
+ "link-name", "loglink1", "in-maint", "false", "link-type", "link-type1");
+ Vertex lint1 = graph.addVertex(T.label, "l-interface", T.id, "5", "aai-node-type",
+ "l-interface", "interface-name", "lint1", "is-port-mirrored", "true", "in-maint",
+ "true", "is-ip-unnumbered", "false", "interface-id", "interface-id1");
+ Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "17", "aai-node-type", "pnf",
+ "pnf-name", "pnf1name", "equip-vendor", "equip-vendor1", "equip-model", "equip-model1");
- // Set up the test graph
- Vertex config1 = graph.addVertex(T.label, "configuration", T.id, "1", "aai-node-type", "configuration", "configuration-id", "configuration1");
- Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type", "generic-vnf", "vnf-id", "vnfid1");
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "3", "aai-node-type", "pserver", "hostname", "pservername1");
- Vertex loglink1 = graph.addVertex(T.label, "logical-link", T.id, "4", "aai-node-type", "logical-link", "link-name", "loglink1", "in-maint", "false",
- "link-type", "link-type1");
- Vertex lint1 = graph.addVertex(T.label, "l-interface", T.id, "5", "aai-node-type", "l-interface", "interface-name", "lint1", "is-port-mirrored", "true",
- "in-maint", "true", "is-ip-unnumbered", "false", "interface-id", "interface-id1");
- Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "17", "aai-node-type", "pnf", "pnf-name", "pnf1name", "equip-vendor", "equip-vendor1", "equip-model",
- "equip-model1");
-
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "22", "aai-node-type", "vserver", "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "22", "aai-node-type",
+ "vserver", "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
- // Following are extra nodes that should not be picked up in
- // expectedResults
- Vertex config2 = graph.addVertex(T.label, "configuration", T.id, "11", "aai-node-type", "configuration", "configuration-id", "configuration2");
- Vertex gvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "12", "aai-node-type", "generic-vnf", "vnf-id", "vnfid2");
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "13", "aai-node-type", "pserver", "hostname", "pservername2");
- Vertex loglink2 = graph.addVertex(T.label, "logical-link", T.id, "14", "aai-node-type", "logical-link", "link-name", "loglink2", "in-maint", "false",
- "link-type", "link-type2");
- Vertex lint2 = graph.addVertex(T.label, "l-interface", T.id, "15", "aai-node-type", "l-interface", "interface-name", "lint1", "is-port-mirrored",
- "true", "in-maint", "true", "is-ip-unnumbered", "false", "interface-id", "interface-id2");
+ // Following are extra nodes that should not be picked up in
+ // expectedResults
+ Vertex config2 = graph.addVertex(T.label, "configuration", T.id, "11", "aai-node-type",
+ "configuration", "configuration-id", "configuration2");
+ Vertex gvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "12", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid2");
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "13", "aai-node-type",
+ "pserver", "hostname", "pservername2");
+ Vertex loglink2 =
+ graph.addVertex(T.label, "logical-link", T.id, "14", "aai-node-type", "logical-link",
+ "link-name", "loglink2", "in-maint", "false", "link-type", "link-type2");
+ Vertex lint2 = graph.addVertex(T.label, "l-interface", T.id, "15", "aai-node-type",
+ "l-interface", "interface-name", "lint1", "is-port-mirrored", "true", "in-maint",
+ "true", "is-ip-unnumbered", "false", "interface-id", "interface-id2");
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, config1, loglink1);
- rules.addEdge(g, config1, loglink2);
- rules.addEdge(g, lint1, loglink1);
- rules.addEdge(g, lint2, loglink1);
- rules.addTreeEdge(g, vserver1,lint1);
- rules.addEdge(g, vserver1, pserver1);
- rules.addEdge(g, loglink1, gvnf1);
- rules.addEdge(g, gvnf1, pnf1);
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, config1, loglink1);
+ rules.addEdge(g, config1, loglink2);
+ rules.addEdge(g, lint1, loglink1);
+ rules.addEdge(g, lint2, loglink1);
+ rules.addTreeEdge(g, vserver1, lint1);
+ rules.addEdge(g, vserver1, pserver1);
+ rules.addEdge(g, loglink1, gvnf1);
+ rules.addEdge(g, gvnf1, pnf1);
- // These should not be picked up in expectedResults
- //rules.addEdge(g, config2, loglink2);
- rules.addEdge(g, loglink2, pserver2);
- rules.addEdge(g, loglink2, gvnf2);
+ // These should not be picked up in expectedResults
+ // rules.addEdge(g, config2, loglink2);
+ rules.addEdge(g, loglink2, pserver2);
+ rules.addEdge(g, loglink2, gvnf2);
- // Note lint2 is not in expectedResults as the filter is based on
- // interface-id1
- expectedResult.add(config1);
- expectedResult.add(lint1);
- expectedResult.add(pserver1);
- expectedResult.add(gvnf1);
- expectedResult.add(pnf1);
+ // Note lint2 is not in expectedResults as the filter is based on
+ // interface-id1
+ expectedResult.add(config1);
+ expectedResult.add(lint1);
+ expectedResult.add(pserver1);
+ expectedResult.add(gvnf1);
+ expectedResult.add(pnf1);
- }
+ }
- @Override
- protected String getQueryName() {
- return "pserver-fromConfigurationFilterInterfaceId";
- }
+ @Override
+ protected String getQueryName() {
+ return "pserver-fromConfigurationFilterInterfaceId";
+ }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("configuration-id", "configuration1");
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("configuration-id", "configuration1");
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("interfaceId", "interface-id1");
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("interfaceId", "interface-id1");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverfromConfigurationTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverfromConfigurationTest.java
index 8a39e1d..5808866 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverfromConfigurationTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/PserverfromConfigurationTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,83 +26,93 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class PserverfromConfigurationTest extends QueryTest {
- public PserverfromConfigurationTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public PserverfromConfigurationTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- // Set up the test graph
- Vertex config1 = graph.addVertex(T.label, "configuration", T.id, "1", "aai-node-type", "configuration", "configuration-id", "configuration1");
- Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type", "generic-vnf", "vnf-id", "vnfid1");
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "3", "aai-node-type", "pserver", "hostname", "pservername1");
- Vertex loglink1 = graph.addVertex(T.label, "logical-link", T.id, "4", "aai-node-type", "logical-link", "link-name", "loglink1", "in-maint", "false",
- "link-type", "link-type1");
- Vertex lint1 = graph.addVertex(T.label, "l-interface", T.id, "5", "aai-node-type", "l-interface", "interface-name", "lint1", "is-port-mirrored", "true",
- "in-maint", "true", "is-ip-unnumbered", "false", "interface-id", "interface-id1");
- Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "17", "aai-node-type", "pnf", "pnf-name", "pnf1name", "equip-vendor", "equip-vendor1", "equip-model",
- "equip-model1");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "22", "aai-node-type", "vserver", "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
+ // Set up the test graph
+ Vertex config1 = graph.addVertex(T.label, "configuration", T.id, "1", "aai-node-type",
+ "configuration", "configuration-id", "configuration1");
+ Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid1");
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "3", "aai-node-type", "pserver",
+ "hostname", "pservername1");
+ Vertex loglink1 =
+ graph.addVertex(T.label, "logical-link", T.id, "4", "aai-node-type", "logical-link",
+ "link-name", "loglink1", "in-maint", "false", "link-type", "link-type1");
+ Vertex lint1 = graph.addVertex(T.label, "l-interface", T.id, "5", "aai-node-type",
+ "l-interface", "interface-name", "lint1", "is-port-mirrored", "true", "in-maint",
+ "true", "is-ip-unnumbered", "false", "interface-id", "interface-id1");
+ Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "17", "aai-node-type", "pnf",
+ "pnf-name", "pnf1name", "equip-vendor", "equip-vendor1", "equip-model", "equip-model1");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "22", "aai-node-type",
+ "vserver", "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
- // Following are extra nodes that should not be picked up in
- // expectedResults
- Vertex config2 = graph.addVertex(T.label, "configuration", T.id, "11", "aai-node-type", "configuration", "configuration-id", "configuration2");
- Vertex gvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "12", "aai-node-type", "generic-vnf", "vnf-id", "vnfid2");
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "13", "aai-node-type", "pserver", "hostname", "pservername2");
- Vertex loglink2 = graph.addVertex(T.label, "logical-link", T.id, "14", "aai-node-type", "logical-link", "link-name", "loglink2", "in-maint", "false",
- "link-type", "link-type2");
- Vertex lint2 = graph.addVertex(T.label, "l-interface", T.id, "16", "aai-node-type", "l-interface", "interface-name", "lint1", "is-port-mirrored",
- "true", "in-maint", "true", "is-ip-unnumbered", "false", "interface-id", "interface-id2");
- Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "18", "aai-node-type", "pnf", "pnf-name", "pnf2name", "equip-vendor", "equip-vendor2", "equip-model",
- "equip-model2");
+ // Following are extra nodes that should not be picked up in
+ // expectedResults
+ Vertex config2 = graph.addVertex(T.label, "configuration", T.id, "11", "aai-node-type",
+ "configuration", "configuration-id", "configuration2");
+ Vertex gvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "12", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid2");
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "13", "aai-node-type",
+ "pserver", "hostname", "pservername2");
+ Vertex loglink2 =
+ graph.addVertex(T.label, "logical-link", T.id, "14", "aai-node-type", "logical-link",
+ "link-name", "loglink2", "in-maint", "false", "link-type", "link-type2");
+ Vertex lint2 = graph.addVertex(T.label, "l-interface", T.id, "16", "aai-node-type",
+ "l-interface", "interface-name", "lint1", "is-port-mirrored", "true", "in-maint",
+ "true", "is-ip-unnumbered", "false", "interface-id", "interface-id2");
+ Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "18", "aai-node-type", "pnf",
+ "pnf-name", "pnf2name", "equip-vendor", "equip-vendor2", "equip-model", "equip-model2");
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, config1, loglink1);
- rules.addEdge(g, lint1, loglink1);
- rules.addEdge(g, lint2, loglink1);
- rules.addTreeEdge(g, vserver1,lint1);
- rules.addEdge(g, vserver1, pserver1);
- rules.addEdge(g, loglink1, gvnf1);
- rules.addEdge(g, gvnf1, pnf1);
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, config1, loglink1);
+ rules.addEdge(g, lint1, loglink1);
+ rules.addEdge(g, lint2, loglink1);
+ rules.addTreeEdge(g, vserver1, lint1);
+ rules.addEdge(g, vserver1, pserver1);
+ rules.addEdge(g, loglink1, gvnf1);
+ rules.addEdge(g, gvnf1, pnf1);
- // These should not be picked up in expectedResults
- rules.addEdge(g, config2, loglink2);
- rules.addEdge(g, loglink2, pserver2);
- rules.addEdge(g, loglink2, gvnf2);
- rules.addEdge(g, gvnf2, pnf2);
+ // These should not be picked up in expectedResults
+ rules.addEdge(g, config2, loglink2);
+ rules.addEdge(g, loglink2, pserver2);
+ rules.addEdge(g, loglink2, gvnf2);
+ rules.addEdge(g, gvnf2, pnf2);
- expectedResult.add(config1);
- expectedResult.add(lint1);
- expectedResult.add(lint2);
- expectedResult.add(pserver1);
- expectedResult.add(gvnf1);
- expectedResult.add(pnf1);
+ expectedResult.add(config1);
+ expectedResult.add(lint1);
+ expectedResult.add(lint2);
+ expectedResult.add(pserver1);
+ expectedResult.add(gvnf1);
+ expectedResult.add(pnf1);
- }
+ }
- @Override
- protected String getQueryName() {
- return "pserver-fromConfiguration";
- }
+ @Override
+ protected String getQueryName() {
+ return "pserver-fromConfiguration";
+ }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("configuration-id", "configuration1");
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("configuration-id", "configuration1");
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/PserversFromVnfQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/PserversFromVnfQueryTest.java
index b7e913c..85f47b2 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/PserversFromVnfQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/PserversFromVnfQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,64 +26,74 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class PserversFromVnfQueryTest extends QueryTest {
- public PserversFromVnfQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
-
- //Set up the test graph
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex", "physical-location-id", "clli");
-
- Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf", "vnf-id", "vnfid1");
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "2", "aai-node-type", "pserver", "hostname", "pservername1");
-
- Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type", "generic-vnf", "vnf-id", "vnfid2");
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver", "hostname", "pservername2");
- Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver", "hostname", "pservername3");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "6", "aai-node-type", "vserver", "vserver-name", "vservername");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "7", "aai-node-type", "tenant", "tenant-id", "tenantuuid", "tenant-name", "tenantname");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "8", "aai-node-type", "cloud-region", "cloud-region-id", "clouduuid", "cloud-region-owner", "cloudOwnername");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, pserver1, complex);
- rules.addEdge(g, pserver2, complex);
-
- rules.addEdge(g, pserver1, vnf1);
- rules.addEdge(g, pserver2, vnf2);
-
- rules.addEdge(g, pserver3, complex);
- rules.addTreeEdge(g, tenant, cloudregion);
- rules.addTreeEdge(g, vserver, tenant);
- rules.addEdge(g, vserver, pserver3);
- rules.addEdge(g, vserver, vnf2);
-
- expectedResult.add(pserver2);
- expectedResult.add(pserver3);
-
- }
- @Override
- protected String getQueryName() {
- return "pservers-fromVnf";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("vnf-id", "vnfid2");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ public PserversFromVnfQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+
+ // Set up the test graph
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex",
+ "physical-location-id", "clli");
+
+ Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid1");
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "2", "aai-node-type", "pserver",
+ "hostname", "pservername1");
+
+ Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid2");
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver",
+ "hostname", "pservername2");
+ Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver",
+ "hostname", "pservername3");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "6", "aai-node-type", "vserver",
+ "vserver-name", "vservername");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "7", "aai-node-type", "tenant",
+ "tenant-id", "tenantuuid", "tenant-name", "tenantname");
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "8", "aai-node-type",
+ "cloud-region", "cloud-region-id", "clouduuid", "cloud-region-owner", "cloudOwnername");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, pserver1, complex);
+ rules.addEdge(g, pserver2, complex);
+
+ rules.addEdge(g, pserver1, vnf1);
+ rules.addEdge(g, pserver2, vnf2);
+
+ rules.addEdge(g, pserver3, complex);
+ rules.addTreeEdge(g, tenant, cloudregion);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addEdge(g, vserver, pserver3);
+ rules.addEdge(g, vserver, vnf2);
+
+ expectedResult.add(pserver2);
+ expectedResult.add(pserver3);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "pservers-fromVnf";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("vnf-id", "vnfid2");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/PserversWithNoComplexTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/PserversWithNoComplexTest.java
index cfd6e05..8340417 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/PserversWithNoComplexTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/PserversWithNoComplexTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -31,50 +31,55 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class PserversWithNoComplexTest extends QueryTest {
- public PserversWithNoComplexTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
+ public PserversWithNoComplexTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver", "hostname", "pservername1");
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "2", "aai-node-type", "pserver", "hostname", "pservername2");
- Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "3", "aai-node-type", "pserver", "hostname", "pservername3");
- Vertex pserver4 = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver", "hostname", "pservername4");
- Vertex pserver5 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver", "hostname", "pservername5");
- Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "6", "aai-node-type", "complex",
- "physical-location-id", "physical-location-id-1", "country", "US");
- Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "7", "aai-node-type", "complex",
- "physical-location-id", "physical-location-id-2", "country", "USA");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, pserver4,complex1);
- rules.addEdge(g, pserver5,complex2);
-
- expectedResult.add(pserver1);
- expectedResult.add(pserver2);
- expectedResult.add(pserver3);
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected String getQueryName() {
- return "pservers-withNoComplex";
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver",
+ "hostname", "pservername1");
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "2", "aai-node-type", "pserver",
+ "hostname", "pservername2");
+ Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "3", "aai-node-type", "pserver",
+ "hostname", "pservername3");
+ Vertex pserver4 = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver",
+ "hostname", "pservername4");
+ Vertex pserver5 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver",
+ "hostname", "pservername5");
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "6", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-1", "country", "US");
+ Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "7", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-2", "country", "USA");
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- return;
-
- }
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, pserver4, complex1);
+ rules.addEdge(g, pserver5, complex2);
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ expectedResult.add(pserver1);
+ expectedResult.add(pserver2);
+ expectedResult.add(pserver3);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "pservers-withNoComplex";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ return;
+
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryCountTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryCountTest.java
index 9ab2284..3d35eb2 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryCountTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryCountTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,32 +19,33 @@
*/
package org.onap.aai.rest.search;
-import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
-import org.onap.aai.exceptions.AAIException;
+import static org.hamcrest.CoreMatchers.is;
+import static org.junit.Assert.assertThat;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
-import static org.hamcrest.CoreMatchers.is;
-import static org.junit.Assert.assertThat;
+import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
+import org.onap.aai.exceptions.AAIException;
public abstract class QueryCountTest extends QueryTest {
- //listOfMapEntryForCoutnQueries is for when the query returns a HashMap, not a Vertex
- protected List<Map.Entry<String, Long>> listOfMapEntryForCoutnQueries;
-
+ // listOfMapEntryForCoutnQueries is for when the query returns a HashMap, not a Vertex
+ protected List<Map.Entry<String, Long>> listOfMapEntryForCoutnQueries;
- public QueryCountTest() throws AAIException {
- super();
- }
+ public QueryCountTest() throws AAIException {
+ super();
+ }
- @Override
- public void run() {
- GraphTraversal<HashMap<String,Long>, HashMap<String,Long>> result = (GraphTraversal<HashMap<String,Long>, HashMap<String,Long>>)shell.executeTraversal(query, params);
+ @Override
+ public void run() {
+ GraphTraversal<HashMap<String, Long>, HashMap<String, Long>> result =
+ (GraphTraversal<HashMap<String, Long>, HashMap<String, Long>>) shell
+ .executeTraversal(query, params);
- assertThat("all hash maps found", listOfMapEntryForCoutnQueries, is(result.toList()));
+ assertThat("all hash maps found", listOfMapEntryForCoutnQueries, is(result.toList()));
- }
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryPnfFromModelByRegionTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryPnfFromModelByRegionTest.java
index 52cc19a..9570de2 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryPnfFromModelByRegionTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryPnfFromModelByRegionTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,8 @@
*/
package org.onap.aai.rest.search;
+import java.util.Map;
+
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.T;
@@ -27,83 +29,86 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-
public class QueryPnfFromModelByRegionTest extends QueryTest {
- public QueryPnfFromModelByRegionTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
-
- //serviceInstance 1,2,3 are good and 4 is bad based upon the filters
- Vertex serviceInst1 = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id",
- "service-instance1", "model-invariant-id", "miid1", "model-version-id", "mvid1");
- Vertex serviceInst2 = graph.addVertex(T.label, "service-instance", T.id, "2", "aai-node-type", "service-instance", "service-instance-id",
- "service-instance2", "model-invariant-id", "miid1", "model-version-id", "mvid1");
- Vertex serviceInst3 = graph.addVertex(T.label, "service-instance", T.id, "3", "aai-node-type", "service-instance", "service-instance-id",
- "service-instance3", "model-invariant-id", "miid1", "model-version-id", "mvid1");
- Vertex serviceInst4 = graph.addVertex(T.label, "service-instance", T.id, "4", "aai-node-type", "service-instance", "service-instance-id",
- "service-instance4", "model-invariant-id", "miid2", "model-version-id", "mvid2");
-
- //pnf 1,2 & 3 are good based upon the filters
- Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "5", "aai-node-type", "pnf", "pnf-name", "pnf1name", "equip-vendor", "equip-vendor1", "equip-model",
- "equip-model1");
- Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "6", "aai-node-type", "pnf", "pnf-name", "pnf2name", "equip-vendor", "equip-vendor1", "equip-model",
- "equip-model1");
- Vertex pnf3 = graph.addVertex(T.label, "pnf", T.id, "7", "aai-node-type", "pnf", "pnf-name", "pnf3name", "equip-vendor", "equip-vendor1", "equip-model",
- "equip-model1");
- Vertex pnf4 = graph.addVertex(T.label, "pnf", T.id, "12", "aai-node-type", "pnf", "pnf-name", "pnf4name", "equip-vendor", "equip-vendor4",
- "equip-model", "equip-model4");
-
- Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "8", "aai-node-type", "complex", "physical-location-id", "physical-location-id-1");
- Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "9", "aai-node-type", "complex", "physical-location-id", "physical-location-id-2");
-
- //cr 1 is good based upon the filter
- Vertex cloudRegion1 = graph.addVertex(T.label, "cloud-region", T.id, "10", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region1");
- Vertex cloudRegion2 = graph.addVertex(T.label, "cloud-region", T.id, "11", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region2");
-
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, serviceInst1, pnf1);
- rules.addEdge(g, serviceInst2, pnf2);
- rules.addEdge(g, serviceInst3, pnf3);
- rules.addEdge(g, serviceInst4, pnf4);
-
- rules.addEdge(g, pnf1, complex1);
- rules.addEdge(g, pnf2, complex1);
- rules.addEdge(g, pnf3, complex2);
- rules.addEdge(g, pnf4, complex2);
-
- rules.addEdge(g, cloudRegion1, complex1);
- rules.addEdge(g, cloudRegion2, complex2);
-
-
- expectedResult.add(pnf1);
- expectedResult.add(pnf2);
- }
-
- @Override
- protected String getQueryName() {
- return "pnf-fromModel-byRegion";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("model-invariant-id", "miid1").has("model-version-id", "mvid1");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("cloudRegionId", "cloud-region1");
- params.put("equipVendor", "equip-vendor1");
- params.put("equipModel", "equip-model1");
- }
+ public QueryPnfFromModelByRegionTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+
+ // serviceInstance 1,2,3 are good and 4 is bad based upon the filters
+ Vertex serviceInst1 = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance1",
+ "model-invariant-id", "miid1", "model-version-id", "mvid1");
+ Vertex serviceInst2 = graph.addVertex(T.label, "service-instance", T.id, "2",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance2",
+ "model-invariant-id", "miid1", "model-version-id", "mvid1");
+ Vertex serviceInst3 = graph.addVertex(T.label, "service-instance", T.id, "3",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance3",
+ "model-invariant-id", "miid1", "model-version-id", "mvid1");
+ Vertex serviceInst4 = graph.addVertex(T.label, "service-instance", T.id, "4",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance4",
+ "model-invariant-id", "miid2", "model-version-id", "mvid2");
+
+ // pnf 1,2 & 3 are good based upon the filters
+ Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "5", "aai-node-type", "pnf", "pnf-name",
+ "pnf1name", "equip-vendor", "equip-vendor1", "equip-model", "equip-model1");
+ Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "6", "aai-node-type", "pnf", "pnf-name",
+ "pnf2name", "equip-vendor", "equip-vendor1", "equip-model", "equip-model1");
+ Vertex pnf3 = graph.addVertex(T.label, "pnf", T.id, "7", "aai-node-type", "pnf", "pnf-name",
+ "pnf3name", "equip-vendor", "equip-vendor1", "equip-model", "equip-model1");
+ Vertex pnf4 = graph.addVertex(T.label, "pnf", T.id, "12", "aai-node-type", "pnf",
+ "pnf-name", "pnf4name", "equip-vendor", "equip-vendor4", "equip-model", "equip-model4");
+
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "8", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-1");
+ Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "9", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-2");
+
+ // cr 1 is good based upon the filter
+ Vertex cloudRegion1 = graph.addVertex(T.label, "cloud-region", T.id, "10", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region1");
+ Vertex cloudRegion2 = graph.addVertex(T.label, "cloud-region", T.id, "11", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region2");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, serviceInst1, pnf1);
+ rules.addEdge(g, serviceInst2, pnf2);
+ rules.addEdge(g, serviceInst3, pnf3);
+ rules.addEdge(g, serviceInst4, pnf4);
+
+ rules.addEdge(g, pnf1, complex1);
+ rules.addEdge(g, pnf2, complex1);
+ rules.addEdge(g, pnf3, complex2);
+ rules.addEdge(g, pnf4, complex2);
+
+ rules.addEdge(g, cloudRegion1, complex1);
+ rules.addEdge(g, cloudRegion2, complex2);
+
+ expectedResult.add(pnf1);
+ expectedResult.add(pnf2);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "pnf-fromModel-byRegion";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("model-invariant-id", "miid1").has("model-version-id", "mvid1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("cloudRegionId", "cloud-region1");
+ params.put("equipVendor", "equip-vendor1");
+ params.put("equipModel", "equip-model1");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryPnfFromModelTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryPnfFromModelTest.java
index 95290fb..e7df71e 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryPnfFromModelTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryPnfFromModelTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,8 @@
*/
package org.onap.aai.rest.search;
+import java.util.Map;
+
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.T;
@@ -27,55 +29,52 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-
public class QueryPnfFromModelTest extends QueryTest {
- public QueryPnfFromModelTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public QueryPnfFromModelTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex serviceInst1 = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id",
- "service-instance1", "model-invariant-id", "miid1", "model-version-id", "mvid1");
- Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "2", "aai-node-type", "pnf", "pnf-name", "pnf1name", "equip-vendor", "equip-vendor1", "equip-model",
- "equip-model1");
-
- Vertex serviceInst2 = graph.addVertex(T.label, "service-instance", T.id, "3", "aai-node-type", "service-instance", "service-instance-id",
- "service-instance2", "model-invariant-id", "miid2", "model-version-id", "mvid2");
- Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "4", "aai-node-type", "pnf", "pnf-name", "pnf2name", "equip-vendor", "equip-vendor2", "equip-model",
- "equip-model2");
+ Vertex serviceInst1 = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance1",
+ "model-invariant-id", "miid1", "model-version-id", "mvid1");
+ Vertex pnf1 = graph.addVertex(T.label, "pnf", T.id, "2", "aai-node-type", "pnf", "pnf-name",
+ "pnf1name", "equip-vendor", "equip-vendor1", "equip-model", "equip-model1");
+ Vertex serviceInst2 = graph.addVertex(T.label, "service-instance", T.id, "3",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance2",
+ "model-invariant-id", "miid2", "model-version-id", "mvid2");
+ Vertex pnf2 = graph.addVertex(T.label, "pnf", T.id, "4", "aai-node-type", "pnf", "pnf-name",
+ "pnf2name", "equip-vendor", "equip-vendor2", "equip-model", "equip-model2");
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, serviceInst1, pnf1);
-
- rules.addEdge(g, serviceInst2, pnf2);//false
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, serviceInst1, pnf1);
+ rules.addEdge(g, serviceInst2, pnf2);// false
- expectedResult.add(pnf1);
- }
+ expectedResult.add(pnf1);
+ }
- @Override
- protected String getQueryName() {
- return "pnf-from-model";
- }
+ @Override
+ protected String getQueryName() {
+ return "pnf-from-model";
+ }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("model-invariant-id", "miid1").has("model-version-id", "mvid1");
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("model-invariant-id", "miid1").has("model-version-id", "mvid1");
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("equipVendor", "equip-vendor1");
- params.put("equipModel", "equip-model1");
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("equipVendor", "equip-vendor1");
+ params.put("equipModel", "equip-model1");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryTest.java
index f96d4c5..317eb4c 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,9 +19,15 @@
*/
package org.onap.aai.rest.search;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
+import static org.junit.Assert.assertEquals;
+import static org.mockito.Matchers.any;
+import static org.mockito.Mockito.when;
+
import com.att.eelf.configuration.EELFManager;
+
+import java.util.*;
+import java.util.stream.Collectors;
+
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.Graph;
@@ -47,167 +53,152 @@ import org.onap.aai.introspection.Loader;
import org.onap.aai.introspection.LoaderFactory;
import org.onap.aai.introspection.ModelType;
import org.onap.aai.nodes.NodeIngestor;
+import org.onap.aai.query.builder.GremlinTraversal;
+import org.onap.aai.restcore.search.GremlinGroovyShell;
+import org.onap.aai.restcore.search.GroovyQueryBuilder;
+import org.onap.aai.serialization.db.EdgeSerializer;
+import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
+import org.onap.aai.serialization.engines.QueryStyle;
+import org.onap.aai.serialization.engines.TransactionalGraphEngine;
import org.onap.aai.setup.AAIConfigTranslator;
+import org.onap.aai.setup.SchemaConfigVersions;
import org.onap.aai.setup.SchemaLocationsBean;
import org.onap.aai.setup.SchemaVersion;
-import org.onap.aai.setup.SchemaConfigVersions;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
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.onap.aai.query.builder.GremlinTraversal;
-import org.onap.aai.restcore.search.GremlinGroovyShell;
-import org.onap.aai.restcore.search.GroovyQueryBuilder;
-import org.onap.aai.serialization.db.EdgeSerializer;
-import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import org.onap.aai.serialization.engines.QueryStyle;
-import org.onap.aai.serialization.engines.TransactionalGraphEngine;
-
-import java.util.*;
-import java.util.stream.Collectors;
-
-import static org.junit.Assert.assertEquals;
-import static org.mockito.Matchers.any;
-import static org.mockito.Mockito.when;
@RunWith(Parameterized.class)
-@ContextConfiguration(classes = {
- ConfigConfiguration.class,
- AAIConfigTranslator.class,
- EdgeIngestor.class,
- EdgeSerializer.class,
- NodeIngestor.class,
- SpringContextAware.class,
- SearchConfiguration.class,
- IntrospectionConfig.class
-})
-@TestPropertySource(properties = {
- "schema.uri.base.path = /aai",
- "schema.ingest.file = src/test/resources/application-test.properties"
-})
+@ContextConfiguration(
+ classes = {ConfigConfiguration.class, AAIConfigTranslator.class, EdgeIngestor.class,
+ EdgeSerializer.class, NodeIngestor.class, SpringContextAware.class,
+ SearchConfiguration.class, IntrospectionConfig.class})
+@TestPropertySource(
+ properties = {"schema.uri.base.path = /aai",
+ "schema.ingest.file = src/test/resources/application-test.properties"})
public abstract class QueryTest {
- @ClassRule
+ @ClassRule
public static final SpringClassRule springClassRule = new SpringClassRule();
@Rule
public final SpringMethodRule springMethodRule = new SpringMethodRule();
- protected Logger logger;
- protected Graph graph;
- protected GremlinGroovyShell shell;
- @Mock protected TransactionalGraphEngine dbEngine;
- protected final List<Vertex> expectedResult = new ArrayList<>();
-
- @Autowired
- protected EdgeIngestor edgeRules;
-
- @Autowired
- protected EdgeSerializer rules;
-
- @Autowired
- protected LoaderFactory loaderFactory;
-
- @Autowired
- protected SchemaConfigVersions schemaVersions;
-
- @Autowired
- protected GremlinServerSingleton gremlinServerSingleton;
-
- protected Loader loader;
- protected GraphTraversalSource gts;
-
- @Parameterized.Parameter(value = 0)
- public SchemaVersion version;
-
- @Parameterized.Parameters(name = "Version.{0}")
- public static Collection<Object[]> data() {
- return Arrays.asList(new Object[][]{
- {new SchemaVersion("v11")},
- {new SchemaVersion("v12")},
- {new SchemaVersion("v13")},
- {new SchemaVersion("v14")}
- });
- }
-
- protected String query;
-
- LinkedHashMap <String, Object> params;
-
- @BeforeClass
- public static void setupBundleconfig() {
- System.setProperty("AJSC_HOME", "./");
- System.setProperty("BUNDLECONFIG_DIR", "src/main/resources/");
- }
-
- @Before
- public void setUp() throws AAIException, NoEdgeRuleFoundException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- System.setProperty("AJSC_HOME", ".");
- System.setProperty("BUNDLECONFIG_DIR", "src/main/resources");
- logger = LoggerFactory.getLogger(getClass());
- MockitoAnnotations.initMocks(this);
- graph = TinkerGraph.open();
- gts = graph.traversal();
- createGraph();
- shell = new GremlinGroovyShell();
- loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, version);
- setUpQuery();
- }
-
-
- protected void setUpQuery() {
- query = gremlinServerSingleton.getStoredQueryFromConfig(getQueryName());
- params = new LinkedHashMap <>();
- addParam(params);
- when(dbEngine.getQueryBuilder(any(QueryStyle.class))).thenReturn(new GremlinTraversal<>(loader, graph.traversal()));
- logger.info("Stored query in abstraction form {}", query);
- query = new GroovyQueryBuilder().executeTraversal(dbEngine, query, params);
- logger.info("After converting to gremlin query {}", query);
- query = "g" + query;
- GraphTraversal<Vertex, Vertex> g = graph.traversal().V();
- addStartNode(g);
- params.put("g", g);
- }
-
- public void run() {
-
- GraphTraversal<Vertex, Vertex> result = (GraphTraversal<Vertex, Vertex>)shell.executeTraversal(query, params);
-
- List<Vertex> vertices = result.toList();
-
- logger.info("Expected result set of vertexes [{}]", convert(expectedResult));
- logger.info("Actual Result set of vertexes [{}]", convert(vertices));
-
- List<Vertex> nonDuplicateExpectedResult = new ArrayList<>(new HashSet<>(expectedResult));
- vertices = new ArrayList<>(new HashSet<>(vertices));
-
- nonDuplicateExpectedResult.sort(Comparator.comparing(vertex -> vertex.id().toString()));
- vertices.sort(Comparator.comparing(vertex -> vertex.id().toString()));
-
-
- // Use this instead of the assertTrue as this provides more useful
- // debugging information such as this when expected and actual differ:
- // java.lang.AssertionError: Expected all the vertices to be found
- // Expected :[v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
- // Actual :[v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
- assertEquals("Expected all the vertices to be found", nonDuplicateExpectedResult, vertices);
-
- }
-
- protected String convert(List<Vertex> vertices){
- return vertices
- .stream()
- .map(vertex -> vertex.property("aai-node-type").value().toString())
- .collect(Collectors.joining(","));
- }
-
- protected abstract void createGraph() throws AAIException, NoEdgeRuleFoundException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException;
-
- protected abstract String getQueryName();
-
- protected abstract void addStartNode(GraphTraversal<Vertex, Vertex> g);
+ protected Logger logger;
+ protected Graph graph;
+ protected GremlinGroovyShell shell;
+ @Mock
+ protected TransactionalGraphEngine dbEngine;
+ protected final List<Vertex> expectedResult = new ArrayList<>();
+
+ @Autowired
+ protected EdgeIngestor edgeRules;
+
+ @Autowired
+ protected EdgeSerializer rules;
+
+ @Autowired
+ protected LoaderFactory loaderFactory;
+
+ @Autowired
+ protected SchemaConfigVersions schemaVersions;
+
+ @Autowired
+ protected GremlinServerSingleton gremlinServerSingleton;
+
+ protected Loader loader;
+ protected GraphTraversalSource gts;
+
+ @Parameterized.Parameter(value = 0)
+ public SchemaVersion version;
+
+ @Parameterized.Parameters(name = "Version.{0}")
+ public static Collection<Object[]> data() {
+ return Arrays.asList(new Object[][] {{new SchemaVersion("v11")}, {new SchemaVersion("v12")},
+ {new SchemaVersion("v13")}, {new SchemaVersion("v14")}});
+ }
+
+ protected String query;
+
+ LinkedHashMap<String, Object> params;
+
+ @BeforeClass
+ public static void setupBundleconfig() {
+ System.setProperty("AJSC_HOME", "./");
+ System.setProperty("BUNDLECONFIG_DIR", "src/main/resources/");
+ }
+
+ @Before
+ public void setUp() throws AAIException, NoEdgeRuleFoundException, EdgeRuleNotFoundException,
+ AmbiguousRuleChoiceException {
+ System.setProperty("AJSC_HOME", ".");
+ System.setProperty("BUNDLECONFIG_DIR", "src/main/resources");
+ logger = LoggerFactory.getLogger(getClass());
+ MockitoAnnotations.initMocks(this);
+ graph = TinkerGraph.open();
+ gts = graph.traversal();
+ createGraph();
+ shell = new GremlinGroovyShell();
+ loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, version);
+ setUpQuery();
+ }
+
+ protected void setUpQuery() {
+ query = gremlinServerSingleton.getStoredQueryFromConfig(getQueryName());
+ params = new LinkedHashMap<>();
+ addParam(params);
+ when(dbEngine.getQueryBuilder(any(QueryStyle.class)))
+ .thenReturn(new GremlinTraversal<>(loader, graph.traversal()));
+ logger.info("Stored query in abstraction form {}", query);
+ query = new GroovyQueryBuilder().executeTraversal(dbEngine, query, params);
+ logger.info("After converting to gremlin query {}", query);
+ query = "g" + query;
+ GraphTraversal<Vertex, Vertex> g = graph.traversal().V();
+ addStartNode(g);
+ params.put("g", g);
+ }
+
+ public void run() {
+
+ GraphTraversal<Vertex, Vertex> result =
+ (GraphTraversal<Vertex, Vertex>) shell.executeTraversal(query, params);
+
+ List<Vertex> vertices = result.toList();
+
+ logger.info("Expected result set of vertexes [{}]", convert(expectedResult));
+ logger.info("Actual Result set of vertexes [{}]", convert(vertices));
+
+ List<Vertex> nonDuplicateExpectedResult = new ArrayList<>(new HashSet<>(expectedResult));
+ vertices = new ArrayList<>(new HashSet<>(vertices));
+
+ nonDuplicateExpectedResult.sort(Comparator.comparing(vertex -> vertex.id().toString()));
+ vertices.sort(Comparator.comparing(vertex -> vertex.id().toString()));
+
+ // Use this instead of the assertTrue as this provides more useful
+ // debugging information such as this when expected and actual differ:
+ // java.lang.AssertionError: Expected all the vertices to be found
+ // Expected :[v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
+ // Actual :[v[1], v[2], v[3], v[4], v[5], v[6], v[7], v[8], v[9], v[10], v[11], v[12]]
+ assertEquals("Expected all the vertices to be found", nonDuplicateExpectedResult, vertices);
+
+ }
+
+ protected String convert(List<Vertex> vertices) {
+ return vertices.stream().map(vertex -> vertex.property("aai-node-type").value().toString())
+ .collect(Collectors.joining(","));
+ }
+
+ protected abstract void createGraph() throws AAIException, NoEdgeRuleFoundException,
+ EdgeRuleNotFoundException, AmbiguousRuleChoiceException;
- protected abstract void addParam(Map<String, Object> params);
+ protected abstract String getQueryName();
+
+ protected abstract void addStartNode(GraphTraversal<Vertex, Vertex> g);
+
+ protected abstract void addParam(Map<String, Object> params);
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryVnfFromModelByRegionTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryVnfFromModelByRegionTest.java
index b79ea2f..4758ba0 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryVnfFromModelByRegionTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/QueryVnfFromModelByRegionTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,8 @@
*/
package org.onap.aai.rest.search;
+import java.util.Map;
+
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.T;
@@ -27,72 +29,80 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-
public class QueryVnfFromModelByRegionTest extends QueryTest {
- public QueryVnfFromModelByRegionTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public QueryVnfFromModelByRegionTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex serviceInst1 = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance1",
+ "model-invariant-id", "miid1", "model-version-id", "mvid1");
+ Vertex serviceInst2 = graph.addVertex(T.label, "service-instance", T.id, "12",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance2",
+ "model-invariant-id", "miid2", "model-version-id", "mvid2");
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex serviceInst1 = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance",
- "service-instance-id", "service-instance1", "model-invariant-id", "miid1", "model-version-id", "mvid1");
- Vertex serviceInst2 = graph.addVertex(T.label, "service-instance", T.id, "12", "aai-node-type", "service-instance",
- "service-instance-id", "service-instance2", "model-invariant-id", "miid2", "model-version-id", "mvid2");
+ Vertex genericVnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type",
+ "generic-vnf", "generic-vnf-id", "generic-vnf1");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver",
+ "vserver-id", "vserver1");
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "4", "aai-node-type", "tenant",
+ "tenant-id", "tenant1");
+ Vertex cloudRegion1 = graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region1");
- Vertex genericVnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type", "generic-vnf", "generic-vnf-id", "generic-vnf1");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserver1");
- Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "4", "aai-node-type", "tenant", "tenant-id", "tenant1");
- Vertex cloudRegion1 = graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region1");
+ // Right invariant and version IDs, wrong cloud region
+ Vertex genericVnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "6", "aai-node-type",
+ "generic-vnf", "generic-vnf-id", "generic-vnf2");
+ Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver",
+ "vserver-id", "vserver2");
+ Vertex tenant2 = graph.addVertex(T.label, "tenant", T.id, "8", "aai-node-type", "tenant",
+ "tenant-id", "tenant2");
+ Vertex cloudRegion2 = graph.addVertex(T.label, "cloud-region", T.id, "9", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region2");
- // Right invariant and version IDs, wrong cloud region
- Vertex genericVnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "6", "aai-node-type", "generic-vnf",
- "generic-vnf-id", "generic-vnf2");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver", "vserver-id", "vserver2");
- Vertex tenant2 = graph.addVertex(T.label, "tenant", T.id, "8", "aai-node-type", "tenant", "tenant-id", "tenant2");
- Vertex cloudRegion2 = graph.addVertex(T.label, "cloud-region", T.id, "9", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region2");
+ // On both the right and the wrong service-instance, with the right cloud-region
+ Vertex genericVnf3 = graph.addVertex(T.label, "generic-vnf", T.id, "10", "aai-node-type",
+ "generic-vnf", "generic-vnf-id", "generic-vnf3");
+ Vertex vserver3 = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type",
+ "vserver", "vserver-id", "vserver3");
- // On both the right and the wrong service-instance, with the right cloud-region
- Vertex genericVnf3 = graph.addVertex(T.label, "generic-vnf", T.id, "10", "aai-node-type", "generic-vnf",
- "generic-vnf-id", "generic-vnf3");
- Vertex vserver3 = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type", "vserver", "vserver-id", "vserver3");
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, serviceInst1, genericVnf1);
+ rules.addEdge(g, genericVnf1, vserver1);
+ rules.addTreeEdge(g, tenant1, vserver1);
+ rules.addTreeEdge(g, cloudRegion1, tenant1);
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, serviceInst1, genericVnf1);
- rules.addEdge(g, genericVnf1, vserver1);
- rules.addTreeEdge(g, tenant1, vserver1);
- rules.addTreeEdge(g, cloudRegion1, tenant1);
+ rules.addEdge(g, serviceInst1, genericVnf2);
+ rules.addEdge(g, genericVnf2, vserver2);
+ rules.addTreeEdge(g, tenant2, vserver2);
+ rules.addTreeEdge(g, cloudRegion2, tenant2);
- rules.addEdge(g, serviceInst1, genericVnf2);
- rules.addEdge(g, genericVnf2, vserver2);
- rules.addTreeEdge(g, tenant2, vserver2);
- rules.addTreeEdge(g, cloudRegion2, tenant2);
-
- rules.addEdge(g, serviceInst2, genericVnf3);
- rules.addEdge(g, genericVnf3, vserver3);
- rules.addTreeEdge(g, tenant1, vserver3);
+ rules.addEdge(g, serviceInst2, genericVnf3);
+ rules.addEdge(g, genericVnf3, vserver3);
+ rules.addTreeEdge(g, tenant1, vserver3);
- expectedResult.add(genericVnf1);
- }
+ expectedResult.add(genericVnf1);
+ }
- @Override
- protected String getQueryName() {
- return "queryvnfFromModelbyRegion";
- }
+ @Override
+ protected String getQueryName() {
+ return "queryvnfFromModelbyRegion";
+ }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("model-invariant-id", "miid1").has("model-version-id", "mvid1");
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("model-invariant-id", "miid1").has("model-version-id", "mvid1");
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("cloudRegionId", "cloud-region1");
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("cloudRegionId", "cloud-region1");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/RelatedToBothCousinAndTreeCustomQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/RelatedToBothCousinAndTreeCustomQueryTest.java
index f2c6369..c1137a7 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/RelatedToBothCousinAndTreeCustomQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/RelatedToBothCousinAndTreeCustomQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -18,6 +18,9 @@
* ============LICENSE_END=========================================================
*/
package org.onap.aai.rest.search;
+
+import java.util.Map;
+
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.T;
@@ -27,11 +30,10 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.query.builder.MissingOptionalParameter;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-
-public class RelatedToBothCousinAndTreeCustomQueryTest extends QueryTest{
+public class RelatedToBothCousinAndTreeCustomQueryTest extends QueryTest {
- public RelatedToBothCousinAndTreeCustomQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ public RelatedToBothCousinAndTreeCustomQueryTest()
+ throws AAIException, NoEdgeRuleFoundException {
super();
}
@@ -39,17 +41,25 @@ public class RelatedToBothCousinAndTreeCustomQueryTest extends QueryTest{
public void run() {
super.run();
}
+
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex lagInterface1 = graph.addVertex(T.label, "lag-interface", T.id, "1", "aai-node-type", "lag-interface", "interface-name", "lag-int1");
+ Vertex lagInterface1 = graph.addVertex(T.label, "lag-interface", T.id, "1", "aai-node-type",
+ "lag-interface", "interface-name", "lag-int1");
- Vertex lInterface1 = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type", "l-interface", "interface-name", "l-interfaceid01");
- Vertex lInterface2 = graph.addVertex(T.label, "l-interface", T.id, "3", "aai-node-type", "l-interface", "interface-name", "l-interfaceid02");
- Vertex lInterface3 = graph.addVertex(T.label, "l-interface", T.id, "4", "aai-node-type", "l-interface", "interface-name", "l-interfaceid03");
- Vertex lInterface4 = graph.addVertex(T.label, "l-interface", T.id, "5", "aai-node-type", "l-interface", "interface-name", "l-interfaceid04");
- Vertex lInterface5 = graph.addVertex(T.label, "l-interface", T.id, "6", "aai-node-type", "l-interface", "interface-name", "l-interfaceid05");
- Vertex lInterface6 = graph.addVertex(T.label, "l-interface", T.id, "7", "aai-node-type", "l-interface", "interface-name", "l-interfaceid06");
+ Vertex lInterface1 = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type",
+ "l-interface", "interface-name", "l-interfaceid01");
+ Vertex lInterface2 = graph.addVertex(T.label, "l-interface", T.id, "3", "aai-node-type",
+ "l-interface", "interface-name", "l-interfaceid02");
+ Vertex lInterface3 = graph.addVertex(T.label, "l-interface", T.id, "4", "aai-node-type",
+ "l-interface", "interface-name", "l-interfaceid03");
+ Vertex lInterface4 = graph.addVertex(T.label, "l-interface", T.id, "5", "aai-node-type",
+ "l-interface", "interface-name", "l-interfaceid04");
+ Vertex lInterface5 = graph.addVertex(T.label, "l-interface", T.id, "6", "aai-node-type",
+ "l-interface", "interface-name", "l-interfaceid05");
+ Vertex lInterface6 = graph.addVertex(T.label, "l-interface", T.id, "7", "aai-node-type",
+ "l-interface", "interface-name", "l-interfaceid06");
GraphTraversalSource g = graph.traversal();
rules.addEdge(g, lagInterface1, lInterface1);
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/RelatedToCustomQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/RelatedToCustomQueryTest.java
index 5147268..0d63115 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/RelatedToCustomQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/RelatedToCustomQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -18,6 +18,9 @@
* ============LICENSE_END=========================================================
*/
package org.onap.aai.rest.search;
+
+import java.util.Map;
+
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.T;
@@ -26,8 +29,7 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-public class RelatedToCustomQueryTest extends QueryTest{
+public class RelatedToCustomQueryTest extends QueryTest {
public RelatedToCustomQueryTest() throws AAIException, NoEdgeRuleFoundException {
super();
@@ -37,14 +39,20 @@ public class RelatedToCustomQueryTest extends QueryTest{
public void run() {
super.run();
}
+
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf", "vnf-id", "genvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
+ Vertex genericvnf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf",
+ "vnf-id", "genvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "2", "aai-node-type", "vserver", "vserver-id", "vserverid01");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserverid02");
- Vertex vserver3 = graph.addVertex(T.label, "vserver", T.id, "4", "aai-node-type", "vserver", "vserver-id", "vserverid03");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "2", "aai-node-type", "vserver",
+ "vserver-id", "vserverid01");
+ Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver",
+ "vserver-id", "vserverid02");
+ Vertex vserver3 = graph.addVertex(T.label, "vserver", T.id, "4", "aai-node-type", "vserver",
+ "vserver-id", "vserverid03");
GraphTraversalSource g = graph.traversal();
rules.addEdge(g, genericvnf1, vserver1);
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/RelatedToTreeCustomQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/RelatedToTreeCustomQueryTest.java
index 2f31206..f47c9c0 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/RelatedToTreeCustomQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/RelatedToTreeCustomQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -18,6 +18,9 @@
* ============LICENSE_END=========================================================
*/
package org.onap.aai.rest.search;
+
+import java.util.Map;
+
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.T;
@@ -26,8 +29,6 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-
public class RelatedToTreeCustomQueryTest extends QueryTest {
public RelatedToTreeCustomQueryTest() throws AAIException, NoEdgeRuleFoundException {
@@ -38,14 +39,20 @@ public class RelatedToTreeCustomQueryTest extends QueryTest {
public void run() {
super.run();
}
+
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf", "vnf-id", "genvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
+ Vertex genericvnf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf",
+ "vnf-id", "genvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
- Vertex entitlement1 = graph.addVertex(T.label, "entitlement", T.id, "2", "aai-node-type", "entitlement", "group-uuid", "entitlementid01", "resource-uuid", "rentitlementid01");
- Vertex entitlement2 = graph.addVertex(T.label, "entitlement", T.id, "3", "aai-node-type", "entitlement", "group-uuid", "entitlementid02", "resource-uuid", "rentitlementid02");
- Vertex entitlement3 = graph.addVertex(T.label, "entitlement", T.id, "4", "aai-node-type", "entitlement", "group-uuid", "entitlementid03", "resource-uuid", "rentitlementid03");
+ Vertex entitlement1 = graph.addVertex(T.label, "entitlement", T.id, "2", "aai-node-type",
+ "entitlement", "group-uuid", "entitlementid01", "resource-uuid", "rentitlementid01");
+ Vertex entitlement2 = graph.addVertex(T.label, "entitlement", T.id, "3", "aai-node-type",
+ "entitlement", "group-uuid", "entitlementid02", "resource-uuid", "rentitlementid02");
+ Vertex entitlement3 = graph.addVertex(T.label, "entitlement", T.id, "4", "aai-node-type",
+ "entitlement", "group-uuid", "entitlementid03", "resource-uuid", "rentitlementid03");
GraphTraversalSource g = graph.traversal();
rules.addTreeEdge(g, genericvnf1, entitlement1);
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/SearchProviderTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/SearchProviderTest.java
index 4332536..672c449 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/SearchProviderTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/SearchProviderTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,16 @@
*/
package org.onap.aai.rest.search;
+import static org.hamcrest.Matchers.containsString;
+import static org.junit.Assert.*;
+import static org.mockito.Matchers.anyObject;
+import static org.mockito.Mockito.mock;
+import static org.mockito.Mockito.when;
+
+import java.util.*;
+
+import javax.ws.rs.core.*;
+
import org.junit.Before;
import org.junit.Ignore;
import org.junit.Test;
@@ -31,16 +41,7 @@ import org.onap.aai.setup.SchemaVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
-import javax.ws.rs.core.*;
-import java.util.*;
-
-import static org.hamcrest.Matchers.containsString;
-import static org.junit.Assert.*;
-import static org.mockito.Matchers.anyObject;
-import static org.mockito.Mockito.mock;
-import static org.mockito.Mockito.when;
-
-public class SearchProviderTest extends AAISetup{
+public class SearchProviderTest extends AAISetup {
protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
@@ -71,21 +72,22 @@ public class SearchProviderTest extends AAISetup{
private List<MediaType> outputMediaTypes;
- private static final Logger logger = LoggerFactory.getLogger(SearchProviderTest.class.getName());
+ private static final Logger logger =
+ LoggerFactory.getLogger(SearchProviderTest.class.getName());
@Before
- public void setup(){
+ public void setup() {
logger.info("Starting the setup for the integration tests of Rest Endpoints");
version = schemaVersions.getDefaultVersion();
-
- searchProvider = new SearchProvider(loaderFactory, searchGraph, schemaVersions, basePath);
- httpHeaders = mock(HttpHeaders.class);
- uriInfo = mock(UriInfo.class);
+
+ searchProvider = new SearchProvider(loaderFactory, searchGraph, schemaVersions, basePath);
+ httpHeaders = mock(HttpHeaders.class);
+ uriInfo = mock(UriInfo.class);
when(uriInfo.getPath()).thenReturn("JUNITURI");
- headersMultiMap = new MultivaluedHashMap<>();
- queryParameters = Mockito.spy(new MultivaluedHashMap<>());
+ headersMultiMap = new MultivaluedHashMap<>();
+ queryParameters = Mockito.spy(new MultivaluedHashMap<>());
headersMultiMap.add("X-FromAppId", "JUNIT");
headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
@@ -101,16 +103,18 @@ public class SearchProviderTest extends AAISetup{
when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
- when(httpHeaders.getRequestHeader("X-FromAppId")).thenReturn(Collections.singletonList("JUNIT"));
- when(httpHeaders.getRequestHeader("X-TransactionId")).thenReturn(Collections.singletonList("JUNIT"));
+ when(httpHeaders.getRequestHeader("X-FromAppId"))
+ .thenReturn(Collections.singletonList("JUNIT"));
+ when(httpHeaders.getRequestHeader("X-TransactionId"))
+ .thenReturn(Collections.singletonList("JUNIT"));
when(httpHeaders.getRequestHeader("aai-request-context")).thenReturn(aaiRequestContextList);
-
when(uriInfo.getQueryParameters()).thenReturn(queryParameters);
when(uriInfo.getQueryParameters(false)).thenReturn(queryParameters);
- // TODO - Check if this is valid since RemoveDME2QueryParameters seems to be very unreasonable
+ // 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);
@@ -131,21 +135,14 @@ public class SearchProviderTest extends AAISetup{
when(httpHeaders.getRequestHeader("X-FromAppId")).thenThrow(IllegalArgumentException.class);
when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
- Response response = searchProvider.getNodesQueryResponse(
- httpHeaders,
- null,
- "cloud-region",
- keys,
- includeStrings,
- version.toString(),
- uriInfo
- );
+ Response response = searchProvider.getNodesQueryResponse(httpHeaders, null, "cloud-region",
+ keys, includeStrings, version.toString(), uriInfo);
assertNotNull(response);
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
}
- //TODO fix test
+ // TODO fix test
@Ignore("Test has a time dependency and fails based on system perf")
@Test
public void testNodesQueryTimeoutThrown() throws Exception {
@@ -162,15 +159,8 @@ public class SearchProviderTest extends AAISetup{
when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
- Response response = searchProvider.getNodesQueryResponse(
- httpHeaders,
- null,
- "cloud-region",
- keys,
- includeStrings,
- version.toString(),
- uriInfo
- );
+ Response response = searchProvider.getNodesQueryResponse(httpHeaders, null, "cloud-region",
+ keys, includeStrings, version.toString(), uriInfo);
assertNotNull(response);
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
@@ -192,22 +182,15 @@ public class SearchProviderTest extends AAISetup{
when(httpHeaders.getRequestHeaders()).thenReturn(headersMultiMap);
when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
- Response response = searchProvider.getNodesQueryResponse(
- httpHeaders,
- null,
- "cloud-region",
- keys,
- includeStrings,
- version.toString(),
- uriInfo
- );
+ Response response = searchProvider.getNodesQueryResponse(httpHeaders, null, "cloud-region",
+ keys, includeStrings, version.toString(), uriInfo);
assertNotNull(response);
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
assertThat(response.getEntity().toString(), containsString("4009"));
}
- //TODO fix test
+ // TODO fix test
@Ignore("Test has a time dependency and fails based on system perf")
@Test
public void testGenericQueryTimeoutThrown() throws Exception {
@@ -225,17 +208,8 @@ public class SearchProviderTest extends AAISetup{
when(httpHeaders.getAcceptableMediaTypes()).thenReturn(outputMediaTypes);
-
- Response response = searchProvider.getGenericQueryResponse(
- httpHeaders,
- null,
- "cloud-region",
- keys,
- includeStrings,
- 0,
- version.toString(),
- uriInfo
- );
+ Response response = searchProvider.getGenericQueryResponse(httpHeaders, null,
+ "cloud-region", keys, includeStrings, 0, version.toString(), uriInfo);
assertNotNull(response);
assertEquals(Response.Status.BAD_REQUEST.getStatusCode(), response.getStatus());
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceFromPserverAndSubsNameTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceFromPserverAndSubsNameTest.java
index 295480b..cfbe65e 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceFromPserverAndSubsNameTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceFromPserverAndSubsNameTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,84 +26,103 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class ServiceFromPserverAndSubsNameTest extends QueryTest {
- public ServiceFromPserverAndSubsNameTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
-
- //Set up the test graph
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver", "hostname", "pservername01");
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "2", "aai-node-type", "pserver", "hostname", "pservername02-wrong");
-
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserverid01");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "4", "aai-node-type", "vserver", "vserver-id", "vserverid02");
- Vertex vserver3 = graph.addVertex(T.label, "vserver", T.id, "5", "aai-node-type", "vserver", "vserver-id", "vserverid03");
-
- Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type", "generic-vnf", "vnf-id", "vnfid01");
- Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "9", "aai-node-type", "generic-vnf", "vnf-id", "vnfid02");
- Vertex vnf3 = graph.addVertex(T.label, "generic-vnf", T.id, "10", "aai-node-type", "generic-vnf", "vnf-id", "vnfid03");
-
- Vertex servinst1 = graph.addVertex(T.label, "service-instance", T.id, "61", "aai-node-type", "service-instance", "service-instance-id", "servInstId01", "service-type", "servType01");
- Vertex servinst2 = graph.addVertex(T.label, "service-instance", T.id, "12", "aai-node-type", "service-instance", "service-instance-id", "servInstId02", "service-type", "servType02", "service-role", "servRole02");
- Vertex servinst3 = graph.addVertex(T.label, "service-instance", T.id, "13", "aai-node-type", "service-instance", "service-instance-id", "servInstId03-wrong", "service-type", "servType03", "service-role", "servRole03");
-
- Vertex servsub1 = graph.addVertex(T.label, "service-subscription", T.id, "14", "aai-node-type", "service-subscription", "service-type", "servType01");
- Vertex servsub2 = graph.addVertex(T.label, "service-subscription", T.id, "15", "aai-node-type", "service-subscription", "service-type", "servType02");
- Vertex servsub3 = graph.addVertex(T.label, "service-subscription", T.id, "16", "aai-node-type", "service-subscription", "service-type", "servType03-wrong");
-
- Vertex customer1 = graph.addVertex(T.label, "customer", T.id, "17", "aai-node-type", "customer", "global-customer-id", "custid01", "subscriber-name", "subscriberName01");
- Vertex customer2 = graph.addVertex(T.label, "customer", T.id, "18", "aai-node-type", "customer", "global-customer-id", "custid02-wrong", "subscriber-name", "subscriberName-wrong");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, vserver1, pserver1); //true
- rules.addEdge(g, vnf1, vserver1); //true
- rules.addEdge(g, vnf1, servinst1); //true
- rules.addTreeEdge(g, servinst1, servsub1); //true
- rules.addTreeEdge(g, servsub1, customer1); //true
-
- rules.addEdge(g, vserver2, pserver1); //true
- rules.addEdge(g, vnf2, vserver2); //true
- rules.addEdge(g, vnf2, servinst2); //true
- rules.addTreeEdge(g, servinst2, servsub2); //true
- rules.addTreeEdge(g, servsub2, customer1); //true
-
- rules.addEdge(g, vserver3, pserver2); //false
- rules.addEdge(g, vnf3, vserver3); //false
- rules.addEdge(g, vnf3, servinst3); //false
- rules.addTreeEdge(g, servinst3, servsub3); //false
- rules.addTreeEdge(g, servsub3, customer2); //false
-
-
- expectedResult.add(servinst1);
- expectedResult.add(servsub1);
- expectedResult.add(servinst2);
- expectedResult.add(servsub2);
-
- }
-
- @Override
- protected String getQueryName() {
- return "service-fromPserverandSubsName";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type","pserver").has("hostname", "pservername01");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("subscriberName","subscriberName01");
- }
+ public ServiceFromPserverAndSubsNameTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+
+ // Set up the test graph
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver",
+ "hostname", "pservername01");
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "2", "aai-node-type", "pserver",
+ "hostname", "pservername02-wrong");
+
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver",
+ "vserver-id", "vserverid01");
+ Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "4", "aai-node-type", "vserver",
+ "vserver-id", "vserverid02");
+ Vertex vserver3 = graph.addVertex(T.label, "vserver", T.id, "5", "aai-node-type", "vserver",
+ "vserver-id", "vserverid03");
+
+ Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid01");
+ Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "9", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid02");
+ Vertex vnf3 = graph.addVertex(T.label, "generic-vnf", T.id, "10", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid03");
+
+ Vertex servinst1 = graph.addVertex(T.label, "service-instance", T.id, "61", "aai-node-type",
+ "service-instance", "service-instance-id", "servInstId01", "service-type",
+ "servType01");
+ Vertex servinst2 = graph.addVertex(T.label, "service-instance", T.id, "12", "aai-node-type",
+ "service-instance", "service-instance-id", "servInstId02", "service-type", "servType02",
+ "service-role", "servRole02");
+ Vertex servinst3 = graph.addVertex(T.label, "service-instance", T.id, "13", "aai-node-type",
+ "service-instance", "service-instance-id", "servInstId03-wrong", "service-type",
+ "servType03", "service-role", "servRole03");
+
+ Vertex servsub1 = graph.addVertex(T.label, "service-subscription", T.id, "14",
+ "aai-node-type", "service-subscription", "service-type", "servType01");
+ Vertex servsub2 = graph.addVertex(T.label, "service-subscription", T.id, "15",
+ "aai-node-type", "service-subscription", "service-type", "servType02");
+ Vertex servsub3 = graph.addVertex(T.label, "service-subscription", T.id, "16",
+ "aai-node-type", "service-subscription", "service-type", "servType03-wrong");
+
+ Vertex customer1 = graph.addVertex(T.label, "customer", T.id, "17", "aai-node-type",
+ "customer", "global-customer-id", "custid01", "subscriber-name", "subscriberName01");
+ Vertex customer2 =
+ graph.addVertex(T.label, "customer", T.id, "18", "aai-node-type", "customer",
+ "global-customer-id", "custid02-wrong", "subscriber-name", "subscriberName-wrong");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, vserver1, pserver1); // true
+ rules.addEdge(g, vnf1, vserver1); // true
+ rules.addEdge(g, vnf1, servinst1); // true
+ rules.addTreeEdge(g, servinst1, servsub1); // true
+ rules.addTreeEdge(g, servsub1, customer1); // true
+
+ rules.addEdge(g, vserver2, pserver1); // true
+ rules.addEdge(g, vnf2, vserver2); // true
+ rules.addEdge(g, vnf2, servinst2); // true
+ rules.addTreeEdge(g, servinst2, servsub2); // true
+ rules.addTreeEdge(g, servsub2, customer1); // true
+
+ rules.addEdge(g, vserver3, pserver2); // false
+ rules.addEdge(g, vnf3, vserver3); // false
+ rules.addEdge(g, vnf3, servinst3); // false
+ rules.addTreeEdge(g, servinst3, servsub3); // false
+ rules.addTreeEdge(g, servsub3, customer2); // false
+
+ expectedResult.add(servinst1);
+ expectedResult.add(servsub1);
+ expectedResult.add(servinst2);
+ expectedResult.add(servsub2);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "service-fromPserverandSubsName";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "pserver").has("hostname", "pservername01");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("subscriberName", "subscriberName01");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceModelsByDistributionStatusTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceModelsByDistributionStatusTest.java
index ee70b07..a0cdfb1 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceModelsByDistributionStatusTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceModelsByDistributionStatusTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,54 +30,69 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class ServiceModelsByDistributionStatusTest extends QueryTest {
- public ServiceModelsByDistributionStatusTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public ServiceModelsByDistributionStatusTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex model1 = graph.addVertex(T.label, "model", T.id, "1", "aai-node-type", "model",
+ "model-invariant-id", "model-invariant-id-1", "model-type", "resource");
+ Vertex modelver1 = graph.addVertex(T.label, "model-ver", T.id, "2", "aai-node-type",
+ "model-ver", "model-version-id", "model-version-id-1", "model-name", "model-name1",
+ "model-version", "model-version-1", "distribution-status", "distribution-status1");
+ Vertex modelver11 = graph.addVertex(T.label, "model-ver", T.id, "21", "aai-node-type",
+ "model-ver", "model-version-id", "model-version-id-11", "model-name", "model-name11",
+ "model-version", "model-version-1", "distribution-status", "distribution-status2");
+
+ Vertex model2 = graph.addVertex(T.label, "model", T.id, "3", "aai-node-type", "model",
+ "model-invariant-id", "model-invariant-id-2", "model-type", "resource");
+ Vertex modelver2 = graph.addVertex(T.label, "model-ver", T.id, "4", "aai-node-type",
+ "model-ver", "model-version-id", "model-version-id-2", "model-name", "model-name2",
+ "model-version", "model-version-22", "distribution-status", "distribution-status2");
+
+ Vertex model3 = graph.addVertex(T.label, "model", T.id, "5", "aai-node-type", "model",
+ "model-invariant-id", "model-invariant-id-3", "model-type", "service");
+ Vertex modelver3 = graph.addVertex(T.label, "model-ver", T.id, "6", "aai-node-type",
+ "model-ver", "model-version-id", "model-version-id-13", "model-name", "model-name3",
+ "model-version", "model-version-3", "distribution-status", "distribution-status1");
+ Vertex modelver13 = graph.addVertex(T.label, "model-ver", T.id, "7", "aai-node-type",
+ "model-ver", "model-version-id", "model-version-id-33", "model-name", "model-name33",
+ "model-version", "model-version-33", "distribution-status", "distribution-status2");
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex model1 = graph.addVertex(T.label, "model", T.id, "1", "aai-node-type", "model", "model-invariant-id", "model-invariant-id-1", "model-type", "resource");
- Vertex modelver1 = graph.addVertex(T.label, "model-ver", T.id, "2", "aai-node-type", "model-ver", "model-version-id", "model-version-id-1","model-name","model-name1", "model-version","model-version-1", "distribution-status", "distribution-status1");
- Vertex modelver11 = graph.addVertex(T.label, "model-ver", T.id, "21", "aai-node-type", "model-ver", "model-version-id", "model-version-id-11","model-name","model-name11", "model-version","model-version-1", "distribution-status", "distribution-status2");
-
- Vertex model2 = graph.addVertex(T.label, "model", T.id, "3", "aai-node-type", "model", "model-invariant-id", "model-invariant-id-2", "model-type", "resource");
- Vertex modelver2 = graph.addVertex(T.label, "model-ver", T.id, "4", "aai-node-type", "model-ver", "model-version-id", "model-version-id-2","model-name","model-name2", "model-version","model-version-22", "distribution-status", "distribution-status2");
-
- Vertex model3 = graph.addVertex(T.label, "model", T.id, "5", "aai-node-type", "model", "model-invariant-id", "model-invariant-id-3", "model-type", "service");
- Vertex modelver3 = graph.addVertex(T.label, "model-ver", T.id, "6", "aai-node-type", "model-ver", "model-version-id", "model-version-id-13","model-name","model-name3", "model-version","model-version-3", "distribution-status", "distribution-status1");
- Vertex modelver13 = graph.addVertex(T.label, "model-ver", T.id, "7", "aai-node-type", "model-ver", "model-version-id", "model-version-id-33","model-name","model-name33", "model-version","model-version-33", "distribution-status", "distribution-status2");
-
GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, modelver2,model2);
-
- rules.addTreeEdge(g, modelver3, model3);
- rules.addTreeEdge(g, modelver13, model3);
- rules.addTreeEdge(g, modelver11, model3);
-
- expectedResult.add(model3);
- expectedResult.add(modelver13);
- expectedResult.add(modelver11);
-
+ rules.addTreeEdge(g, modelver2, model2);
+
+ rules.addTreeEdge(g, modelver3, model3);
+ rules.addTreeEdge(g, modelver13, model3);
+ rules.addTreeEdge(g, modelver11, model3);
+
+ expectedResult.add(model3);
+ expectedResult.add(modelver13);
+ expectedResult.add(modelver11);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "serviceModels-byDistributionStatus";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "model").has("model-invariant-id", "model-invariant-id-3");
+ }
- }
- @Override
- protected String getQueryName() {
- return "serviceModels-byDistributionStatus";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "model").has("model-invariant-id", "model-invariant-id-3");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("distributionStatus", "distribution-status2");
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("distributionStatus", "distribution-status2");
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceSitesQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceSitesQueryTest.java
index bb970c6..dd61cf3 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceSitesQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceSitesQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,68 +26,74 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class ServiceSitesQueryTest extends QueryTest {
- public ServiceSitesQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
+ public ServiceSitesQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex customer1 = graph.addVertex(T.label, "customer", T.id, "0", "aai-node-type",
+ "customer", "global-customer-id", "customer1");
+ Vertex customer2 = graph.addVertex(T.label, "customer", T.id, "1", "aai-node-type",
+ "customer", "global-customer-id", "customer2");
+ Vertex service1 = graph.addVertex(T.label, "service-subscription", T.id, "2",
+ "aai-node-type", "service-subscription", "service-type", "service1");
+ Vertex service2 = graph.addVertex(T.label, "service-subscription", T.id, "3",
+ "aai-node-type", "service-subscription", "service-type", "service2");
+ Vertex instance = graph.addVertex(T.label, "service-instance", T.id, "4", "aai-node-type",
+ "service-instance");
+ Vertex vnf =
+ graph.addVertex(T.label, "generic-vnf", T.id, "5", "aai-node-type", "generic-vnf");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "6", "aai-node-type", "vserver");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "9", "aai-node-type", "tenant");
+ Vertex region =
+ graph.addVertex(T.label, "cloud-region", T.id, "10", "aai-node-type", "cloud-region");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "7", "aai-node-type", "pserver");
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "8", "aai-node-type", "complex");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addTreeEdge(g, customer1, service1);
+ rules.addTreeEdge(g, customer1, service2);
+ rules.addTreeEdge(g, service1, instance);
+ rules.addEdge(g, vnf, instance);
+ rules.addEdge(g, vnf, vserver);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addTreeEdge(g, tenant, region);
+ rules.addEdge(g, region, complex);
+ rules.addEdge(g, vserver, pserver);
+ rules.addEdge(g, pserver, complex);
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex customer1 = graph.addVertex(T.label, "customer", T.id, "0", "aai-node-type", "customer", "global-customer-id", "customer1");
- Vertex customer2 = graph.addVertex(T.label, "customer", T.id, "1", "aai-node-type", "customer", "global-customer-id", "customer2");
- Vertex service1 = graph.addVertex(T.label, "service-subscription", T.id, "2", "aai-node-type", "service-subscription", "service-type", "service1");
- Vertex service2 = graph.addVertex(T.label, "service-subscription", T.id, "3", "aai-node-type", "service-subscription", "service-type", "service2");
- Vertex instance = graph.addVertex(T.label, "service-instance", T.id, "4", "aai-node-type", "service-instance");
- Vertex vnf = graph.addVertex(T.label, "generic-vnf", T.id, "5", "aai-node-type", "generic-vnf");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "6", "aai-node-type", "vserver");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "9", "aai-node-type", "tenant");
- Vertex region = graph.addVertex(T.label, "cloud-region", T.id, "10", "aai-node-type", "cloud-region");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "7", "aai-node-type", "pserver");
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "8", "aai-node-type", "complex");
+ expectedResult.add(instance);
+ expectedResult.add(vnf);
+ expectedResult.add(region);
+ expectedResult.add(complex);
+ }
- GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, customer1, service1);
- rules.addTreeEdge(g, customer1, service2);
- rules.addTreeEdge(g, service1, instance);
- rules.addEdge(g, vnf, instance);
- rules.addEdge(g, vnf, vserver);
- rules.addTreeEdge(g, vserver, tenant);
- rules.addTreeEdge(g, tenant, region);
- rules.addEdge(g, region, complex);
- rules.addEdge(g, vserver, pserver);
- rules.addEdge(g, pserver, complex);
-
- expectedResult.add(instance);
- expectedResult.add(vnf);
- expectedResult.add(region);
- expectedResult.add(complex);
- }
+ @Override
+ protected String getQueryName() {
+ return "service-sites";
+ }
- @Override
- protected String getQueryName() {
- return "service-sites";
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "customer");
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "customer");
-
- }
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("customerId", "customer1");
- params.put("type", "service1");
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("customerId", "customer1");
+ params.put("type", "service1");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceTopologyTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceTopologyTest.java
index 21482aa..ecae9a7 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceTopologyTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/ServiceTopologyTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,8 @@
*/
package org.onap.aai.rest.search;
+import java.util.Map;
+
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.T;
@@ -27,8 +29,6 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-
public class ServiceTopologyTest extends QueryTest {
public ServiceTopologyTest() throws AAIException, NoEdgeRuleFoundException {
super();
@@ -38,84 +38,121 @@ public class ServiceTopologyTest extends QueryTest {
public void run() {
super.run();
}
+
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex servinst = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id", "servInstId01", "service-type", "servType01");
- Vertex gv = graph.addVertex(T.id, "2", "aai-node-type", "generic-vnf", "vnf-id", "gvId", "vnf-name", "name", "vnf-type", "type");
- Vertex vnfc = graph.addVertex(T.id, "3", "aai-node-type", "vnfc","vnfc-name", "vnfcName1", "nfc-naming-code", "blue", "nfc-function", "correct-function");
-
- Vertex vipipv4addresslist1 = graph.addVertex(T.label, "vip-ipv4-address-list", T.id, "4", "aai-node-type", "vip-ipv4-address-list", "vip-ipv4-addres", "vip-ipv4-address1");
- Vertex subnet1 = graph.addVertex(T.label, "subnet", T.id, "5", "aai-node-type", "subnet", "subnet-id", "subnet1");
- Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "6", "aai-node-type", "l3-network", "network-id", "network1-id1", "network-name", "network1-name1");
-
- Vertex vipipv6addresslist1 = graph.addVertex(T.label, "vip-ipv6-address-list", T.id, "7", "aai-node-type", "vip-ipv6-address-list", "vip-ipv6-address", "vip-ipv6-address2");
- Vertex subnet2 = graph.addVertex(T.label, "subnet", T.id, "8", "aai-node-type", "subnet", "subnet-id", "subnet2");
- Vertex l3network2 = graph.addVertex(T.label, "l3-network", T.id, "9", "aai-node-type", "l3-network", "network-id", "network1-id2", "network-name", "network2-name2");
-
- Vertex l3inter1ipv4addresslist1 = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "10", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "l3-interface-ipv4-address1");
- Vertex l3network3 = graph.addVertex(T.label, "l3-network", T.id, "11", "aai-node-type", "l3-network", "network-id", "network3-id3", "network-name", "network2-name3");
- Vertex subnet3 = graph.addVertex(T.label, "subnet", T.id, "12", "aai-node-type", "subnet", "subnet-id", "subnet3");
- Vertex l3network3_2 = graph.addVertex(T.label, "l3-network", T.id, "13", "aai-node-type", "l3-network", "network-id", "network3-id3", "network-name", "network3_2-name3_2");
-
- Vertex l3inter1ipv6addresslist1 = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "14", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "l3-interface-ipv6-address1");
- Vertex l3network4 = graph.addVertex(T.label, "l3-network", T.id, "15", "aai-node-type", "l3-network", "network-id", "network3-id3", "network-name", "network2-name4");
- Vertex subnet4 = graph.addVertex(T.label, "subnet", T.id, "16", "aai-node-type", "subnet", "subnet-id", "subnet4");
- Vertex l3network4_2 = graph.addVertex(T.label, "l3-network", T.id, "17", "aai-node-type", "l3-network", "network-id", "network3-id4", "network-name", "network4_2-name4_2");
-
-
- Vertex vserv1 = graph.addVertex(T.id, "18", "aai-node-type", "vserver", "vserver-id", "vservId1", "vserver-name", "vservName1");
- Vertex tenant1 = graph.addVertex(T.id, "19", "aai-node-type", "tenant", "tenant-id", "ten1", "tenant-name", "tenName1");
- Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "20", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id1", "l-interface-name", "l-interface-name1");
- Vertex l3inter1ipv4addresslist2 = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "21", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "l3-interface-ipv4-address2");
- Vertex l3network5 = graph.addVertex(T.label, "l3-network", T.id, "22", "aai-node-type", "l3-network", "network-id", "network3-id3", "network-name", "network2-name3");
- Vertex subnet5 = graph.addVertex(T.label, "subnet", T.id, "23", "aai-node-type", "subnet", "subnet-id", "subnet3");
- Vertex l3network5_2 = graph.addVertex(T.label, "l3-network", T.id, "24", "aai-node-type", "l3-network", "network-id", "network3-id3", "network-name", "network3_2-name3_2");
-
- Vertex l3inter1ipv6addresslist2 = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "25", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "l3-interface-ipv6-address1");
- Vertex l3network6 = graph.addVertex(T.label, "l3-network", T.id, "26", "aai-node-type", "l3-network", "network-id", "network3-id3", "network-name", "network2-name4");
- Vertex subnet6 = graph.addVertex(T.label, "subnet", T.id, "27", "aai-node-type", "subnet", "subnet-id", "subnet4");
- Vertex l3network6_2 = graph.addVertex(T.label, "l3-network", T.id, "28", "aai-node-type", "l3-network", "network-id", "network3-id4", "network-name", "network4_2-name4_2");
-
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "29", "aai-node-type", "pserver", "hostname", "pservername1");
-
-
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "30", "aai-node-type", "pserver", "hostname", "pservername1");
- Vertex pserverint = graph.addVertex(T.label, "p-interface", T.id, "31", "aai-node-type", "p-interface", "interface-name", "xe0/0/0");
- Vertex plink1 = graph.addVertex(T.label, "physical-link", T.id, "32", "aai-node-type", "physical-link", "link-name", "ge0/0/0-to-xe0/0/0");
+ Vertex servinst = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type",
+ "service-instance", "service-instance-id", "servInstId01", "service-type",
+ "servType01");
+ Vertex gv = graph.addVertex(T.id, "2", "aai-node-type", "generic-vnf", "vnf-id", "gvId",
+ "vnf-name", "name", "vnf-type", "type");
+ Vertex vnfc = graph.addVertex(T.id, "3", "aai-node-type", "vnfc", "vnfc-name", "vnfcName1",
+ "nfc-naming-code", "blue", "nfc-function", "correct-function");
+
+ Vertex vipipv4addresslist1 = graph.addVertex(T.label, "vip-ipv4-address-list", T.id, "4",
+ "aai-node-type", "vip-ipv4-address-list", "vip-ipv4-addres", "vip-ipv4-address1");
+ Vertex subnet1 = graph.addVertex(T.label, "subnet", T.id, "5", "aai-node-type", "subnet",
+ "subnet-id", "subnet1");
+ Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "6", "aai-node-type",
+ "l3-network", "network-id", "network1-id1", "network-name", "network1-name1");
+
+ Vertex vipipv6addresslist1 = graph.addVertex(T.label, "vip-ipv6-address-list", T.id, "7",
+ "aai-node-type", "vip-ipv6-address-list", "vip-ipv6-address", "vip-ipv6-address2");
+ Vertex subnet2 = graph.addVertex(T.label, "subnet", T.id, "8", "aai-node-type", "subnet",
+ "subnet-id", "subnet2");
+ Vertex l3network2 = graph.addVertex(T.label, "l3-network", T.id, "9", "aai-node-type",
+ "l3-network", "network-id", "network1-id2", "network-name", "network2-name2");
+
+ Vertex l3inter1ipv4addresslist1 = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "10", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address1");
+ Vertex l3network3 = graph.addVertex(T.label, "l3-network", T.id, "11", "aai-node-type",
+ "l3-network", "network-id", "network3-id3", "network-name", "network2-name3");
+ Vertex subnet3 = graph.addVertex(T.label, "subnet", T.id, "12", "aai-node-type", "subnet",
+ "subnet-id", "subnet3");
+ Vertex l3network3_2 = graph.addVertex(T.label, "l3-network", T.id, "13", "aai-node-type",
+ "l3-network", "network-id", "network3-id3", "network-name", "network3_2-name3_2");
+
+ Vertex l3inter1ipv6addresslist1 = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "14", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address1");
+ Vertex l3network4 = graph.addVertex(T.label, "l3-network", T.id, "15", "aai-node-type",
+ "l3-network", "network-id", "network3-id3", "network-name", "network2-name4");
+ Vertex subnet4 = graph.addVertex(T.label, "subnet", T.id, "16", "aai-node-type", "subnet",
+ "subnet-id", "subnet4");
+ Vertex l3network4_2 = graph.addVertex(T.label, "l3-network", T.id, "17", "aai-node-type",
+ "l3-network", "network-id", "network3-id4", "network-name", "network4_2-name4_2");
+
+ Vertex vserv1 = graph.addVertex(T.id, "18", "aai-node-type", "vserver", "vserver-id",
+ "vservId1", "vserver-name", "vservName1");
+ Vertex tenant1 = graph.addVertex(T.id, "19", "aai-node-type", "tenant", "tenant-id", "ten1",
+ "tenant-name", "tenName1");
+ Vertex linterface1 =
+ graph.addVertex(T.label, "l-interface", T.id, "20", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id1", "l-interface-name", "l-interface-name1");
+ Vertex l3inter1ipv4addresslist2 = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "21", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address2");
+ Vertex l3network5 = graph.addVertex(T.label, "l3-network", T.id, "22", "aai-node-type",
+ "l3-network", "network-id", "network3-id3", "network-name", "network2-name3");
+ Vertex subnet5 = graph.addVertex(T.label, "subnet", T.id, "23", "aai-node-type", "subnet",
+ "subnet-id", "subnet3");
+ Vertex l3network5_2 = graph.addVertex(T.label, "l3-network", T.id, "24", "aai-node-type",
+ "l3-network", "network-id", "network3-id3", "network-name", "network3_2-name3_2");
+
+ Vertex l3inter1ipv6addresslist2 = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "25", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address1");
+ Vertex l3network6 = graph.addVertex(T.label, "l3-network", T.id, "26", "aai-node-type",
+ "l3-network", "network-id", "network3-id3", "network-name", "network2-name4");
+ Vertex subnet6 = graph.addVertex(T.label, "subnet", T.id, "27", "aai-node-type", "subnet",
+ "subnet-id", "subnet4");
+ Vertex l3network6_2 = graph.addVertex(T.label, "l3-network", T.id, "28", "aai-node-type",
+ "l3-network", "network-id", "network3-id4", "network-name", "network4_2-name4_2");
+
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "29", "aai-node-type",
+ "pserver", "hostname", "pservername1");
+
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "30", "aai-node-type",
+ "pserver", "hostname", "pservername1");
+ Vertex pserverint = graph.addVertex(T.label, "p-interface", T.id, "31", "aai-node-type",
+ "p-interface", "interface-name", "xe0/0/0");
+ Vertex plink1 = graph.addVertex(T.label, "physical-link", T.id, "32", "aai-node-type",
+ "physical-link", "link-name", "ge0/0/0-to-xe0/0/0");
GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, servinst , gv);
- rules.addEdge(g,gv,vnfc);
- rules.addEdge(g,vnfc,vipipv4addresslist1);
- rules.addEdge(g,vipipv4addresslist1,subnet1);
- rules.addTreeEdge(g,subnet1,l3network1);
- rules.addEdge(g,vnfc,vipipv6addresslist1);
- rules.addEdge(g,vipipv6addresslist1,subnet2);
- rules.addTreeEdge(g,subnet2,l3network2);
- rules.addTreeEdge(g,vnfc,l3inter1ipv4addresslist1);
- rules.addEdge(g,l3inter1ipv4addresslist1,l3network3);
- rules.addEdge(g,l3inter1ipv4addresslist1,subnet3);
- rules.addTreeEdge(g,subnet3,l3network3_2);
- rules.addTreeEdge(g,vnfc,l3inter1ipv6addresslist1);
- rules.addEdge(g,l3inter1ipv6addresslist1,l3network4);
- rules.addEdge(g,l3inter1ipv6addresslist1,subnet4);
- rules.addTreeEdge(g,subnet4,l3network4_2);
- rules.addEdge(g,gv,vserv1);
- rules.addTreeEdge(g,vserv1,tenant1);
- rules.addTreeEdge(g,vserv1,linterface1);
- rules.addTreeEdge(g,linterface1,l3inter1ipv4addresslist2);
- rules.addEdge(g,l3inter1ipv4addresslist2,l3network5);
- rules.addEdge(g,l3inter1ipv4addresslist2,subnet5);
- rules.addTreeEdge(g,subnet5,l3network5_2);
- rules.addTreeEdge(g,linterface1,l3inter1ipv6addresslist2);
- rules.addEdge(g,l3inter1ipv6addresslist2,l3network6);
- rules.addEdge(g,l3inter1ipv6addresslist2,subnet6);
- rules.addTreeEdge(g,subnet6,l3network6_2);
- rules.addEdge(g,vserv1,pserver1);
- rules.addEdge(g,gv,pserver2);
- rules.addTreeEdge(g,pserver2,pserverint);
- rules.addEdge(g,pserverint,plink1);
+ rules.addEdge(g, servinst, gv);
+ rules.addEdge(g, gv, vnfc);
+ rules.addEdge(g, vnfc, vipipv4addresslist1);
+ rules.addEdge(g, vipipv4addresslist1, subnet1);
+ rules.addTreeEdge(g, subnet1, l3network1);
+ rules.addEdge(g, vnfc, vipipv6addresslist1);
+ rules.addEdge(g, vipipv6addresslist1, subnet2);
+ rules.addTreeEdge(g, subnet2, l3network2);
+ rules.addTreeEdge(g, vnfc, l3inter1ipv4addresslist1);
+ rules.addEdge(g, l3inter1ipv4addresslist1, l3network3);
+ rules.addEdge(g, l3inter1ipv4addresslist1, subnet3);
+ rules.addTreeEdge(g, subnet3, l3network3_2);
+ rules.addTreeEdge(g, vnfc, l3inter1ipv6addresslist1);
+ rules.addEdge(g, l3inter1ipv6addresslist1, l3network4);
+ rules.addEdge(g, l3inter1ipv6addresslist1, subnet4);
+ rules.addTreeEdge(g, subnet4, l3network4_2);
+ rules.addEdge(g, gv, vserv1);
+ rules.addTreeEdge(g, vserv1, tenant1);
+ rules.addTreeEdge(g, vserv1, linterface1);
+ rules.addTreeEdge(g, linterface1, l3inter1ipv4addresslist2);
+ rules.addEdge(g, l3inter1ipv4addresslist2, l3network5);
+ rules.addEdge(g, l3inter1ipv4addresslist2, subnet5);
+ rules.addTreeEdge(g, subnet5, l3network5_2);
+ rules.addTreeEdge(g, linterface1, l3inter1ipv6addresslist2);
+ rules.addEdge(g, l3inter1ipv6addresslist2, l3network6);
+ rules.addEdge(g, l3inter1ipv6addresslist2, subnet6);
+ rules.addTreeEdge(g, subnet6, l3network6_2);
+ rules.addEdge(g, vserv1, pserver1);
+ rules.addEdge(g, gv, pserver2);
+ rules.addTreeEdge(g, pserver2, pserverint);
+ rules.addEdge(g, pserverint, plink1);
expectedResult.add(servinst);
expectedResult.add(gv);
@@ -150,8 +187,8 @@ public class ServiceTopologyTest extends QueryTest {
expectedResult.add(pserverint);
expectedResult.add(plink1);
-
}
+
@Override
protected String getQueryName() {
return "service-topology";
@@ -161,6 +198,7 @@ public class ServiceTopologyTest extends QueryTest {
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
g.has("aai-node-type", "service-instance");
}
+
@Override
protected void addParam(Map<String, Object> params) {
return;
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/SimpleFormatTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/SimpleFormatTest.java
index 934d3fa..0b53b72 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/SimpleFormatTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/SimpleFormatTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,7 +19,16 @@
*/
package org.onap.aai.rest.search;
+import static org.junit.Assert.assertNotNull;
+import static org.junit.Assert.assertTrue;
+import static org.mockito.Mockito.spy;
+import static org.mockito.Mockito.when;
+
import com.google.gson.JsonObject;
+
+import java.util.ArrayList;
+import java.util.List;
+
import org.apache.tinkerpop.gremlin.structure.Graph;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
@@ -42,78 +51,66 @@ import org.onap.aai.serialization.queryformats.exceptions.AAIFormatVertexExcepti
import org.onap.aai.serialization.queryformats.utils.UrlBuilder;
import org.springframework.test.annotation.DirtiesContext;
-import java.util.ArrayList;
-import java.util.List;
+@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
+public class SimpleFormatTest extends AAISetup {
-import static org.junit.Assert.assertNotNull;
-import static org.junit.Assert.assertTrue;
-import static org.mockito.Mockito.spy;
-import static org.mockito.Mockito.when;
+ protected Graph graph;
+ private TransactionalGraphEngine dbEngine;
-@DirtiesContext(classMode = DirtiesContext.ClassMode.BEFORE_CLASS)
-public class SimpleFormatTest extends AAISetup{
-
-
- protected Graph graph;
- private TransactionalGraphEngine dbEngine;
-
- protected final List<Vertex> expectedResult = new ArrayList<>();
-
- protected Loader loader;
- private DBSerializer serializer;
-
- @Mock
- private UrlBuilder urlBuilder;
- private RawFormat _simpleFormat;
-
- Vertex vfmodule = null;
-
- @Before
- public void setUp() throws AAIException, NoEdgeRuleFoundException {
- MockitoAnnotations.initMocks(this);
- graph = TinkerGraph.open();
- loader = loaderFactory.createLoaderForVersion(ModelType.MOXY, schemaVersions.getRelatedLinkVersion());
- vfmodule = graph.addVertex(T.label, "vf-module",
- T.id, "5",
- "aai-node-type", "vf-module",
- "vf-module-id", "vf-module-id-val-68205",
- "vf-module-name", "example-vf-module-name-val-68205",
- "heat-stack-id", "example-heat-stack-id-val-68205",
- "orchestration-status", "example-orchestration-status-val-68205",
- "is-base-vf-module", "true",
- "resource-version", "1498166571906",
- "model-invariant-id", "fe8aac07-ce6c-4f9f-aa0d-b561c77da9e8",
- "model-invariant-id-local", "fe8aac07-ce6c-4f9f-aa0d-b561c77da9e8",
- "model-version-id", "0d23052d-8ffe-433e-a25d-da5da027bb7c",
- "model-version-id-local", "0d23052d-8ffe-433e-a25d-da5da027bb7c",
- "widget-model-id", "example-widget-model-id-val-68205",
- "widget-model-version", "example-widget--model-version-val-68205",
- "contrail-service-instance-fqdn", "example-contrail-service-instance-fqdn-val-68205");
-
- final ModelType factoryType = ModelType.MOXY;
- Loader loader = loaderFactory.createLoaderForVersion(factoryType, schemaVersions.getRelatedLinkVersion());
- dbEngine = spy(new JanusGraphDBEngine(
- QueryStyle.TRAVERSAL,
- loader));
-
- when(dbEngine.tx()).thenReturn(graph);
- TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin());
- when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal());
- when(dbEngine.asAdmin()).thenReturn(spyAdmin);
- serializer = new DBSerializer(schemaVersions.getRelatedLinkVersion(), dbEngine, factoryType, "Junit");
- _simpleFormat = new RawFormat.Builder(loader, serializer, urlBuilder).modelDriven().build();
- dbEngine.startTransaction();
- }
-
- @Test
- public void run() throws AAIFormatVertexException {
- assertNotNull(dbEngine.tx());
- System.out.println(dbEngine.tx());
- assertNotNull(graph.traversal());
- JsonObject json = _simpleFormat.createPropertiesObject(vfmodule).get();
- json.entrySet().forEach((System.out::println));
- assertTrue(json.has("model-invariant-id"));
-
- }
+ protected final List<Vertex> expectedResult = new ArrayList<>();
+
+ protected Loader loader;
+ private DBSerializer serializer;
+
+ @Mock
+ private UrlBuilder urlBuilder;
+ private RawFormat _simpleFormat;
+
+ Vertex vfmodule = null;
+
+ @Before
+ public void setUp() throws AAIException, NoEdgeRuleFoundException {
+ MockitoAnnotations.initMocks(this);
+ graph = TinkerGraph.open();
+ loader = loaderFactory.createLoaderForVersion(ModelType.MOXY,
+ schemaVersions.getRelatedLinkVersion());
+ vfmodule = graph.addVertex(T.label, "vf-module", T.id, "5", "aai-node-type", "vf-module",
+ "vf-module-id", "vf-module-id-val-68205", "vf-module-name",
+ "example-vf-module-name-val-68205", "heat-stack-id", "example-heat-stack-id-val-68205",
+ "orchestration-status", "example-orchestration-status-val-68205", "is-base-vf-module",
+ "true", "resource-version", "1498166571906", "model-invariant-id",
+ "fe8aac07-ce6c-4f9f-aa0d-b561c77da9e8", "model-invariant-id-local",
+ "fe8aac07-ce6c-4f9f-aa0d-b561c77da9e8", "model-version-id",
+ "0d23052d-8ffe-433e-a25d-da5da027bb7c", "model-version-id-local",
+ "0d23052d-8ffe-433e-a25d-da5da027bb7c", "widget-model-id",
+ "example-widget-model-id-val-68205", "widget-model-version",
+ "example-widget--model-version-val-68205", "contrail-service-instance-fqdn",
+ "example-contrail-service-instance-fqdn-val-68205");
+
+ final ModelType factoryType = ModelType.MOXY;
+ Loader loader = loaderFactory.createLoaderForVersion(factoryType,
+ schemaVersions.getRelatedLinkVersion());
+ dbEngine = spy(new JanusGraphDBEngine(QueryStyle.TRAVERSAL, loader));
+
+ when(dbEngine.tx()).thenReturn(graph);
+ TransactionalGraphEngine.Admin spyAdmin = spy(dbEngine.asAdmin());
+ when(spyAdmin.getTraversalSource()).thenReturn(graph.traversal());
+ when(dbEngine.asAdmin()).thenReturn(spyAdmin);
+ serializer = new DBSerializer(schemaVersions.getRelatedLinkVersion(), dbEngine, factoryType,
+ "Junit");
+ _simpleFormat = new RawFormat.Builder(loader, serializer, urlBuilder).modelDriven().build();
+ dbEngine.startTransaction();
+ }
+
+ @Test
+ public void run() throws AAIFormatVertexException {
+ assertNotNull(dbEngine.tx());
+ System.out.println(dbEngine.tx());
+ assertNotNull(graph.traversal());
+ JsonObject json = _simpleFormat.createPropertiesObject(vfmodule).get();
+ json.entrySet().forEach((System.out::println));
+ assertTrue(json.has("model-invariant-id"));
+
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/SiteL3NetworkCloudRegionQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/SiteL3NetworkCloudRegionQueryTest.java
index 74ee775..9538be9 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/SiteL3NetworkCloudRegionQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/SiteL3NetworkCloudRegionQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,59 +26,65 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class SiteL3NetworkCloudRegionQueryTest extends QueryTest {
- public SiteL3NetworkCloudRegionQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public SiteL3NetworkCloudRegionQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex",
+ "physical-location-id", "clli");
+ Vertex network =
+ graph.addVertex(T.label, "l3-network", T.id, "1", "aai-node-type", "l3-network");
+ Vertex region =
+ graph.addVertex(T.label, "cloud-region", T.id, "2", "aai-node-type", "cloud-region");
+ Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex",
+ "physical-location-id", "clli2");
+ Vertex network2 =
+ graph.addVertex(T.label, "l3-network", T.id, "4", "aai-node-type", "l3-network");
+ Vertex region2 =
+ graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type", "cloud-region");
+ Vertex network3 =
+ graph.addVertex(T.label, "l3-network", T.id, "6", "aai-node-type", "l3-network");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, complex, network);
+ rules.addEdge(g, region, network);
+ rules.addEdge(g, complex, network3);
+ rules.addEdge(g, complex2, network2);
+ rules.addEdge(g, region2, network2);
+
+ expectedResult.add(complex);
+ expectedResult.add(network);
+ expectedResult.add(region);
+ expectedResult.add(network3);
+
+ }
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex", "physical-location-id", "clli");
- Vertex network = graph.addVertex(T.label, "l3-network", T.id, "1", "aai-node-type", "l3-network");
- Vertex region = graph.addVertex(T.label, "cloud-region", T.id, "2", "aai-node-type", "cloud-region");
- Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex", "physical-location-id", "clli2");
- Vertex network2 = graph.addVertex(T.label, "l3-network", T.id, "4", "aai-node-type", "l3-network");
- Vertex region2 = graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type", "cloud-region");
- Vertex network3 = graph.addVertex(T.label, "l3-network", T.id, "6", "aai-node-type", "l3-network");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, complex, network);
- rules.addEdge(g, region, network);
- rules.addEdge(g, complex, network3);
- rules.addEdge(g, complex2, network2);
- rules.addEdge(g, region2, network2);
-
- expectedResult.add(complex);
- expectedResult.add(network);
- expectedResult.add(region);
- expectedResult.add(network3);
-
- }
+ @Override
+ protected String getQueryName() {
+ return "site-l3network-cloudRegion";
+ }
- @Override
- protected String getQueryName() {
- return "site-l3network-cloudRegion";
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("physical-location-id", "clli");
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("physical-location-id", "clli");
-
- }
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/SitesByCloudRegionIdQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/SitesByCloudRegionIdQueryTest.java
index abc518c..3686ef3 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/SitesByCloudRegionIdQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/SitesByCloudRegionIdQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,54 +26,58 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class SitesByCloudRegionIdQueryTest extends QueryTest {
- public SitesByCloudRegionIdQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public SitesByCloudRegionIdQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex");
+ Vertex network =
+ graph.addVertex(T.label, "l3-network", T.id, "1", "aai-node-type", "l3-network");
+ Vertex region = graph.addVertex(T.label, "cloud-region", T.id, "2", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionuuid");
+ Vertex complex2 =
+ graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex");
+ Vertex network2 =
+ graph.addVertex(T.label, "l3-network", T.id, "4", "aai-node-type", "l3-network");
+ Vertex region2 = graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionuuid2");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, complex, network);
+ rules.addEdge(g, region, network);
+ rules.addEdge(g, complex2, network2);
+ rules.addEdge(g, region2, network2);
+
+ expectedResult.add(complex);
+
+ }
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex");
- Vertex network = graph.addVertex(T.label, "l3-network", T.id, "1", "aai-node-type", "l3-network");
- Vertex region = graph.addVertex(T.label, "cloud-region", T.id, "2", "aai-node-type", "cloud-region", "cloud-region-id", "regionuuid");
- Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex");
- Vertex network2 = graph.addVertex(T.label, "l3-network", T.id, "4", "aai-node-type", "l3-network");
- Vertex region2 = graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type", "cloud-region", "cloud-region-id", "regionuuid2");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, complex, network);
- rules.addEdge(g, region, network);
- rules.addEdge(g, complex2, network2);
- rules.addEdge(g, region2, network2);
-
- expectedResult.add(complex);
-
- }
+ @Override
+ protected String getQueryName() {
+ return "sites-byCloudRegionId";
+ }
- @Override
- protected String getQueryName() {
- return "sites-byCloudRegionId";
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("cloud-region-id", "regionuuid");
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("cloud-region-id", "regionuuid");
-
- }
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/SitesByCountryFilterCloudRegionIdQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/SitesByCountryFilterCloudRegionIdQueryTest.java
index 25ca62b..4c1dc14 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/SitesByCountryFilterCloudRegionIdQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/SitesByCountryFilterCloudRegionIdQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
package org.onap.aai.rest.search;
+
import java.util.Map;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
@@ -25,61 +26,67 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class SitesByCountryFilterCloudRegionIdQueryTest extends QueryTest {
-
- public SitesByCountryFilterCloudRegionIdQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public SitesByCountryFilterCloudRegionIdQueryTest()
+ throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+
+ // Set up the test graph
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex",
+ "physical-location-id", "clli-100", "country", "countrycode-100");
+ Vertex l3network = graph.addVertex(T.label, "l3-network", T.id, "1", "aai-node-type",
+ "l3-network", "network-id", "networkId-100", "network-name", "networkName-100",
+ "is-bound-to-vpn", "false", "is-provider-network", "false", "is-shared-network",
+ "false", "is-external-network", "false");
+ Vertex cloudregion =
+ graph.addVertex(T.label, "cloud-region", T.id, "2", "aai-node-type", "cloud-region",
+ "cloud-owner", "cloudOwner-100", "cloud-region-id", "cloudRegionId-100");
+ Vertex cloudregion2 =
+ graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region",
+ "cloud-owner", "cloudOwner-200", "cloud-region-id", "cloudRegionId-200");
+ Vertex l3network2 = graph.addVertex(T.label, "l3-network", T.id, "4", "aai-node-type",
+ "l3-network", "network-id", "networkId-200", "network-name", "networkName-200",
+ "is-bound-to-vpn", "false", "is-provider-network", "false", "is-shared-network",
+ "false", "is-external-network", "false");
+ Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "5", "aai-node-type", "complex",
+ "physical-location-id", "clli-200", "country", "countrycode-100");
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
- //Set up the test graph
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex", "physical-location-id", "clli-100", "country", "countrycode-100");
- Vertex l3network = graph.addVertex(T.label, "l3-network", T.id, "1", "aai-node-type", "l3-network", "network-id", "networkId-100", "network-name", "networkName-100",
- "is-bound-to-vpn", "false", "is-provider-network", "false", "is-shared-network", "false", "is-external-network", "false");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "2", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner-100", "cloud-region-id", "cloudRegionId-100");
- Vertex cloudregion2 = graph.addVertex(T.label, "cloud-region", T.id, "3", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner-200", "cloud-region-id", "cloudRegionId-200");
- Vertex l3network2 = graph.addVertex(T.label, "l3-network", T.id, "4", "aai-node-type", "l3-network", "network-id", "networkId-200", "network-name", "networkName-200",
- "is-bound-to-vpn", "false", "is-provider-network", "false", "is-shared-network", "false", "is-external-network", "false");
- Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "5", "aai-node-type", "complex", "physical-location-id", "clli-200", "country", "countrycode-100");
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, complex, l3network);
+ rules.addEdge(g, cloudregion, l3network);
+ rules.addEdge(g, complex2, l3network2);
+ rules.addEdge(g, cloudregion2, l3network2);
+ expectedResult.add(complex);
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, complex, l3network);
- rules.addEdge(g, cloudregion, l3network);
- rules.addEdge(g, complex2, l3network2);
- rules.addEdge(g, cloudregion2, l3network2);
-
- expectedResult.add(complex);
-
+ }
- }
+ @Override
+ protected String getQueryName() {
+ return "sites-byCountryFilterCloudRegionId";
+ }
- @Override
- protected String getQueryName() {
- return "sites-byCountryFilterCloudRegionId";
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "complex").has("country", "countrycode-100");
+ }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "complex").has("country", "countrycode-100");
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("cloudRegionId", "cloudRegionId-100");
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("cloudRegionId", "cloudRegionId-100");
-
- }
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/SitesByCountryFilterCloudRegionVerQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/SitesByCountryFilterCloudRegionVerQueryTest.java
index 92ecfc2..383f188 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/SitesByCountryFilterCloudRegionVerQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/SitesByCountryFilterCloudRegionVerQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -18,6 +18,7 @@
* ============LICENSE_END=========================================================
*/
package org.onap.aai.rest.search;
+
import java.util.Map;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
@@ -25,62 +26,68 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class SitesByCountryFilterCloudRegionVerQueryTest extends QueryTest {
-
- public SitesByCountryFilterCloudRegionVerQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public SitesByCountryFilterCloudRegionVerQueryTest()
+ throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+
+ // Set up the test graph
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex",
+ "physical-location-id", "clli-100", "country", "countrycode-100");
+ Vertex l3network = graph.addVertex(T.label, "l3-network", T.id, "1", "aai-node-type",
+ "l3-network", "network-id", "networkId-100", "network-name", "networkName-100",
+ "is-bound-to-vpn", "false", "is-provider-network", "false", "is-shared-network",
+ "false", "is-external-network", "false");
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "2", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloudOwner-100", "cloud-region-id", "cloudRegionId-100",
+ "cloud-region-version", "cloudRegionVer-3.0");
+ Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex",
+ "physical-location-id", "clli-200", "country", "countrycode-100");
+ Vertex l3network2 = graph.addVertex(T.label, "l3-network", T.id, "4", "aai-node-type",
+ "l3-network", "network-id", "networkId-200", "network-name", "networkName-200",
+ "is-bound-to-vpn", "false", "is-provider-network", "false", "is-shared-network",
+ "false", "is-external-network", "false");
+ Vertex cloudregion2 = graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloudOwner-200", "cloud-region-id", "cloudRegionId-200",
+ "cloud-region-version", "cloudRegionVer-2.5");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, complex, l3network);
+ rules.addEdge(g, cloudregion, l3network);
+ rules.addEdge(g, complex2, l3network2);
+ rules.addEdge(g, cloudregion2, l3network2);
+
+ expectedResult.add(complex);
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
- //Set up the test graph
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex", "physical-location-id", "clli-100", "country", "countrycode-100");
- Vertex l3network = graph.addVertex(T.label, "l3-network", T.id, "1", "aai-node-type", "l3-network", "network-id", "networkId-100", "network-name", "networkName-100",
- "is-bound-to-vpn", "false", "is-provider-network", "false", "is-shared-network", "false", "is-external-network", "false");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "2", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner-100", "cloud-region-id", "cloudRegionId-100",
- "cloud-region-version", "cloudRegionVer-3.0");
- Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "3", "aai-node-type", "complex", "physical-location-id", "clli-200", "country", "countrycode-100");
- Vertex l3network2 = graph.addVertex(T.label, "l3-network", T.id, "4", "aai-node-type", "l3-network", "network-id", "networkId-200", "network-name", "networkName-200",
- "is-bound-to-vpn", "false", "is-provider-network", "false", "is-shared-network", "false", "is-external-network", "false");
- Vertex cloudregion2 = graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner-200", "cloud-region-id", "cloudRegionId-200",
- "cloud-region-version", "cloudRegionVer-2.5");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, complex, l3network);
- rules.addEdge(g, cloudregion, l3network);
- rules.addEdge(g, complex2, l3network2);
- rules.addEdge(g, cloudregion2, l3network2);
+ }
- expectedResult.add(complex);
-
+ @Override
+ protected String getQueryName() {
+ return "sites-byCountryFilterCloudRegionVer";
+ }
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "complex").has("country", "countrycode-100");
- @Override
- protected String getQueryName() {
- return "sites-byCountryFilterCloudRegionVer";
- }
+ }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "complex").has("country", "countrycode-100");
-
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("cloudRegionVersion", "cloudRegionVer-3.0");
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("cloudRegionVersion", "cloudRegionVer-3.0");
-
- }
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/SriovTopologyFromVnfQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/SriovTopologyFromVnfQueryTest.java
index cceab09..953b814 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/SriovTopologyFromVnfQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/SriovTopologyFromVnfQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,80 +30,92 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class SriovTopologyFromVnfQueryTest extends QueryTest {
- public SriovTopologyFromVnfQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
-
- //Set up the test graph
- Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf",
- "vnf-id", "gvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "1", "aai-node-type", "vserver","vserver-name", "vservername1");
- Vertex lint1 = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type", "l-interface",
- "interface-name", "lint1", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false");
-
- Vertex sriovVf1 = graph.addVertex(T.label, "sriov-vf", T.id, "3", "aai-node-type", "sriov-vf", "pci-id", "pcIid1");
- Vertex sriovPf1 = graph.addVertex(T.label, "sriov-pf", T.id, "4", "aai-node-type", "sriov-pf", "pf-pci-id", "pfPciId1");
-
- Vertex pint1 = graph.addVertex(T.label, "p-interface", T.id, "5", "aai-node-type", "p-interface", "interface-name", "ge0/0/0");
- Vertex plink1 = graph.addVertex(T.label, "physical-link", T.id, "6", "aai-node-type", "physical-link", "link-name", "ge0/0/0-to-xe0/0/0");
-
-
- Vertex gvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "10", "aai-node-type", "generic-vnf",
- "vnf-id", "gvnf2", "vnf-name", "genvnfname2", "nf-type", "sample-nf-type1");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type", "vserver","vserver-name", "vservername2");
- Vertex lint2 = graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type", "l-interface",
- "interface-name", "lint2", "is-port-mirrored", "true", "in-maint", "true", "is-ip-unnumbered", "false");
-
- Vertex sriovVf2 = graph.addVertex(T.label, "sriov-vf", T.id, "13", "aai-node-type", "sriov-vf", "pci-id", "pcIid2");
- Vertex sriovPf2 = graph.addVertex(T.label, "sriov-pf", T.id, "14", "aai-node-type", "sriov-pf", "pf-pci-id", "pfPciId2");
-
- Vertex pint2 = graph.addVertex(T.label, "p-interface", T.id, "15", "aai-node-type", "p-interface", "interface-name", "ge0/0/1");
- Vertex plink2 = graph.addVertex(T.label, "physical-link", T.id, "16", "aai-node-type", "physical-link", "link-name", "ge0/0/0-to-xe0/0/1");
-
-
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addEdge(g, gvnf1, vserver1);
- rules.addTreeEdge(g, vserver1, lint1);
- rules.addTreeEdge(g, lint1, sriovVf1);
- rules.addEdge(g, sriovVf1, sriovPf1);
- rules.addTreeEdge(g, sriovPf1, pint1);
- rules.addEdge(g, pint1, plink1);
-
- rules.addEdge(g, gvnf2, vserver2);//false
- rules.addTreeEdge(g, vserver2, lint2);//false
- rules.addTreeEdge(g, lint2, sriovVf2);//false
- rules.addEdge(g, sriovVf2, sriovPf2);//false
- rules.addTreeEdge(g, sriovPf2, pint2);//false
- rules.addEdge(g, pint2, plink2);//false
-
-
- expectedResult.add(gvnf1);
- expectedResult.add(vserver1);
- expectedResult.add(sriovVf1);
- expectedResult.add(plink1);
-
- }
- @Override
- protected String getQueryName() {
- return "sriov-topology-fromVnf";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type","generic-vnf").has("vnf-id", "gvnf1").has("vnf-name", "genvnfname1");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ public SriovTopologyFromVnfQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+
+ // Set up the test graph
+ Vertex gvnf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf",
+ "vnf-id", "gvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "1", "aai-node-type", "vserver",
+ "vserver-name", "vservername1");
+ Vertex lint1 = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type",
+ "l-interface", "interface-name", "lint1", "is-port-mirrored", "true", "in-maint",
+ "true", "is-ip-unnumbered", "false");
+
+ Vertex sriovVf1 = graph.addVertex(T.label, "sriov-vf", T.id, "3", "aai-node-type",
+ "sriov-vf", "pci-id", "pcIid1");
+ Vertex sriovPf1 = graph.addVertex(T.label, "sriov-pf", T.id, "4", "aai-node-type",
+ "sriov-pf", "pf-pci-id", "pfPciId1");
+
+ Vertex pint1 = graph.addVertex(T.label, "p-interface", T.id, "5", "aai-node-type",
+ "p-interface", "interface-name", "ge0/0/0");
+ Vertex plink1 = graph.addVertex(T.label, "physical-link", T.id, "6", "aai-node-type",
+ "physical-link", "link-name", "ge0/0/0-to-xe0/0/0");
+
+ Vertex gvnf2 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "10", "aai-node-type", "generic-vnf",
+ "vnf-id", "gvnf2", "vnf-name", "genvnfname2", "nf-type", "sample-nf-type1");
+ Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type",
+ "vserver", "vserver-name", "vservername2");
+ Vertex lint2 = graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type",
+ "l-interface", "interface-name", "lint2", "is-port-mirrored", "true", "in-maint",
+ "true", "is-ip-unnumbered", "false");
+
+ Vertex sriovVf2 = graph.addVertex(T.label, "sriov-vf", T.id, "13", "aai-node-type",
+ "sriov-vf", "pci-id", "pcIid2");
+ Vertex sriovPf2 = graph.addVertex(T.label, "sriov-pf", T.id, "14", "aai-node-type",
+ "sriov-pf", "pf-pci-id", "pfPciId2");
+
+ Vertex pint2 = graph.addVertex(T.label, "p-interface", T.id, "15", "aai-node-type",
+ "p-interface", "interface-name", "ge0/0/1");
+ Vertex plink2 = graph.addVertex(T.label, "physical-link", T.id, "16", "aai-node-type",
+ "physical-link", "link-name", "ge0/0/0-to-xe0/0/1");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addEdge(g, gvnf1, vserver1);
+ rules.addTreeEdge(g, vserver1, lint1);
+ rules.addTreeEdge(g, lint1, sriovVf1);
+ rules.addEdge(g, sriovVf1, sriovPf1);
+ rules.addTreeEdge(g, sriovPf1, pint1);
+ rules.addEdge(g, pint1, plink1);
+
+ rules.addEdge(g, gvnf2, vserver2);// false
+ rules.addTreeEdge(g, vserver2, lint2);// false
+ rules.addTreeEdge(g, lint2, sriovVf2);// false
+ rules.addEdge(g, sriovVf2, sriovPf2);// false
+ rules.addTreeEdge(g, sriovPf2, pint2);// false
+ rules.addEdge(g, pint2, plink2);// false
+
+ expectedResult.add(gvnf1);
+ expectedResult.add(vserver1);
+ expectedResult.add(sriovVf1);
+ expectedResult.add(plink1);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "sriov-topology-fromVnf";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "generic-vnf").has("vnf-id", "gvnf1").has("vnf-name", "genvnfname1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyDetailFromVnfQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyDetailFromVnfQueryTest.java
index c553d05..e9c5d28 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyDetailFromVnfQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyDetailFromVnfQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,138 +26,182 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class TopologyDetailFromVnfQueryTest extends QueryTest {
- public TopologyDetailFromVnfQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf", "vnf-id", "vnfuuid", "vnf-name", "vnf-name-1", "service-id", "service-id-1");
- Vertex gnvf2 = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-2", "vnf-name", "vnf-name-2", "service-id", "service-id-wrong");
-
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1", "vserver-selflink", "vserver-selflink-1");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "4", "aai-node-type", "vserver", "vserver-id", "vserver-id-2", "vserver-name", "vserver-name-2", "vserver-selflink", "vserver-selflink-2");
-
- Vertex vnfc1 = graph.addVertex(T.label, "vnfc", T.id, "5", "aai-node-type", "vnfc", "vnfc-name", "vnfc-name-1", "nfc-naming-code", "nfc-naming-code-1");
- Vertex vnfc2 = graph.addVertex(T.label, "vnfc", T.id, "6", "aai-node-type", "vnfc", "vnfc-name", "vnfc-name-2", "nfc-naming-code", "nfc-naming-code-2");
-
- Vertex tenant1 = graph.addVertex(T.label, "tenant-id", T.id, "7", "aai-node-type", "tenant", "tenant-id", "TenantID", "tenant-name", "TenantName");
- Vertex tenant2 = graph.addVertex(T.label, "tenant-id", T.id, "8", "aai-node-type", "tenant", "tenant-id", "TenantID2", "tenant-name", "TenantName2");
-
- Vertex flavor1 = graph.addVertex(T.label, "flavor", T.id, "9", "aai-node-type", "flavor", "flavor-id", "flavor-id-1", "flavor-name", "flavor-name-1", "flavor-selflink", "flavor-selflink-1");
- Vertex image1 = graph.addVertex(T.label, "image", T.id, "10", "aai-node-type", "image", "image-id", "image-id-1", "image-name", "image-name-1", "image-os-distro", "image-os-distro-1", "image-os-version", "image-os-version-1");
-
- Vertex flavor2 = graph.addVertex(T.label, "flavor", T.id, "11", "aai-node-type", "flavor", "flavor-id", "flavor-id-2", "flavor-name", "flavor-name-2", "flavor-selflink", "flavor-selflink-2");
- Vertex image2 = graph.addVertex(T.label, "image", T.id, "12", "aai-node-type", "image", "image-id", "image-id-2", "image-name", "image-name-2", "image-os-distro", "image-os-distro-2", "image-os-version", "image-os-version-2");
-
- Vertex linter1 = graph.addVertex(T.label, "l-interface", T.id, "13", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id-1", "l-interface-name", "l-interface-name1");
- Vertex linter2 = graph.addVertex(T.label, "l-interface", T.id, "14", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id-2", "l-interface-name", "l-interface-name2");
-
- Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "15", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "l3-interface-ipv4-address-1");
- Vertex l3inter1ipv4addresslist2 = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "16", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "l3-interface-ipv4-address-2");
-
- Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "17", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "l3-interface-ipv6-address-1");
- Vertex l3inter1ipv6addresslist2 = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "18", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "l3-interface-ipv6-address-2");
-
- Vertex cloudRegion1 = graph.addVertex(T.label, "cloud-region", T.id, "19", "aai-node-type", "cloud-region", "cloud-owner", "CloudOwner1", "cloud-region-id", "CloudRegionId1");
- Vertex cloudRegion2 = graph.addVertex(T.label, "cloud-region", T.id, "20", "aai-node-type", "cloud-region", "cloud-owner", "CloudOwner2", "cloud-region-id", "CloudRegionId2");
-
- Vertex availibityzone1 = graph.addVertex(T.label, "availability-zone", T.id, "21", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-1", "hypervisor-type", "hypervisortype-1");
-
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "22", "aai-node-type", "pserver", "pserver-id", "PserverID1", "hostname", "PserverHostName1");
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "23", "aai-node-type", "pserver", "pserver-id", "PserverID2", "hostname", "PserverHostName2"); //false
-
- Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "24", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name", "service-instance-name-1");
- Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "25", "aai-node-type", "service-instance", "service-instance-id", "servInstId-2", "service-type", "servType-2", "service-role", "servRole-2");
-
- Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "26", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
- Vertex vfmodule2 = graph.addVertex(T.label, "vf-module", T.id, "27", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-2", "vf-module-name", "vf-module-name2");
-
- Vertex volumegroup1 = graph.addVertex(T.label, "volume-group", T.id, "28", "aai-node-type", "volume-group", "volume-group-id", "volume-group-id-1", "volume-group-name", "volume-group-name1");
- Vertex volumegroup2 = graph.addVertex(T.label, "volume-group", T.id, "29", "aai-node-type", "volume-group", "volume-group-id", "volume-group-id-2", "volume-group-name", "volume-group-name2");
-
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "30", "aai-node-type", "complex");
-
-
- GraphTraversalSource g = graph.traversal();//true
-
- rules.addEdge(g, gnvf1, vserver1);//true
-
- rules.addEdge(g, vserver1, vnfc1);//true
- rules.addEdge(g, vserver2, vnfc1);//true
-
- rules.addTreeEdge(g, vserver1, tenant1);//true
- rules.addTreeEdge(g, tenant1, cloudRegion1);//true
- rules.addTreeEdge(g, cloudRegion1,availibityzone1 );//true
- rules.addEdge(g, vserver1, image1);//true
- rules.addEdge(g, vserver1, flavor1);//true
- rules.addEdge(g, vserver1, pserver1);//true
- rules.addEdge(g, vserver2, image1);
- rules.addEdge(g, vserver2, flavor1);
- rules.addEdge(g, pserver1, complex);//true
-
- rules.addTreeEdge(g, vserver1, linter1);//true
- rules.addTreeEdge(g, linter1, l3inter1ipv4addresslist);//true
- rules.addTreeEdge(g, linter1, l3inter1ipv6addresslist);//true
-
- rules.addEdge(g, gnvf1, serviceinstance1);//true
- rules.addTreeEdge(g, gnvf1, vfmodule1);//true
- rules.addEdge(g, vfmodule1, volumegroup1);
-
- //---------------------------------------------------
-
- //rules.addTreeEdge(g, vserver1, tenant2);//false
- //rules.addTreeEdge(g, vserver2, linter1);//false
- //rules.addEdge(g, vserver1, vnfc2);//false
-
-
-
- expectedResult.add(gnvf1);
- expectedResult.add(vnfc1);
- expectedResult.add(vserver1);
- expectedResult.add(tenant1);
- expectedResult.add(cloudRegion1);
- expectedResult.add(image1);
- expectedResult.add(flavor1);
- expectedResult.add(pserver1);
- expectedResult.add(complex);
-
- expectedResult.add(serviceinstance1);
- expectedResult.add(availibityzone1);
- expectedResult.add(volumegroup1);
- expectedResult.add(linter1);
- expectedResult.add(l3inter1ipv4addresslist);
- expectedResult.add(l3inter1ipv6addresslist);
-
-
- }
-
- @Override
- protected String getQueryName() {
- return "topology-detail-fromVnf";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("vnf-id", "vnfuuid");
-
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- //return;
- params.put("serviceId", "service-id-1");
- }
+ public TopologyDetailFromVnfQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex gnvf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnfuuid", "vnf-name", "vnf-name-1", "service-id", "service-id-1");
+ Vertex gnvf2 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnf-id-2", "vnf-name", "vnf-name-2", "service-id", "service-id-wrong");
+
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1", "vserver-selflink",
+ "vserver-selflink-1");
+ Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "4", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-2", "vserver-name", "vserver-name-2", "vserver-selflink",
+ "vserver-selflink-2");
+
+ Vertex vnfc1 = graph.addVertex(T.label, "vnfc", T.id, "5", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfc-name-1", "nfc-naming-code", "nfc-naming-code-1");
+ Vertex vnfc2 = graph.addVertex(T.label, "vnfc", T.id, "6", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfc-name-2", "nfc-naming-code", "nfc-naming-code-2");
+
+ Vertex tenant1 = graph.addVertex(T.label, "tenant-id", T.id, "7", "aai-node-type", "tenant",
+ "tenant-id", "TenantID", "tenant-name", "TenantName");
+ Vertex tenant2 = graph.addVertex(T.label, "tenant-id", T.id, "8", "aai-node-type", "tenant",
+ "tenant-id", "TenantID2", "tenant-name", "TenantName2");
+
+ Vertex flavor1 = graph.addVertex(T.label, "flavor", T.id, "9", "aai-node-type", "flavor",
+ "flavor-id", "flavor-id-1", "flavor-name", "flavor-name-1", "flavor-selflink",
+ "flavor-selflink-1");
+ Vertex image1 = graph.addVertex(T.label, "image", T.id, "10", "aai-node-type", "image",
+ "image-id", "image-id-1", "image-name", "image-name-1", "image-os-distro",
+ "image-os-distro-1", "image-os-version", "image-os-version-1");
+
+ Vertex flavor2 = graph.addVertex(T.label, "flavor", T.id, "11", "aai-node-type", "flavor",
+ "flavor-id", "flavor-id-2", "flavor-name", "flavor-name-2", "flavor-selflink",
+ "flavor-selflink-2");
+ Vertex image2 = graph.addVertex(T.label, "image", T.id, "12", "aai-node-type", "image",
+ "image-id", "image-id-2", "image-name", "image-name-2", "image-os-distro",
+ "image-os-distro-2", "image-os-version", "image-os-version-2");
+
+ Vertex linter1 =
+ graph.addVertex(T.label, "l-interface", T.id, "13", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id-1", "l-interface-name", "l-interface-name1");
+ Vertex linter2 =
+ graph.addVertex(T.label, "l-interface", T.id, "14", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id-2", "l-interface-name", "l-interface-name2");
+
+ Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "15", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-1");
+ Vertex l3inter1ipv4addresslist2 = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "16", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-2");
+
+ Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "17", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-1");
+ Vertex l3inter1ipv6addresslist2 = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "18", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-2");
+
+ Vertex cloudRegion1 = graph.addVertex(T.label, "cloud-region", T.id, "19", "aai-node-type",
+ "cloud-region", "cloud-owner", "CloudOwner1", "cloud-region-id", "CloudRegionId1");
+ Vertex cloudRegion2 = graph.addVertex(T.label, "cloud-region", T.id, "20", "aai-node-type",
+ "cloud-region", "cloud-owner", "CloudOwner2", "cloud-region-id", "CloudRegionId2");
+
+ Vertex availibityzone1 = graph.addVertex(T.label, "availability-zone", T.id, "21",
+ "aai-node-type", "availability-zone", "availability-zone-name", "az-name-1",
+ "hypervisor-type", "hypervisortype-1");
+
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "22", "aai-node-type",
+ "pserver", "pserver-id", "PserverID1", "hostname", "PserverHostName1");
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "23", "aai-node-type",
+ "pserver", "pserver-id", "PserverID2", "hostname", "PserverHostName2"); // false
+
+ Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "24",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
+ Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "25",
+ "aai-node-type", "service-instance", "service-instance-id", "servInstId-2",
+ "service-type", "servType-2", "service-role", "servRole-2");
+
+ Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "26", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
+ Vertex vfmodule2 = graph.addVertex(T.label, "vf-module", T.id, "27", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-2", "vf-module-name", "vf-module-name2");
+
+ Vertex volumegroup1 =
+ graph.addVertex(T.label, "volume-group", T.id, "28", "aai-node-type", "volume-group",
+ "volume-group-id", "volume-group-id-1", "volume-group-name", "volume-group-name1");
+ Vertex volumegroup2 =
+ graph.addVertex(T.label, "volume-group", T.id, "29", "aai-node-type", "volume-group",
+ "volume-group-id", "volume-group-id-2", "volume-group-name", "volume-group-name2");
+
+ Vertex complex =
+ graph.addVertex(T.label, "complex", T.id, "30", "aai-node-type", "complex");
+
+ GraphTraversalSource g = graph.traversal();// true
+
+ rules.addEdge(g, gnvf1, vserver1);// true
+
+ rules.addEdge(g, vserver1, vnfc1);// true
+ rules.addEdge(g, vserver2, vnfc1);// true
+
+ rules.addTreeEdge(g, vserver1, tenant1);// true
+ rules.addTreeEdge(g, tenant1, cloudRegion1);// true
+ rules.addTreeEdge(g, cloudRegion1, availibityzone1);// true
+ rules.addEdge(g, vserver1, image1);// true
+ rules.addEdge(g, vserver1, flavor1);// true
+ rules.addEdge(g, vserver1, pserver1);// true
+ rules.addEdge(g, vserver2, image1);
+ rules.addEdge(g, vserver2, flavor1);
+ rules.addEdge(g, pserver1, complex);// true
+
+ rules.addTreeEdge(g, vserver1, linter1);// true
+ rules.addTreeEdge(g, linter1, l3inter1ipv4addresslist);// true
+ rules.addTreeEdge(g, linter1, l3inter1ipv6addresslist);// true
+
+ rules.addEdge(g, gnvf1, serviceinstance1);// true
+ rules.addTreeEdge(g, gnvf1, vfmodule1);// true
+ rules.addEdge(g, vfmodule1, volumegroup1);
+
+ // ---------------------------------------------------
+
+ // rules.addTreeEdge(g, vserver1, tenant2);//false
+ // rules.addTreeEdge(g, vserver2, linter1);//false
+ // rules.addEdge(g, vserver1, vnfc2);//false
+
+ expectedResult.add(gnvf1);
+ expectedResult.add(vnfc1);
+ expectedResult.add(vserver1);
+ expectedResult.add(tenant1);
+ expectedResult.add(cloudRegion1);
+ expectedResult.add(image1);
+ expectedResult.add(flavor1);
+ expectedResult.add(pserver1);
+ expectedResult.add(complex);
+
+ expectedResult.add(serviceinstance1);
+ expectedResult.add(availibityzone1);
+ expectedResult.add(volumegroup1);
+ expectedResult.add(linter1);
+ expectedResult.add(l3inter1ipv4addresslist);
+ expectedResult.add(l3inter1ipv6addresslist);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "topology-detail-fromVnf";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("vnf-id", "vnfuuid");
+
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ // return;
+ params.put("serviceId", "service-id-1");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyDetailFromVserverQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyDetailFromVserverQueryTest.java
index d9821d0..f6c0b7d 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyDetailFromVserverQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyDetailFromVserverQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,124 +26,158 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class TopologyDetailFromVserverQueryTest extends QueryTest {
- public TopologyDetailFromVserverQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //set up test graph
- Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf", "vnf-id", "vnfid0", "nf-type", "sample-nf-type");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type", "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "2", "aai-node-type", "tenant", "tenant-id", "tenantid0", "tenant-name", "tenantName0");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserverid0");
- Vertex linterface = graph.addVertex(T.label, "l-interface", T.id, "4", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0");
- Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "5", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "l3-interface-ipv4-address-0");
- Vertex subnet4 = graph.addVertex(T.label, "subnet", T.id, "6", "aai-node-type", "subnet", "subnet-id", "subnet4-id-0");
- Vertex l3network4 = graph.addVertex(T.label, "l3-network", T.id, "7", "aai-node-type", "l3-network", "network-id", "network4-id-0", "network-name", "network4-name0");
- Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "8", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "l3-interface-ipv6-address-0");
- Vertex subnet6 = graph.addVertex(T.label, "subnet", T.id, "9", "aai-node-type", "subnet", "subnet-id", "subnet6-id-0");
- Vertex l3network6 = graph.addVertex(T.label, "l3-network", T.id, "10", "aai-node-type", "l3-network", "network-id", "network6-id-0", "network-name", "network6-name0");
- Vertex platform = graph.addVertex(T.label, "platform", T.id, "11", "aai-node-type", "platform", "platform-name", "platform0");
- Vertex lineofbusiness = graph.addVertex(T.label, "line-of-business", T.id, "12", "aai-node-type", "line-of-business", "line-of-business-name", "business0");
- Vertex servinst = graph.addVertex(T.label, "service-instance", T.id, "13", "aai-node-type", "service-instance", "service-instance-id", "servInstId0", "service-type", "servType0");
- Vertex owningentity = graph.addVertex(T.label, "owning-entity", T.id, "14", "aai-node-type", "owning-entity", "owning-entity-id", "entityId0", "owning-entity-name", "entityName0");
- Vertex project = graph.addVertex(T.label, "project", T.id, "15", "aai-node-type", "project", "project-name", "project0");
- Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "16", "aai-node-type", "vnfc", "vnfc-name", "vnfc0", "nfc-naming-code", "namingCode0", "nfc-function", "function0");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "17", "aai-node-type", "pserver", "hostname", "pservername1");
- Vertex complex = graph.addVertex(T.label, "pserver", T.id, "18", "aai-node-type", "complex", "physical-location-id", "locationId", "physical-location-type", "locationType", "physical-location-id", "locationId",
- "city", "cityName", "state", "stateName", "postal-code", "zip", "country", "countryName");
- Vertex availabilityZone = graph.addVertex(T.label, "availability-zone", T.id, "19", "aai-node-type", "availability-zone", "availability-zone-name", "azName0", "hypervisor-type", "ht0");
- Vertex virtualDataCenter = graph.addVertex(T.label, "virtual-data-center", T.id, "20", "aai-node-type", "virtual-data-center", "vdc-id", "vdcId0", "vdc-name", "vdcName0");
- Vertex volumeGroup = graph.addVertex(T.label, "volume-group", T.id, "21", "aai-node-type", "volume-group", "volume-group-id", "vgId0", "volume-group-name", "vgName0", "vnf-type", "vnfType0");
- Vertex image = graph.addVertex(T.label, "image", T.id, "22", "aai-node-type", "image", "image-id", "imageId0", "image-name", "imageName0", "image-os-distro", "imageOsDistro0", "image-os-version", "imageOsVersion0", "image-selflink", "imageSl0");
- Vertex flavor = graph.addVertex(T.label, "flavor", T.id, "23", "aai-node-type", "flavor", "flavor-id", "flavorId0", "flavor-name", "flavorName0", "flavor-selflink", "flavorSl0");
- Vertex vfModule = graph.addVertex(T.label, "vf-module", T.id, "24", "aai-node-type", "vf-module", "vf-module-id", "vfmId0", "is-base-vf-module", "true");
- Vertex genericvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "25", "aai-node-type", "generic-vnf", "vnf-id", "vnfid1", "nf-type", "sample-nf-type");
- Vertex vfModule2 = graph.addVertex(T.label, "vf-module", T.id, "26", "aai-node-type", "vf-module", "vf-module-id", "vfmId1", "is-base-vf-module", "true");
+ public TopologyDetailFromVserverQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // set up test graph
+ Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid0", "nf-type", "sample-nf-type");
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "2", "aai-node-type", "tenant",
+ "tenant-id", "tenantid0", "tenant-name", "tenantName0");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver",
+ "vserver-id", "vserverid0");
+ Vertex linterface =
+ graph.addVertex(T.label, "l-interface", T.id, "4", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0");
+ Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "5", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-0");
+ Vertex subnet4 = graph.addVertex(T.label, "subnet", T.id, "6", "aai-node-type", "subnet",
+ "subnet-id", "subnet4-id-0");
+ Vertex l3network4 = graph.addVertex(T.label, "l3-network", T.id, "7", "aai-node-type",
+ "l3-network", "network-id", "network4-id-0", "network-name", "network4-name0");
+ Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "8", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-0");
+ Vertex subnet6 = graph.addVertex(T.label, "subnet", T.id, "9", "aai-node-type", "subnet",
+ "subnet-id", "subnet6-id-0");
+ Vertex l3network6 = graph.addVertex(T.label, "l3-network", T.id, "10", "aai-node-type",
+ "l3-network", "network-id", "network6-id-0", "network-name", "network6-name0");
+ Vertex platform = graph.addVertex(T.label, "platform", T.id, "11", "aai-node-type",
+ "platform", "platform-name", "platform0");
+ Vertex lineofbusiness = graph.addVertex(T.label, "line-of-business", T.id, "12",
+ "aai-node-type", "line-of-business", "line-of-business-name", "business0");
+ Vertex servinst = graph.addVertex(T.label, "service-instance", T.id, "13", "aai-node-type",
+ "service-instance", "service-instance-id", "servInstId0", "service-type", "servType0");
+ Vertex owningentity = graph.addVertex(T.label, "owning-entity", T.id, "14", "aai-node-type",
+ "owning-entity", "owning-entity-id", "entityId0", "owning-entity-name", "entityName0");
+ Vertex project = graph.addVertex(T.label, "project", T.id, "15", "aai-node-type", "project",
+ "project-name", "project0");
+ Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "16", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfc0", "nfc-naming-code", "namingCode0", "nfc-function", "function0");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "17", "aai-node-type", "pserver",
+ "hostname", "pservername1");
+ Vertex complex = graph.addVertex(T.label, "pserver", T.id, "18", "aai-node-type", "complex",
+ "physical-location-id", "locationId", "physical-location-type", "locationType",
+ "physical-location-id", "locationId", "city", "cityName", "state", "stateName",
+ "postal-code", "zip", "country", "countryName");
+ Vertex availabilityZone =
+ graph.addVertex(T.label, "availability-zone", T.id, "19", "aai-node-type",
+ "availability-zone", "availability-zone-name", "azName0", "hypervisor-type", "ht0");
+ Vertex virtualDataCenter = graph.addVertex(T.label, "virtual-data-center", T.id, "20",
+ "aai-node-type", "virtual-data-center", "vdc-id", "vdcId0", "vdc-name", "vdcName0");
+ Vertex volumeGroup =
+ graph.addVertex(T.label, "volume-group", T.id, "21", "aai-node-type", "volume-group",
+ "volume-group-id", "vgId0", "volume-group-name", "vgName0", "vnf-type", "vnfType0");
+ Vertex image = graph.addVertex(T.label, "image", T.id, "22", "aai-node-type", "image",
+ "image-id", "imageId0", "image-name", "imageName0", "image-os-distro", "imageOsDistro0",
+ "image-os-version", "imageOsVersion0", "image-selflink", "imageSl0");
+ Vertex flavor = graph.addVertex(T.label, "flavor", T.id, "23", "aai-node-type", "flavor",
+ "flavor-id", "flavorId0", "flavor-name", "flavorName0", "flavor-selflink", "flavorSl0");
+ Vertex vfModule = graph.addVertex(T.label, "vf-module", T.id, "24", "aai-node-type",
+ "vf-module", "vf-module-id", "vfmId0", "is-base-vf-module", "true");
+ Vertex genericvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "25", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid1", "nf-type", "sample-nf-type");
+ Vertex vfModule2 = graph.addVertex(T.label, "vf-module", T.id, "26", "aai-node-type",
+ "vf-module", "vf-module-id", "vfmId1", "is-base-vf-module", "true");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addTreeEdge(g, tenant, cloudregion);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addEdge(g, pserver, vserver);
+ rules.addEdge(g, complex, pserver);
+ rules.addEdge(g, availabilityZone, pserver);
+ rules.addEdge(g, genericvnf, vserver);
+ rules.addTreeEdge(g, genericvnf, vfModule); // related to the genericvnf only, not the
+ // vserver
+ rules.addEdge(g, genericvnf, platform);
+ rules.addEdge(g, genericvnf, lineofbusiness);
+ rules.addEdge(g, genericvnf, vnfc);
+ rules.addEdge(g, genericvnf, servinst);
+ rules.addEdge(g, virtualDataCenter, genericvnf);
+ rules.addEdge(g, volumeGroup, genericvnf);
+ rules.addEdge(g, owningentity, servinst);
+ rules.addEdge(g, project, servinst);
+ rules.addTreeEdge(g, linterface, vserver);
+ rules.addTreeEdge(g, l3inter1ipv4addresslist, linterface);
+ rules.addEdge(g, l3inter1ipv4addresslist, subnet4);
+ rules.addTreeEdge(g, l3network4, subnet4);
+ rules.addTreeEdge(g, l3inter1ipv6addresslist, linterface);
+ rules.addEdge(g, l3inter1ipv6addresslist, subnet6);
+ rules.addTreeEdge(g, l3network6, subnet6);
+ rules.addEdge(g, image, vserver);
+ rules.addEdge(g, flavor, vserver);
+ rules.addTreeEdge(g, genericvnf2, vfModule2);
+ rules.addEdge(g, vserver, vfModule2);
+
+ expectedResult.add(vserver);
+ expectedResult.add(linterface);
+ expectedResult.add(l3inter1ipv4addresslist);
+ expectedResult.add(subnet4);
+ expectedResult.add(l3network4);
+ expectedResult.add(l3inter1ipv6addresslist);
+ expectedResult.add(subnet6);
+ expectedResult.add(l3network6);
+ expectedResult.add(tenant);
+ expectedResult.add(cloudregion);
+ expectedResult.add(pserver);
+ expectedResult.add(complex);
+ expectedResult.add(availabilityZone);
+ expectedResult.add(genericvnf);
+ expectedResult.add(vfModule); // related to the genericvnf only, not the vserver
+ expectedResult.add(platform);
+ expectedResult.add(lineofbusiness);
+ expectedResult.add(virtualDataCenter);
+ expectedResult.add(volumeGroup);
+ expectedResult.add(owningentity);
+ expectedResult.add(project);
+ expectedResult.add(vnfc);
+ expectedResult.add(image);
+ expectedResult.add(flavor);
+ expectedResult.add(vfModule2); // related to the vserver
+ }
- GraphTraversalSource g = graph.traversal();
-
- rules.addTreeEdge(g, tenant, cloudregion);
- rules.addTreeEdge(g, vserver, tenant);
- rules.addEdge(g, pserver, vserver);
- rules.addEdge(g, complex, pserver);
- rules.addEdge(g, availabilityZone, pserver);
- rules.addEdge(g, genericvnf, vserver);
- rules.addTreeEdge(g, genericvnf, vfModule); // related to the genericvnf only, not the vserver
- rules.addEdge(g, genericvnf, platform);
- rules.addEdge(g, genericvnf, lineofbusiness);
- rules.addEdge(g, genericvnf, vnfc);
- rules.addEdge(g, genericvnf, servinst);
- rules.addEdge(g, virtualDataCenter, genericvnf);
- rules.addEdge(g, volumeGroup, genericvnf);
- rules.addEdge(g, owningentity, servinst);
- rules.addEdge(g, project, servinst);
- rules.addTreeEdge(g, linterface, vserver);
- rules.addTreeEdge(g, l3inter1ipv4addresslist, linterface);
- rules.addEdge(g, l3inter1ipv4addresslist, subnet4);
- rules.addTreeEdge(g, l3network4, subnet4);
- rules.addTreeEdge(g, l3inter1ipv6addresslist, linterface);
- rules.addEdge(g, l3inter1ipv6addresslist, subnet6);
- rules.addTreeEdge(g, l3network6, subnet6);
- rules.addEdge(g, image, vserver);
- rules.addEdge(g, flavor, vserver);
- rules.addTreeEdge(g, genericvnf2, vfModule2);
- rules.addEdge(g, vserver, vfModule2);
+ @Override
+ protected String getQueryName() {
+ return "topology-detail-fromVserver";
+ }
- expectedResult.add(vserver);
- expectedResult.add(linterface);
- expectedResult.add(l3inter1ipv4addresslist);
- expectedResult.add(subnet4);
- expectedResult.add(l3network4);
- expectedResult.add(l3inter1ipv6addresslist);
- expectedResult.add(subnet6);
- expectedResult.add(l3network6);
- expectedResult.add(tenant);
- expectedResult.add(cloudregion);
- expectedResult.add(pserver);
- expectedResult.add(complex);
- expectedResult.add(availabilityZone);
- expectedResult.add(genericvnf);
- expectedResult.add(vfModule); // related to the genericvnf only, not the vserver
- expectedResult.add(platform);
- expectedResult.add(lineofbusiness);
- expectedResult.add(virtualDataCenter);
- expectedResult.add(volumeGroup);
- expectedResult.add(owningentity);
- expectedResult.add(project);
- expectedResult.add(vnfc);
- expectedResult.add(image);
- expectedResult.add(flavor);
- expectedResult.add(vfModule2); // related to the vserver
- }
- @Override
- protected String getQueryName() {
- return "topology-detail-fromVserver";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "cloud-region")
- .has("cloud-region-id", "regionid0")
- .has("cloud-owner", "cloudOwnername0")
- .in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type","tenant")
- .has("tenant-id", "tenantid0")
- .in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type","vserver")
- .has("vserver-id", "vserverid0");
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "cloud-region").has("cloud-region-id", "regionid0")
+ .has("cloud-owner", "cloudOwnername0").in("org.onap.relationships.inventory.BelongsTo")
+ .has("aai-node-type", "tenant").has("tenant-id", "tenantid0")
+ .in("org.onap.relationships.inventory.BelongsTo").has("aai-node-type", "vserver")
+ .has("vserver-id", "vserverid0");
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
-} \ No newline at end of file
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyDetailsQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyDetailsQueryTest.java
index 36911a8..c8e7dec 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyDetailsQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyDetailsQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,137 +30,182 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class TopologyDetailsQueryTest extends QueryTest {
- public TopologyDetailsQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //set up test graph
- Vertex genericvnf = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf", "vnf-id", "vnfid0","vnf-name", "vnf-name-1", "nf-type", "sample-nf-type");
- Vertex platform = graph.addVertex(T.label, "platform", T.id, "1", "aai-node-type", "platform", "platform-name", "platform0");
- Vertex lineofbusiness = graph.addVertex(T.label, "line-of-business", T.id, "2", "aai-node-type", "line-of-business", "line-of-business-name", "business0");
- Vertex servinst = graph.addVertex(T.label, "service-instance", T.id, "3", "aai-node-type", "service-instance", "service-instance-id", "servInstId0", "service-type", "servType0");
- Vertex owningentity = graph.addVertex(T.label, "owning-entity", T.id, "4", "aai-node-type", "owning-entity", "owning-entity-id", "entityId0", "owning-entity-name", "entityName0");
- Vertex project = graph.addVertex(T.label, "project", T.id, "5", "aai-node-type", "project", "project-name", "project0");
- Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "6", "aai-node-type", "vnfc", "vnfc-name", "vnfc0", "nfc-naming-code", "namingCode0", "nfc-function", "function0");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver", "vserver-id", "vserverid0");
- Vertex linterface = graph.addVertex(T.label, "l-interface", T.id, "8", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0");
- Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "9", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "l3-interface-ipv4-address-0");
- Vertex subnet4 = graph.addVertex(T.label, "subnet", T.id, "10", "aai-node-type", "subnet", "subnet-id", "subnet4-id-0");
- Vertex l3network4 = graph.addVertex(T.label, "l3-network", T.id, "11", "aai-node-type", "l3-network", "network-id", "network4-id-0", "network-name", "network4-name0");
- Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "12", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "l3-interface-ipv6-address-0");
- Vertex subnet6 = graph.addVertex(T.label, "subnet", T.id, "13", "aai-node-type", "subnet", "subnet-id", "subnet6-id-0");
- Vertex l3network6 = graph.addVertex(T.label, "l3-network", T.id, "14", "aai-node-type", "l3-network", "network-id", "network6-id-0", "network-name", "network6-name0");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "15", "aai-node-type", "tenant", "tenant-id", "tenantid0", "tenant-name", "tenantName0");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "16", "aai-node-type", "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "17", "aai-node-type", "pserver", "hostname", "pservername1");
- Vertex complex = graph.addVertex(T.label, "pserver", T.id, "18", "aai-node-type", "complex", "physical-location-id", "locationId", "physical-location-type", "locationType", "physical-location-id", "locationId",
- "city", "cityName", "state", "stateName", "postal-code", "zip", "country", "countryName");
-
-
-
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "20", "aai-node-type", "generic-vnf", "vnf-id", "vnfid1","vnf-name", "vnf-name-2", "nf-type", "sample-nf-type1");
- Vertex platform1 = graph.addVertex(T.label, "platform", T.id, "21", "aai-node-type", "platform", "platform-name", "platform1");
- Vertex lineofbusiness1 = graph.addVertex(T.label, "line-of-business", T.id, "22", "aai-node-type", "line-of-business", "line-of-business-name", "business1");
- Vertex servinst1 = graph.addVertex(T.label, "service-instance", T.id, "23", "aai-node-type", "service-instance", "service-instance-id", "servInstId1", "service-type", "servType1");
- Vertex owningentity1 = graph.addVertex(T.label, "owning-entity", T.id, "24", "aai-node-type", "owning-entity", "owning-entity-id", "entityId1", "owning-entity-name", "entityName1");
- Vertex project1 = graph.addVertex(T.label, "project", T.id, "25", "aai-node-type", "project", "project-name", "project1");
- Vertex vnfc1 = graph.addVertex(T.label, "vnfc", T.id, "26", "aai-node-type", "vnfc", "vnfc-name", "vnfc1", "nfc-naming-code", "namingCode1", "nfc-function", "function1");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "27", "aai-node-type", "vserver", "vserver-id", "vserverid1");
- Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "28", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id1", "l-interface-name", "l-interface-name1");
- Vertex l3inter1ipv4addresslist1 = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "29", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "l3-interface-ipv4-address-1");
- Vertex subnet41 = graph.addVertex(T.label, "subnet", T.id, "30", "aai-node-type", "subnet", "subnet-id", "subnet4-id-1");
- Vertex l3network41 = graph.addVertex(T.label, "l3-network", T.id, "31", "aai-node-type", "l3-network", "network-id", "network4-id-1", "network-name", "network4-name1");
- Vertex l3inter1ipv6addresslist1 = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "32", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "l3-interface-ipv6-address-1");
- Vertex subnet61 = graph.addVertex(T.label, "subnet", T.id, "33", "aai-node-type", "subnet", "subnet-id", "subnet6-id-1");
- Vertex l3network61 = graph.addVertex(T.label, "l3-network", T.id, "34", "aai-node-type", "l3-network", "network-id", "network6-id-1", "network-name", "network6-name1");
- Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "35", "aai-node-type", "tenant", "tenant-id", "tenantid0", "tenant-name", "tenantName1");
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "36", "aai-node-type", "cloud-region", "cloud-region-id", "regionid1", "cloud-owner", "cloudOwnername1");
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "37", "aai-node-type", "pserver", "hostname", "pservername2");
- Vertex complex1 = graph.addVertex(T.label, "pserver", T.id, "38", "aai-node-type", "complex", "physical-location-id", "locationId1", "physical-location-type", "locationType1", "physical-location-id", "locationId1",
- "city", "cityName1", "state", "stateName1", "postal-code", "zip1", "country", "countryName1");
-
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addEdge(g, genericvnf, platform);
- rules.addEdge(g, genericvnf, lineofbusiness);
- rules.addEdge(g, genericvnf, servinst);
- rules.addEdge(g, owningentity, servinst);
- rules.addEdge(g, project, servinst);
- rules.addEdge(g, genericvnf, vnfc);
- rules.addEdge(g, genericvnf,vserver);
- rules.addTreeEdge(g, linterface, vserver);
- rules.addTreeEdge(g, l3inter1ipv4addresslist, linterface);
- rules.addEdge(g, l3inter1ipv4addresslist, subnet4);
- rules.addTreeEdge(g, l3network4, subnet4);
- rules.addTreeEdge(g, l3inter1ipv6addresslist, linterface);
- rules.addEdge(g, l3inter1ipv6addresslist, subnet6);
- rules.addTreeEdge(g, l3network6, subnet6);
- rules.addTreeEdge(g, vserver, tenant);
- rules.addTreeEdge(g, tenant, cloudregion);
- rules.addEdge(g, pserver, vserver);
- rules.addEdge(g, complex, pserver);
-
-
- //false
- rules.addEdge(g, genericvnf1, platform1);
- rules.addEdge(g, genericvnf1, lineofbusiness1);
- rules.addEdge(g, genericvnf1, servinst1);
- rules.addEdge(g, owningentity1, servinst1);
- rules.addEdge(g, project1, servinst1);
- rules.addEdge(g, genericvnf1, vnfc1);
- rules.addEdge(g, genericvnf1,vserver1);
- rules.addTreeEdge(g, linterface1, vserver1);
- rules.addTreeEdge(g, l3inter1ipv4addresslist1, linterface1);
- rules.addEdge(g, l3inter1ipv4addresslist1, subnet41);
- rules.addTreeEdge(g, l3network41, subnet41);
- rules.addTreeEdge(g, l3inter1ipv6addresslist1, linterface1);
- rules.addEdge(g, l3inter1ipv6addresslist1, subnet61);
- rules.addTreeEdge(g, l3network61, subnet61);
- rules.addTreeEdge(g, vserver1, tenant1);
- rules.addTreeEdge(g, tenant1, cloudregion1);
- rules.addEdge(g, pserver1, vserver1);
- rules.addEdge(g, complex1, pserver1);
-
-
-
-
- expectedResult.add(genericvnf);
- expectedResult.add(platform);
- expectedResult.add(lineofbusiness);
- expectedResult.add(owningentity);
- expectedResult.add(project);
- expectedResult.add(vnfc);
- expectedResult.add(vserver);
- expectedResult.add(linterface);
- expectedResult.add(l3inter1ipv4addresslist);
- expectedResult.add(subnet4);
- expectedResult.add(l3network4);
- expectedResult.add(l3inter1ipv6addresslist);
- expectedResult.add(subnet6);
- expectedResult.add(l3network6);
- expectedResult.add(cloudregion);
- expectedResult.add(complex);
-
-
-
- }
- @Override
- protected String getQueryName() {
- return "topology-detail";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "generic-vnf").has("vnf-name", "vnf-name-1").has("vnf-id", "vnfid0");
-
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ public TopologyDetailsQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // set up test graph
+ Vertex genericvnf =
+ graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnfid0", "vnf-name", "vnf-name-1", "nf-type", "sample-nf-type");
+ Vertex platform = graph.addVertex(T.label, "platform", T.id, "1", "aai-node-type",
+ "platform", "platform-name", "platform0");
+ Vertex lineofbusiness = graph.addVertex(T.label, "line-of-business", T.id, "2",
+ "aai-node-type", "line-of-business", "line-of-business-name", "business0");
+ Vertex servinst = graph.addVertex(T.label, "service-instance", T.id, "3", "aai-node-type",
+ "service-instance", "service-instance-id", "servInstId0", "service-type", "servType0");
+ Vertex owningentity = graph.addVertex(T.label, "owning-entity", T.id, "4", "aai-node-type",
+ "owning-entity", "owning-entity-id", "entityId0", "owning-entity-name", "entityName0");
+ Vertex project = graph.addVertex(T.label, "project", T.id, "5", "aai-node-type", "project",
+ "project-name", "project0");
+ Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "6", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfc0", "nfc-naming-code", "namingCode0", "nfc-function", "function0");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver",
+ "vserver-id", "vserverid0");
+ Vertex linterface =
+ graph.addVertex(T.label, "l-interface", T.id, "8", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0");
+ Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "9", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-0");
+ Vertex subnet4 = graph.addVertex(T.label, "subnet", T.id, "10", "aai-node-type", "subnet",
+ "subnet-id", "subnet4-id-0");
+ Vertex l3network4 = graph.addVertex(T.label, "l3-network", T.id, "11", "aai-node-type",
+ "l3-network", "network-id", "network4-id-0", "network-name", "network4-name0");
+ Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "12", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-0");
+ Vertex subnet6 = graph.addVertex(T.label, "subnet", T.id, "13", "aai-node-type", "subnet",
+ "subnet-id", "subnet6-id-0");
+ Vertex l3network6 = graph.addVertex(T.label, "l3-network", T.id, "14", "aai-node-type",
+ "l3-network", "network-id", "network6-id-0", "network-name", "network6-name0");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "15", "aai-node-type", "tenant",
+ "tenant-id", "tenantid0", "tenant-name", "tenantName0");
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "16", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionid0", "cloud-owner", "cloudOwnername0");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "17", "aai-node-type", "pserver",
+ "hostname", "pservername1");
+ Vertex complex = graph.addVertex(T.label, "pserver", T.id, "18", "aai-node-type", "complex",
+ "physical-location-id", "locationId", "physical-location-type", "locationType",
+ "physical-location-id", "locationId", "city", "cityName", "state", "stateName",
+ "postal-code", "zip", "country", "countryName");
+
+ Vertex genericvnf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "20", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnfid1", "vnf-name", "vnf-name-2", "nf-type", "sample-nf-type1");
+ Vertex platform1 = graph.addVertex(T.label, "platform", T.id, "21", "aai-node-type",
+ "platform", "platform-name", "platform1");
+ Vertex lineofbusiness1 = graph.addVertex(T.label, "line-of-business", T.id, "22",
+ "aai-node-type", "line-of-business", "line-of-business-name", "business1");
+ Vertex servinst1 = graph.addVertex(T.label, "service-instance", T.id, "23", "aai-node-type",
+ "service-instance", "service-instance-id", "servInstId1", "service-type", "servType1");
+ Vertex owningentity1 =
+ graph.addVertex(T.label, "owning-entity", T.id, "24", "aai-node-type", "owning-entity",
+ "owning-entity-id", "entityId1", "owning-entity-name", "entityName1");
+ Vertex project1 = graph.addVertex(T.label, "project", T.id, "25", "aai-node-type",
+ "project", "project-name", "project1");
+ Vertex vnfc1 = graph.addVertex(T.label, "vnfc", T.id, "26", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfc1", "nfc-naming-code", "namingCode1", "nfc-function", "function1");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "27", "aai-node-type",
+ "vserver", "vserver-id", "vserverid1");
+ Vertex linterface1 =
+ graph.addVertex(T.label, "l-interface", T.id, "28", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id1", "l-interface-name", "l-interface-name1");
+ Vertex l3inter1ipv4addresslist1 = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "29", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-1");
+ Vertex subnet41 = graph.addVertex(T.label, "subnet", T.id, "30", "aai-node-type", "subnet",
+ "subnet-id", "subnet4-id-1");
+ Vertex l3network41 = graph.addVertex(T.label, "l3-network", T.id, "31", "aai-node-type",
+ "l3-network", "network-id", "network4-id-1", "network-name", "network4-name1");
+ Vertex l3inter1ipv6addresslist1 = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "32", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-1");
+ Vertex subnet61 = graph.addVertex(T.label, "subnet", T.id, "33", "aai-node-type", "subnet",
+ "subnet-id", "subnet6-id-1");
+ Vertex l3network61 = graph.addVertex(T.label, "l3-network", T.id, "34", "aai-node-type",
+ "l3-network", "network-id", "network6-id-1", "network-name", "network6-name1");
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "35", "aai-node-type", "tenant",
+ "tenant-id", "tenantid0", "tenant-name", "tenantName1");
+ Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "36", "aai-node-type",
+ "cloud-region", "cloud-region-id", "regionid1", "cloud-owner", "cloudOwnername1");
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "37", "aai-node-type",
+ "pserver", "hostname", "pservername2");
+ Vertex complex1 = graph.addVertex(T.label, "pserver", T.id, "38", "aai-node-type",
+ "complex", "physical-location-id", "locationId1", "physical-location-type",
+ "locationType1", "physical-location-id", "locationId1", "city", "cityName1", "state",
+ "stateName1", "postal-code", "zip1", "country", "countryName1");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addEdge(g, genericvnf, platform);
+ rules.addEdge(g, genericvnf, lineofbusiness);
+ rules.addEdge(g, genericvnf, servinst);
+ rules.addEdge(g, owningentity, servinst);
+ rules.addEdge(g, project, servinst);
+ rules.addEdge(g, genericvnf, vnfc);
+ rules.addEdge(g, genericvnf, vserver);
+ rules.addTreeEdge(g, linterface, vserver);
+ rules.addTreeEdge(g, l3inter1ipv4addresslist, linterface);
+ rules.addEdge(g, l3inter1ipv4addresslist, subnet4);
+ rules.addTreeEdge(g, l3network4, subnet4);
+ rules.addTreeEdge(g, l3inter1ipv6addresslist, linterface);
+ rules.addEdge(g, l3inter1ipv6addresslist, subnet6);
+ rules.addTreeEdge(g, l3network6, subnet6);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addTreeEdge(g, tenant, cloudregion);
+ rules.addEdge(g, pserver, vserver);
+ rules.addEdge(g, complex, pserver);
+
+ // false
+ rules.addEdge(g, genericvnf1, platform1);
+ rules.addEdge(g, genericvnf1, lineofbusiness1);
+ rules.addEdge(g, genericvnf1, servinst1);
+ rules.addEdge(g, owningentity1, servinst1);
+ rules.addEdge(g, project1, servinst1);
+ rules.addEdge(g, genericvnf1, vnfc1);
+ rules.addEdge(g, genericvnf1, vserver1);
+ rules.addTreeEdge(g, linterface1, vserver1);
+ rules.addTreeEdge(g, l3inter1ipv4addresslist1, linterface1);
+ rules.addEdge(g, l3inter1ipv4addresslist1, subnet41);
+ rules.addTreeEdge(g, l3network41, subnet41);
+ rules.addTreeEdge(g, l3inter1ipv6addresslist1, linterface1);
+ rules.addEdge(g, l3inter1ipv6addresslist1, subnet61);
+ rules.addTreeEdge(g, l3network61, subnet61);
+ rules.addTreeEdge(g, vserver1, tenant1);
+ rules.addTreeEdge(g, tenant1, cloudregion1);
+ rules.addEdge(g, pserver1, vserver1);
+ rules.addEdge(g, complex1, pserver1);
+
+ expectedResult.add(genericvnf);
+ expectedResult.add(platform);
+ expectedResult.add(lineofbusiness);
+ expectedResult.add(owningentity);
+ expectedResult.add(project);
+ expectedResult.add(vnfc);
+ expectedResult.add(vserver);
+ expectedResult.add(linterface);
+ expectedResult.add(l3inter1ipv4addresslist);
+ expectedResult.add(subnet4);
+ expectedResult.add(l3network4);
+ expectedResult.add(l3inter1ipv6addresslist);
+ expectedResult.add(subnet6);
+ expectedResult.add(l3network6);
+ expectedResult.add(cloudregion);
+ expectedResult.add(complex);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "topology-detail";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "generic-vnf").has("vnf-name", "vnf-name-1").has("vnf-id", "vnfid0");
+
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyFromCloudRegionIdAndServiceIdTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyFromCloudRegionIdAndServiceIdTest.java
index 266077a..250241a 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyFromCloudRegionIdAndServiceIdTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyFromCloudRegionIdAndServiceIdTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,133 +26,188 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class TopologyFromCloudRegionIdAndServiceIdTest extends QueryTest {
- public TopologyFromCloudRegionIdAndServiceIdTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "61", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name", "service-instance-name-1");
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-owner", "cloud-owner-1");
- Vertex availibityzone1 = graph.addVertex(T.label, "cloud-region", T.id, "2", "aai-node-type", "availability-zone", "availability-zone-name", "az-name-1", "hypervisor-type", "hypervisortype-1");
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1", "service-id", "service-id-1");
-
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver", "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1", "vserver-selflink", "vserver-selflink-1");
- Vertex flavor1 = graph.addVertex(T.label, "flavor", T.id, "8", "aai-node-type", "flavor", "flavor-id", "flavor-id-1", "flavor-name", "flavor-name-1", "flavor-selflink", "flavor-selflink-1");
- Vertex image1 = graph.addVertex(T.label, "image", T.id, "9", "aai-node-type", "image", "image-id", "image-id-1", "image-name", "image-name-1", "image-os-distro", "image-os-distro-1", "image-os-version", "image-os-version-1");
- Vertex volume1 = graph.addVertex(T.label, "volume", T.id, "10", "aai-node-type", "volume", "volume-id", "volume-id-1", "volume-selflink", "volume-selflink-1");
- Vertex vnfc1 = graph.addVertex(T.label, "vnfc", T.id, "11", "aai-node-type", "vnfc", "vnfc-name", "vnfc-name-1", "nfc-naming-code", "nfc-naming-code-1");
- Vertex snapshot1 = graph.addVertex(T.label, "snapshot", T.id, "12", "aai-node-type", "snapshot", "snapshot-id", "snapshot-id-1");
- Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "13", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
- Vertex linter1 = graph.addVertex(T.label, "l-interface", T.id, "14", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id-1", "l-interface-name", "l-interface-name1");
- Vertex logicallink1 = graph.addVertex(T.label, "logical-link", T.id, "15", "aai-node-type", "logical-link", "link-name", "link-name-1", "l-interface-name", "l-interface-name1");
- Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "16", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "l3-interface-ipv4-address-1");
- Vertex subnet14 = graph.addVertex(T.label, "subnet", T.id, "17", "aai-node-type", "subnet", "subnet-id", "subnet-id-14");
- Vertex l3network14 = graph.addVertex(T.label, "l3-network", T.id, "18", "aai-node-type", "l3-network", "network-id", "network-id-14", "network-name", "network-name-14");
- Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "19", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "l3-interface-ipv6-address-1");
- Vertex subnet16 = graph.addVertex(T.label, "subnet", T.id, "20", "aai-node-type", "subnet", "subnet-id", "subnet-id-16");
- Vertex l3network16 = graph.addVertex(T.label, "l3-network", T.id, "21", "aai-node-type", "l3-network", "network-id", "network-id-16", "network-name", "network-name16");
-
- Vertex gnvf2 = graph.addVertex(T.label, "generic-vnf", T.id, "33", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-2", "vnf-name", "vnf-name-2", "service-id", "service-id-wrong");
- Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "36", "aai-node-type", "service-instance", "service-instance-id", "servInstId-2", "service-type", "servType-2", "service-role", "servRole-2");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "37", "aai-node-type", "vserver", "vserver-id", "vserver-id-2", "vserver-name", "vserver-name-2", "vserver-selflink", "vserver-selflink-2");
- Vertex flavor2 = graph.addVertex(T.label, "flavor", T.id, "38", "aai-node-type", "flavor", "flavor-id", "flavor-id-2", "flavor-name", "flavor-name-2", "flavor-selflink", "flavor-selflink-2");
- Vertex image2 = graph.addVertex(T.label, "image", T.id, "39", "aai-node-type", "image", "image-id", "image-id-2", "image-name", "image-name-2", "image-os-distro", "image-os-distro-2", "image-os-version", "image-os-version-2");
- Vertex volume2 = graph.addVertex(T.label, "volume", T.id, "40", "aai-node-type", "volume", "volume-id", "volume-id-2", "volume-selflink", "volume-selflink-2");
- Vertex vnfc2 = graph.addVertex(T.label, "vnfc", T.id, "41", "aai-node-type", "vnfc", "vnfc-name", "vnfc-name-2", "nfc-naming-code", "nfc-naming-code-2");
- Vertex snapshot2 = graph.addVertex(T.label, "snapshot", T.id, "42", "aai-node-type", "snapshot", "snapshot-id", "snapshot-id-2");
- Vertex vfmodule2 = graph.addVertex(T.label, "vf-module", T.id, "43", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-2", "vf-module-name", "vf-module-name2");
- Vertex linter2 = graph.addVertex(T.label, "l-interface", T.id, "44", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id-2", "l-interface-name", "l-interface-name2");
- Vertex logicallink2 = graph.addVertex(T.label, "logical-link", T.id, "45", "aai-node-type", "logical-link", "link-name", "link-name-2", "l-interface-name", "l-interface-name2");
- Vertex l3inter1ipv4addresslist2 = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "46", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "l3-interface-ipv4-address-2");
- Vertex subnet24 = graph.addVertex(T.label, "subnet", T.id, "47", "aai-node-type", "subnet", "subnet-id", "subnet-id-24");
- Vertex l3network24 = graph.addVertex(T.label, "l3-network", T.id, "48", "aai-node-type", "l3-network", "network-id", "network-id-24", "network-name", "network-name-24");
- Vertex l3inter1ipv6addresslist2 = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "49", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "l3-interface-ipv6-address-2");
- Vertex subnet26 = graph.addVertex(T.label, "subnet", T.id, "50", "aai-node-type", "subnet", "subnet-id", "subnet-id-26");
- Vertex l3network26 = graph.addVertex(T.label, "l3-network", T.id, "51", "aai-node-type", "l3-network", "network-id", "network-id-26", "network-name", "network-name26");
-
- GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, cloudregion1, availibityzone1);//true
- rules.addEdge(g, availibityzone1, gnvf1);//true
- rules.addEdge(g, gnvf1, serviceinstance1);//true
- rules.addEdge(g, gnvf1, vserver1);//true
-
- rules.addEdge(g, vserver1, flavor1);//true
- rules.addEdge(g, vserver1, image1);//true
- rules.addTreeEdge(g, vserver1, volume1);//true
- rules.addEdge(g, vserver1, vnfc1);//true
- rules.addEdge(g, vserver1, snapshot1);//true
- rules.addEdge(g, vserver1, vfmodule1);//true
- rules.addEdge(g, linter1, logicallink1);//true
- rules.addTreeEdge(g, vserver1, linter1);//true
- rules.addTreeEdge(g, linter1, l3inter1ipv4addresslist);//true
- rules.addTreeEdge(g, linter1, l3inter1ipv6addresslist);//true
- rules.addEdge(g, l3inter1ipv4addresslist, subnet14);//true
- rules.addTreeEdge(g, subnet14, l3network14);//true
- rules.addEdge(g, l3inter1ipv6addresslist, subnet16);//true
- rules.addTreeEdge(g, subnet16, l3network16);//true
-
- // false
- rules.addEdge(g, availibityzone1, gnvf2);
- rules.addEdge(g, gnvf2, serviceinstance2);
- rules.addEdge(g, gnvf2, vserver2);
- rules.addEdge(g, vserver2, flavor2);
- rules.addEdge(g, vserver2, image2);
- rules.addTreeEdge(g, vserver2, volume2);
- rules.addEdge(g, vserver2, vnfc2);
- rules.addEdge(g, vserver2, snapshot2);
- rules.addEdge(g, vserver2, vfmodule2);
- rules.addEdge(g, linter2, logicallink2);
- rules.addTreeEdge(g, vserver2, linter2);
- rules.addTreeEdge(g, linter2, l3inter1ipv4addresslist2);
- rules.addTreeEdge(g, linter2, l3inter1ipv6addresslist2);
- rules.addEdge(g, l3inter1ipv4addresslist2, subnet24);
- rules.addTreeEdge(g, subnet24, l3network24);
- rules.addEdge(g, l3inter1ipv6addresslist2, subnet26);
- rules.addTreeEdge(g, subnet26, l3network26);
-
-
- expectedResult.add(serviceinstance1);
- expectedResult.add(vserver1);
- expectedResult.add(flavor1);
- expectedResult.add(image1);
- expectedResult.add(volume1);
- expectedResult.add(vnfc1);
- expectedResult.add(snapshot1);
- expectedResult.add(vfmodule1);
- expectedResult.add(linter1);
- expectedResult.add(logicallink1);
- expectedResult.add(l3inter1ipv4addresslist);
- expectedResult.add(subnet14);
- expectedResult.add(l3network14);
- expectedResult.add(l3inter1ipv6addresslist);
- expectedResult.add(subnet16);
- expectedResult.add(l3network16);
-
- }
-
- @Override
- protected String getQueryName() {
- return "topology-fromCloudRegionIdandServiceId";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type","cloud-region").has("cloud-owner","cloud-owner-1").has("cloud-region-id","cloud-region-id-1");
-
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("serviceId", "service-id-1");
- }
+ public TopologyFromCloudRegionIdAndServiceIdTest()
+ throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "61",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
+ Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-owner", "cloud-owner-1");
+ Vertex availibityzone1 = graph.addVertex(T.label, "cloud-region", T.id, "2",
+ "aai-node-type", "availability-zone", "availability-zone-name", "az-name-1",
+ "hypervisor-type", "hypervisortype-1");
+ Vertex gnvf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1", "service-id", "service-id-1");
+
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "7", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1", "vserver-selflink",
+ "vserver-selflink-1");
+ Vertex flavor1 = graph.addVertex(T.label, "flavor", T.id, "8", "aai-node-type", "flavor",
+ "flavor-id", "flavor-id-1", "flavor-name", "flavor-name-1", "flavor-selflink",
+ "flavor-selflink-1");
+ Vertex image1 = graph.addVertex(T.label, "image", T.id, "9", "aai-node-type", "image",
+ "image-id", "image-id-1", "image-name", "image-name-1", "image-os-distro",
+ "image-os-distro-1", "image-os-version", "image-os-version-1");
+ Vertex volume1 = graph.addVertex(T.label, "volume", T.id, "10", "aai-node-type", "volume",
+ "volume-id", "volume-id-1", "volume-selflink", "volume-selflink-1");
+ Vertex vnfc1 = graph.addVertex(T.label, "vnfc", T.id, "11", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfc-name-1", "nfc-naming-code", "nfc-naming-code-1");
+ Vertex snapshot1 = graph.addVertex(T.label, "snapshot", T.id, "12", "aai-node-type",
+ "snapshot", "snapshot-id", "snapshot-id-1");
+ Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "13", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
+ Vertex linter1 =
+ graph.addVertex(T.label, "l-interface", T.id, "14", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id-1", "l-interface-name", "l-interface-name1");
+ Vertex logicallink1 = graph.addVertex(T.label, "logical-link", T.id, "15", "aai-node-type",
+ "logical-link", "link-name", "link-name-1", "l-interface-name", "l-interface-name1");
+ Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "16", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-1");
+ Vertex subnet14 = graph.addVertex(T.label, "subnet", T.id, "17", "aai-node-type", "subnet",
+ "subnet-id", "subnet-id-14");
+ Vertex l3network14 = graph.addVertex(T.label, "l3-network", T.id, "18", "aai-node-type",
+ "l3-network", "network-id", "network-id-14", "network-name", "network-name-14");
+ Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "19", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-1");
+ Vertex subnet16 = graph.addVertex(T.label, "subnet", T.id, "20", "aai-node-type", "subnet",
+ "subnet-id", "subnet-id-16");
+ Vertex l3network16 = graph.addVertex(T.label, "l3-network", T.id, "21", "aai-node-type",
+ "l3-network", "network-id", "network-id-16", "network-name", "network-name16");
+
+ Vertex gnvf2 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "33", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnf-id-2", "vnf-name", "vnf-name-2", "service-id", "service-id-wrong");
+ Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "36",
+ "aai-node-type", "service-instance", "service-instance-id", "servInstId-2",
+ "service-type", "servType-2", "service-role", "servRole-2");
+ Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "37", "aai-node-type",
+ "vserver", "vserver-id", "vserver-id-2", "vserver-name", "vserver-name-2",
+ "vserver-selflink", "vserver-selflink-2");
+ Vertex flavor2 = graph.addVertex(T.label, "flavor", T.id, "38", "aai-node-type", "flavor",
+ "flavor-id", "flavor-id-2", "flavor-name", "flavor-name-2", "flavor-selflink",
+ "flavor-selflink-2");
+ Vertex image2 = graph.addVertex(T.label, "image", T.id, "39", "aai-node-type", "image",
+ "image-id", "image-id-2", "image-name", "image-name-2", "image-os-distro",
+ "image-os-distro-2", "image-os-version", "image-os-version-2");
+ Vertex volume2 = graph.addVertex(T.label, "volume", T.id, "40", "aai-node-type", "volume",
+ "volume-id", "volume-id-2", "volume-selflink", "volume-selflink-2");
+ Vertex vnfc2 = graph.addVertex(T.label, "vnfc", T.id, "41", "aai-node-type", "vnfc",
+ "vnfc-name", "vnfc-name-2", "nfc-naming-code", "nfc-naming-code-2");
+ Vertex snapshot2 = graph.addVertex(T.label, "snapshot", T.id, "42", "aai-node-type",
+ "snapshot", "snapshot-id", "snapshot-id-2");
+ Vertex vfmodule2 = graph.addVertex(T.label, "vf-module", T.id, "43", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-2", "vf-module-name", "vf-module-name2");
+ Vertex linter2 =
+ graph.addVertex(T.label, "l-interface", T.id, "44", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id-2", "l-interface-name", "l-interface-name2");
+ Vertex logicallink2 = graph.addVertex(T.label, "logical-link", T.id, "45", "aai-node-type",
+ "logical-link", "link-name", "link-name-2", "l-interface-name", "l-interface-name2");
+ Vertex l3inter1ipv4addresslist2 = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "46", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-2");
+ Vertex subnet24 = graph.addVertex(T.label, "subnet", T.id, "47", "aai-node-type", "subnet",
+ "subnet-id", "subnet-id-24");
+ Vertex l3network24 = graph.addVertex(T.label, "l3-network", T.id, "48", "aai-node-type",
+ "l3-network", "network-id", "network-id-24", "network-name", "network-name-24");
+ Vertex l3inter1ipv6addresslist2 = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "49", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-2");
+ Vertex subnet26 = graph.addVertex(T.label, "subnet", T.id, "50", "aai-node-type", "subnet",
+ "subnet-id", "subnet-id-26");
+ Vertex l3network26 = graph.addVertex(T.label, "l3-network", T.id, "51", "aai-node-type",
+ "l3-network", "network-id", "network-id-26", "network-name", "network-name26");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addTreeEdge(g, cloudregion1, availibityzone1);// true
+ rules.addEdge(g, availibityzone1, gnvf1);// true
+ rules.addEdge(g, gnvf1, serviceinstance1);// true
+ rules.addEdge(g, gnvf1, vserver1);// true
+
+ rules.addEdge(g, vserver1, flavor1);// true
+ rules.addEdge(g, vserver1, image1);// true
+ rules.addTreeEdge(g, vserver1, volume1);// true
+ rules.addEdge(g, vserver1, vnfc1);// true
+ rules.addEdge(g, vserver1, snapshot1);// true
+ rules.addEdge(g, vserver1, vfmodule1);// true
+ rules.addEdge(g, linter1, logicallink1);// true
+ rules.addTreeEdge(g, vserver1, linter1);// true
+ rules.addTreeEdge(g, linter1, l3inter1ipv4addresslist);// true
+ rules.addTreeEdge(g, linter1, l3inter1ipv6addresslist);// true
+ rules.addEdge(g, l3inter1ipv4addresslist, subnet14);// true
+ rules.addTreeEdge(g, subnet14, l3network14);// true
+ rules.addEdge(g, l3inter1ipv6addresslist, subnet16);// true
+ rules.addTreeEdge(g, subnet16, l3network16);// true
+
+ // false
+ rules.addEdge(g, availibityzone1, gnvf2);
+ rules.addEdge(g, gnvf2, serviceinstance2);
+ rules.addEdge(g, gnvf2, vserver2);
+ rules.addEdge(g, vserver2, flavor2);
+ rules.addEdge(g, vserver2, image2);
+ rules.addTreeEdge(g, vserver2, volume2);
+ rules.addEdge(g, vserver2, vnfc2);
+ rules.addEdge(g, vserver2, snapshot2);
+ rules.addEdge(g, vserver2, vfmodule2);
+ rules.addEdge(g, linter2, logicallink2);
+ rules.addTreeEdge(g, vserver2, linter2);
+ rules.addTreeEdge(g, linter2, l3inter1ipv4addresslist2);
+ rules.addTreeEdge(g, linter2, l3inter1ipv6addresslist2);
+ rules.addEdge(g, l3inter1ipv4addresslist2, subnet24);
+ rules.addTreeEdge(g, subnet24, l3network24);
+ rules.addEdge(g, l3inter1ipv6addresslist2, subnet26);
+ rules.addTreeEdge(g, subnet26, l3network26);
+
+ expectedResult.add(serviceinstance1);
+ expectedResult.add(vserver1);
+ expectedResult.add(flavor1);
+ expectedResult.add(image1);
+ expectedResult.add(volume1);
+ expectedResult.add(vnfc1);
+ expectedResult.add(snapshot1);
+ expectedResult.add(vfmodule1);
+ expectedResult.add(linter1);
+ expectedResult.add(logicallink1);
+ expectedResult.add(l3inter1ipv4addresslist);
+ expectedResult.add(subnet14);
+ expectedResult.add(l3network14);
+ expectedResult.add(l3inter1ipv6addresslist);
+ expectedResult.add(subnet16);
+ expectedResult.add(l3network16);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "topology-fromCloudRegionIdandServiceId";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "cloud-region").has("cloud-owner", "cloud-owner-1")
+ .has("cloud-region-id", "cloud-region-id-1");
+
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("serviceId", "service-id-1");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyFromSubscriberNameAndServiceTypeTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyFromSubscriberNameAndServiceTypeTest.java
index 7164dba..46f47de 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyFromSubscriberNameAndServiceTypeTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologyFromSubscriberNameAndServiceTypeTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,9 @@
*/
package org.onap.aai.rest.search;
+import com.att.eelf.configuration.EELFManager;
+import com.google.common.base.CaseFormat;
+
import java.util.Map;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
@@ -26,232 +29,239 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.__;
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import com.att.eelf.configuration.EELFManager;
-import com.google.common.base.CaseFormat;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
public class TopologyFromSubscriberNameAndServiceTypeTest extends QueryTest {
- private static final Logger LOGGER = LoggerFactory
- .getLogger(TopologyFromSubscriberNameAndServiceTypeTest.class);
-
- public TopologyFromSubscriberNameAndServiceTypeTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- // Set up the test graph
- Vertex customer1 = graph.addVertex(T.label, "customer", T.id, "1", "aai-node-type", "customer",
- "global-customer-id", "global-customer-id-1", "subscriber-name", "subscriber-name-1");
- //Customer has 2 subscriptions - we filter by subscription-type
- Vertex servicesubscription1 = graph.addVertex(T.label, "service-subscription", T.id, "2", "aai-node-type",
- "service-subscription", "service-type", "service-type-1");
- Vertex servicesubscription112 = graph.addVertex(T.label, "service-subscription", T.id, "112", "aai-node-type",
- "service-subscription", "service-type", "service-type-112");
-
- Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "3", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name",
- "service-instance-name-1");
- Vertex serviceinstance113 = graph.addVertex(T.label, "service-instance", T.id, "113", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id-113", "service-instance-name",
- "service-instance-name-113");
-
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type", "generic-vnf", "vnf-id",
- "vnf-id-1", "vnf-name", "vnf-name-1", "service-id", "service-id-1");
- Vertex gnvf114 = graph.addVertex(T.label, "generic-vnf", T.id, "114", "aai-node-type", "generic-vnf", "vnf-id",
- "vnf-id-114", "vnf-name", "vnf-name-2", "service-id", "service-id-2");
-
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver", "hostname",
- "pservername1");
- Vertex pserver115 = graph.addVertex(T.label, "pserver", T.id, "115", "aai-node-type", "pserver", "hostname",
- "pservername115");
-
- Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "6", "aai-node-type", "complex",
- "physical-location-id", "physical-location-id-1", "country", "US");
-
- Vertex pnfint1 = graph.addVertex(T.label, "p-interface", T.id, "7", "aai-node-type", "p-interface",
- "interface-name", "ge0/0/0");
-
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "8", "aai-node-type", "vserver", "vserver-id",
- "vserver-id-1", "vserver-name", "vserver-name-1", "vserver-selflink", "vserver-selflink-1");
-
- Vertex vserver116 = graph.addVertex(T.label, "vserver", T.id, "116", "aai-node-type", "vserver", "vserver-id",
- "vserver-id-116", "vserver-name", "vserver-name-116", "vserver-selflink", "vserver-selflink-116");
-
- Vertex flavor1 = graph.addVertex(T.label, "flavor", T.id, "9", "aai-node-type", "flavor", "flavor-id",
- "flavor-id-1", "flavor-name", "flavor-name-1", "flavor-selflink", "flavor-selflink-1");
- Vertex image1 = graph.addVertex(T.label, "image", T.id, "10", "aai-node-type", "image", "image-id",
- "image-id-1", "image-name", "image-name-1", "image-os-distro", "image-os-distro-1", "image-os-version",
- "image-os-version-1");
-
- Vertex linter1 = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type", "l-interface",
- "l-interface-id", "l-interface-id-1", "l-interface-name", "l-interface-name1");
- Vertex logicallink1 = graph.addVertex(T.label, "logical-link", T.id, "12", "aai-node-type", "logical-link",
- "link-name", "link-name-1", "l-interface-name", "l-interface-name1");
- Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "13",
- "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address",
- "l3-interface-ipv4-address-1");
- Vertex subnet1 = graph.addVertex(T.label, "subnet", T.id, "14", "aai-node-type", "subnet", "subnet-id",
- "subnet-id-1");
- Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "15", "aai-node-type", "l3-network",
- "network-id", "network-id-1", "network-name", "network-name-1");
- Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "16",
- "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address",
- "l3-interface-ipv6-address-1");
- Vertex subnet2 = graph.addVertex(T.label, "subnet", T.id, "17", "aai-node-type", "subnet", "subnet-id",
- "subnet-id-2");
- Vertex l3network2 = graph.addVertex(T.label, "l3-network", T.id, "18", "aai-node-type", "l3-network",
- "network-id", "network-id-2", "network-name", "network-name2");
-
- Vertex customer2 = graph.addVertex(T.label, "customer", T.id, "19", "aai-node-type", "customer",
- "global-customer-id", "global-customer-id-2", "subscriber-name", "subscriber-name-2");
- Vertex servicesubscription2 = graph.addVertex(T.label, "service-subscription", T.id, "20", "aai-node-type",
- "service-subscription", "service-type", "service-type-2");
- Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "21", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id-2", "service-instance-name",
- "service-instance-name-2");
- Vertex gnvf2 = graph.addVertex(T.label, "generic-vnf", T.id, "22", "aai-node-type", "generic-vnf", "vnf-id",
- "vnf-id-2", "vnf-name", "vnf-name-2", "service-id", "service-id-2");
-
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "23", "aai-node-type", "pserver", "hostname",
- "pservername1");
- Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "24", "aai-node-type", "complex",
- "physical-location-id", "physical-location-id-2", "country", "US");
- Vertex pnfint2 = graph.addVertex(T.label, "p-interface", T.id, "25", "aai-node-type", "p-interface",
- "interface-name", "ge0/0/0");
-
- Vertex plink1 = graph.addVertex(T.label, "physical-link", T.id, "251", "aai-node-type", "physical-link", "link-name", "ge0/0/0-to-xe0/0/0");
-
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "26", "aai-node-type", "vserver", "vserver-id",
- "vserver-id-2", "vserver-name", "vserver-name-2", "vserver-selflink", "vserver-selflink-2");
- Vertex flavor2 = graph.addVertex(T.label, "flavor", T.id, "27", "aai-node-type", "flavor", "flavor-id",
- "flavor-id-2", "flavor-name", "flavor-name-2", "flavor-selflink", "flavor-selflink-2");
- Vertex image2 = graph.addVertex(T.label, "image", T.id, "28", "aai-node-type", "image", "image-id",
- "image-id-2", "image-name", "image-name-2", "image-os-distro", "image-os-distro-2", "image-os-version",
- "image-os-version-2");
-
- Vertex linter2 = graph.addVertex(T.label, "l-interface", T.id, "29", "aai-node-type", "l-interface",
- "l-interface-id", "l-interface-id-2", "l-interface-name", "l-interface-name2");
- Vertex logicallink2 = graph.addVertex(T.label, "logical-link", T.id, "30", "aai-node-type", "logical-link",
- "link-name", "link-name-2", "l-interface-name", "l-interface-name2");
- Vertex l3inter1ipv4addresslist2 = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "31",
- "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address",
- "l3-interface-ipv4-address-2");
- Vertex subnet3 = graph.addVertex(T.label, "subnet", T.id, "32", "aai-node-type", "subnet", "subnet-id",
- "subnet-id-3");
- Vertex l3network3 = graph.addVertex(T.label, "l3-network", T.id, "33", "aai-node-type", "l3-network",
- "network-id", "network-id-3", "network-name", "network-name-3");
- Vertex l3inter1ipv6addresslist2 = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "34",
- "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address",
- "l3-interface-ipv6-address-2");
- Vertex subnet4 = graph.addVertex(T.label, "subnet", T.id, "35", "aai-node-type", "subnet", "subnet-id",
- "subnet-id-4");
- Vertex l3network4 = graph.addVertex(T.label, "l3-network", T.id, "36", "aai-node-type", "l3-network",
- "network-id", "network-id-4", "network-name", "network-name4");
-
- GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, customer1, servicesubscription1);// true
-
- rules.addTreeEdge(g, customer1, servicesubscription112);// true
-
- rules.addTreeEdge(g, servicesubscription1, serviceinstance1);// true
- rules.addTreeEdge(g, servicesubscription1, serviceinstance113);// true
-
-
- rules.addEdge(g, serviceinstance1, gnvf1);// true
- rules.addEdge(g, serviceinstance113, gnvf114);// true
-
- rules.addEdge(g, gnvf1, vserver1);// true
- rules.addEdge(g, gnvf114, vserver116);// true
-
- rules.addEdge(g, gnvf1, pserver1);// true
- rules.addEdge(g, gnvf114, pserver115);// true
-
- rules.addEdge(g, pserver1, complex1);// true
- rules.addTreeEdge(g, pserver1, pnfint1);
- rules.addEdge(g, pnfint1, plink1);
-
- rules.addEdge(g, vserver1, flavor1);// true
- rules.addEdge(g, vserver1, image1);// true
- rules.addEdge(g, vserver1, pserver1);// true
- rules.addEdge(g, linter1, logicallink1);// true
- rules.addTreeEdge(g, vserver1, linter1);// true
- rules.addTreeEdge(g, linter1, l3inter1ipv4addresslist);// true
- rules.addTreeEdge(g, linter1, l3inter1ipv6addresslist);// true
- rules.addEdge(g, l3inter1ipv4addresslist, subnet1);// true
- rules.addTreeEdge(g, subnet1, l3network1);// true
- rules.addEdge(g, l3inter1ipv6addresslist, subnet2);// true
- rules.addTreeEdge(g, subnet2, l3network2);// true
- // false
-
- rules.addTreeEdge(g, customer2, servicesubscription2);// true
- rules.addTreeEdge(g, servicesubscription2, serviceinstance2);// true
- rules.addEdge(g, serviceinstance2, gnvf2);// true
- rules.addEdge(g, gnvf2, pserver2);// true
- rules.addEdge(g, pserver2, complex2);// true
- rules.addTreeEdge(g, pserver2, pnfint2);// true
-
- rules.addEdge(g, gnvf2, vserver2);// true
-
- rules.addEdge(g, vserver2, flavor2);// true
- rules.addEdge(g, vserver2, image2);// true
- rules.addEdge(g, linter2, logicallink2);// true
- rules.addTreeEdge(g, vserver2, linter2);// true
- rules.addTreeEdge(g, linter2, l3inter1ipv4addresslist2);// true
- rules.addTreeEdge(g, linter2, l3inter1ipv6addresslist2);// true
- rules.addEdge(g, l3inter1ipv4addresslist2, subnet3);// true
- rules.addTreeEdge(g, subnet3, l3network3);// true
- rules.addEdge(g, l3inter1ipv6addresslist2, subnet4);// true
- rules.addTreeEdge(g, subnet4, l3network4);// true
-
- expectedResult.add(complex1);
- expectedResult.add(vserver1);
- expectedResult.add(vserver116);
- expectedResult.add(pserver1);
- expectedResult.add(flavor1);
- expectedResult.add(image1);
- expectedResult.add(linter1);
- expectedResult.add(logicallink1);
- expectedResult.add(plink1);
- expectedResult.add(l3inter1ipv4addresslist);
- expectedResult.add(subnet1);
- expectedResult.add(l3network1);
- expectedResult.add(l3inter1ipv6addresslist);
- expectedResult.add(subnet2);
- expectedResult.add(l3network2);
-
- }
-
- @Override
- protected String getQueryName() {
- return "spaas-topology-fromServiceInstance";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g
- .has("aai-node-type", "customer")
- .has("global-customer-id", "global-customer-id-1")
- .in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type","service-subscription")
- .has("service-type", "service-type-1")
- .in("org.onap.relationships.inventory.BelongsTo")
- .has("aai-node-type","service-instance");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- //params.put("serviceType", "service-type-1");
- //params.put("subscriberName", "subscriber-name-1");
- }
+ private static final Logger LOGGER =
+ LoggerFactory.getLogger(TopologyFromSubscriberNameAndServiceTypeTest.class);
+
+ public TopologyFromSubscriberNameAndServiceTypeTest()
+ throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex customer1 = graph.addVertex(T.label, "customer", T.id, "1", "aai-node-type",
+ "customer", "global-customer-id", "global-customer-id-1", "subscriber-name",
+ "subscriber-name-1");
+ // Customer has 2 subscriptions - we filter by subscription-type
+ Vertex servicesubscription1 = graph.addVertex(T.label, "service-subscription", T.id, "2",
+ "aai-node-type", "service-subscription", "service-type", "service-type-1");
+ Vertex servicesubscription112 = graph.addVertex(T.label, "service-subscription", T.id,
+ "112", "aai-node-type", "service-subscription", "service-type", "service-type-112");
+
+ Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "3",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
+ Vertex serviceinstance113 = graph.addVertex(T.label, "service-instance", T.id, "113",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-113",
+ "service-instance-name", "service-instance-name-113");
+
+ Vertex gnvf1 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1", "service-id", "service-id-1");
+ Vertex gnvf114 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "114", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnf-id-114", "vnf-name", "vnf-name-2", "service-id", "service-id-2");
+
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver",
+ "hostname", "pservername1");
+ Vertex pserver115 = graph.addVertex(T.label, "pserver", T.id, "115", "aai-node-type",
+ "pserver", "hostname", "pservername115");
+
+ Vertex complex1 = graph.addVertex(T.label, "complex", T.id, "6", "aai-node-type", "complex",
+ "physical-location-id", "physical-location-id-1", "country", "US");
+
+ Vertex pnfint1 = graph.addVertex(T.label, "p-interface", T.id, "7", "aai-node-type",
+ "p-interface", "interface-name", "ge0/0/0");
+
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "8", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1", "vserver-selflink",
+ "vserver-selflink-1");
+
+ Vertex vserver116 = graph.addVertex(T.label, "vserver", T.id, "116", "aai-node-type",
+ "vserver", "vserver-id", "vserver-id-116", "vserver-name", "vserver-name-116",
+ "vserver-selflink", "vserver-selflink-116");
+
+ Vertex flavor1 = graph.addVertex(T.label, "flavor", T.id, "9", "aai-node-type", "flavor",
+ "flavor-id", "flavor-id-1", "flavor-name", "flavor-name-1", "flavor-selflink",
+ "flavor-selflink-1");
+ Vertex image1 = graph.addVertex(T.label, "image", T.id, "10", "aai-node-type", "image",
+ "image-id", "image-id-1", "image-name", "image-name-1", "image-os-distro",
+ "image-os-distro-1", "image-os-version", "image-os-version-1");
+
+ Vertex linter1 =
+ graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id-1", "l-interface-name", "l-interface-name1");
+ Vertex logicallink1 = graph.addVertex(T.label, "logical-link", T.id, "12", "aai-node-type",
+ "logical-link", "link-name", "link-name-1", "l-interface-name", "l-interface-name1");
+ Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "13", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-1");
+ Vertex subnet1 = graph.addVertex(T.label, "subnet", T.id, "14", "aai-node-type", "subnet",
+ "subnet-id", "subnet-id-1");
+ Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "15", "aai-node-type",
+ "l3-network", "network-id", "network-id-1", "network-name", "network-name-1");
+ Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "16", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-1");
+ Vertex subnet2 = graph.addVertex(T.label, "subnet", T.id, "17", "aai-node-type", "subnet",
+ "subnet-id", "subnet-id-2");
+ Vertex l3network2 = graph.addVertex(T.label, "l3-network", T.id, "18", "aai-node-type",
+ "l3-network", "network-id", "network-id-2", "network-name", "network-name2");
+
+ Vertex customer2 = graph.addVertex(T.label, "customer", T.id, "19", "aai-node-type",
+ "customer", "global-customer-id", "global-customer-id-2", "subscriber-name",
+ "subscriber-name-2");
+ Vertex servicesubscription2 = graph.addVertex(T.label, "service-subscription", T.id, "20",
+ "aai-node-type", "service-subscription", "service-type", "service-type-2");
+ Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "21",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2",
+ "service-instance-name", "service-instance-name-2");
+ Vertex gnvf2 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "22", "aai-node-type", "generic-vnf",
+ "vnf-id", "vnf-id-2", "vnf-name", "vnf-name-2", "service-id", "service-id-2");
+
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "23", "aai-node-type",
+ "pserver", "hostname", "pservername1");
+ Vertex complex2 = graph.addVertex(T.label, "complex", T.id, "24", "aai-node-type",
+ "complex", "physical-location-id", "physical-location-id-2", "country", "US");
+ Vertex pnfint2 = graph.addVertex(T.label, "p-interface", T.id, "25", "aai-node-type",
+ "p-interface", "interface-name", "ge0/0/0");
+
+ Vertex plink1 = graph.addVertex(T.label, "physical-link", T.id, "251", "aai-node-type",
+ "physical-link", "link-name", "ge0/0/0-to-xe0/0/0");
+
+ Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "26", "aai-node-type",
+ "vserver", "vserver-id", "vserver-id-2", "vserver-name", "vserver-name-2",
+ "vserver-selflink", "vserver-selflink-2");
+ Vertex flavor2 = graph.addVertex(T.label, "flavor", T.id, "27", "aai-node-type", "flavor",
+ "flavor-id", "flavor-id-2", "flavor-name", "flavor-name-2", "flavor-selflink",
+ "flavor-selflink-2");
+ Vertex image2 = graph.addVertex(T.label, "image", T.id, "28", "aai-node-type", "image",
+ "image-id", "image-id-2", "image-name", "image-name-2", "image-os-distro",
+ "image-os-distro-2", "image-os-version", "image-os-version-2");
+
+ Vertex linter2 =
+ graph.addVertex(T.label, "l-interface", T.id, "29", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id-2", "l-interface-name", "l-interface-name2");
+ Vertex logicallink2 = graph.addVertex(T.label, "logical-link", T.id, "30", "aai-node-type",
+ "logical-link", "link-name", "link-name-2", "l-interface-name", "l-interface-name2");
+ Vertex l3inter1ipv4addresslist2 = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "31", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "l3-interface-ipv4-address-2");
+ Vertex subnet3 = graph.addVertex(T.label, "subnet", T.id, "32", "aai-node-type", "subnet",
+ "subnet-id", "subnet-id-3");
+ Vertex l3network3 = graph.addVertex(T.label, "l3-network", T.id, "33", "aai-node-type",
+ "l3-network", "network-id", "network-id-3", "network-name", "network-name-3");
+ Vertex l3inter1ipv6addresslist2 = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "34", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "l3-interface-ipv6-address-2");
+ Vertex subnet4 = graph.addVertex(T.label, "subnet", T.id, "35", "aai-node-type", "subnet",
+ "subnet-id", "subnet-id-4");
+ Vertex l3network4 = graph.addVertex(T.label, "l3-network", T.id, "36", "aai-node-type",
+ "l3-network", "network-id", "network-id-4", "network-name", "network-name4");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addTreeEdge(g, customer1, servicesubscription1);// true
+
+ rules.addTreeEdge(g, customer1, servicesubscription112);// true
+
+ rules.addTreeEdge(g, servicesubscription1, serviceinstance1);// true
+ rules.addTreeEdge(g, servicesubscription1, serviceinstance113);// true
+
+ rules.addEdge(g, serviceinstance1, gnvf1);// true
+ rules.addEdge(g, serviceinstance113, gnvf114);// true
+
+ rules.addEdge(g, gnvf1, vserver1);// true
+ rules.addEdge(g, gnvf114, vserver116);// true
+
+ rules.addEdge(g, gnvf1, pserver1);// true
+ rules.addEdge(g, gnvf114, pserver115);// true
+
+ rules.addEdge(g, pserver1, complex1);// true
+ rules.addTreeEdge(g, pserver1, pnfint1);
+ rules.addEdge(g, pnfint1, plink1);
+
+ rules.addEdge(g, vserver1, flavor1);// true
+ rules.addEdge(g, vserver1, image1);// true
+ rules.addEdge(g, vserver1, pserver1);// true
+ rules.addEdge(g, linter1, logicallink1);// true
+ rules.addTreeEdge(g, vserver1, linter1);// true
+ rules.addTreeEdge(g, linter1, l3inter1ipv4addresslist);// true
+ rules.addTreeEdge(g, linter1, l3inter1ipv6addresslist);// true
+ rules.addEdge(g, l3inter1ipv4addresslist, subnet1);// true
+ rules.addTreeEdge(g, subnet1, l3network1);// true
+ rules.addEdge(g, l3inter1ipv6addresslist, subnet2);// true
+ rules.addTreeEdge(g, subnet2, l3network2);// true
+ // false
+
+ rules.addTreeEdge(g, customer2, servicesubscription2);// true
+ rules.addTreeEdge(g, servicesubscription2, serviceinstance2);// true
+ rules.addEdge(g, serviceinstance2, gnvf2);// true
+ rules.addEdge(g, gnvf2, pserver2);// true
+ rules.addEdge(g, pserver2, complex2);// true
+ rules.addTreeEdge(g, pserver2, pnfint2);// true
+
+ rules.addEdge(g, gnvf2, vserver2);// true
+
+ rules.addEdge(g, vserver2, flavor2);// true
+ rules.addEdge(g, vserver2, image2);// true
+ rules.addEdge(g, linter2, logicallink2);// true
+ rules.addTreeEdge(g, vserver2, linter2);// true
+ rules.addTreeEdge(g, linter2, l3inter1ipv4addresslist2);// true
+ rules.addTreeEdge(g, linter2, l3inter1ipv6addresslist2);// true
+ rules.addEdge(g, l3inter1ipv4addresslist2, subnet3);// true
+ rules.addTreeEdge(g, subnet3, l3network3);// true
+ rules.addEdge(g, l3inter1ipv6addresslist2, subnet4);// true
+ rules.addTreeEdge(g, subnet4, l3network4);// true
+
+ expectedResult.add(complex1);
+ expectedResult.add(vserver1);
+ expectedResult.add(vserver116);
+ expectedResult.add(pserver1);
+ expectedResult.add(flavor1);
+ expectedResult.add(image1);
+ expectedResult.add(linter1);
+ expectedResult.add(logicallink1);
+ expectedResult.add(plink1);
+ expectedResult.add(l3inter1ipv4addresslist);
+ expectedResult.add(subnet1);
+ expectedResult.add(l3network1);
+ expectedResult.add(l3inter1ipv6addresslist);
+ expectedResult.add(subnet2);
+ expectedResult.add(l3network2);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "spaas-topology-fromServiceInstance";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "customer").has("global-customer-id", "global-customer-id-1")
+ .in("org.onap.relationships.inventory.BelongsTo")
+ .has("aai-node-type", "service-subscription").has("service-type", "service-type-1")
+ .in("org.onap.relationships.inventory.BelongsTo")
+ .has("aai-node-type", "service-instance");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ // params.put("serviceType", "service-type-1");
+ // params.put("subscriberName", "subscriber-name-1");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologySummaryFromCloudRegionQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologySummaryFromCloudRegionQueryTest.java
index 0377182..2043706 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologySummaryFromCloudRegionQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologySummaryFromCloudRegionQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,13 +26,12 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-public class TopologySummaryFromCloudRegionQueryTest extends QueryTest{
+public class TopologySummaryFromCloudRegionQueryTest extends QueryTest {
- public TopologySummaryFromCloudRegionQueryTest() throws AAIException, NoEdgeRuleFoundException{
+ public TopologySummaryFromCloudRegionQueryTest() throws AAIException, NoEdgeRuleFoundException {
super();
}
@@ -43,35 +42,45 @@ public class TopologySummaryFromCloudRegionQueryTest extends QueryTest{
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex region = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1",
- "cloud-region-owner", "cloud-region-owner-1","cloud-region-version","cloud-region-version-1");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "2", "aai-node-type", "tenant", "tenant-id", "tenant-id-1",
- "tenant-name", "tenant-name-1");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserver-id-1",
- "vserver-name", "vserver-name-1");
- Vertex vnf = graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type", "generic-vnf", "vnf-id", "vnf-uuid-1",
- "vnf-name", "vnf-name=1");
- Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "13", "aai-node-type", "vnfc", "vnfc-name", "VnfcName", "nfc-naming-code",
- "NfcNamingCode", "nfc-function", "NfcFunction", "in-maint", "false", "is-closed-loop-disabled", "false");
- Vertex vnfc2 = graph.addVertex(T.label, "vnfc", T.id, "15", "aai-node-type", "vnfc", "vnfc-name", "VnfcName3", "nfc-naming-code",
- "NfcNamingCode3", "nfc-function", "NfcFunction3", "in-maint", "false", "is-closed-loop-disabled", "false");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver", "hostname", "pserver-hostname-1");
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "6", "aai-node-type", "pserver", "hostname", "pserver-hostname-2");
+ Vertex region = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner",
+ "cloud-region-owner-1", "cloud-region-version", "cloud-region-version-1");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "2", "aai-node-type", "tenant",
+ "tenant-id", "tenant-id-1", "tenant-name", "tenant-name-1");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
+ Vertex vnf = graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-uuid-1", "vnf-name", "vnf-name=1");
+ Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "13", "aai-node-type", "vnfc",
+ "vnfc-name", "VnfcName", "nfc-naming-code", "NfcNamingCode", "nfc-function",
+ "NfcFunction", "in-maint", "false", "is-closed-loop-disabled", "false");
+ Vertex vnfc2 = graph.addVertex(T.label, "vnfc", T.id, "15", "aai-node-type", "vnfc",
+ "vnfc-name", "VnfcName3", "nfc-naming-code", "NfcNamingCode3", "nfc-function",
+ "NfcFunction3", "in-maint", "false", "is-closed-loop-disabled", "false");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver",
+ "hostname", "pserver-hostname-1");
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "6", "aai-node-type", "pserver",
+ "hostname", "pserver-hostname-2");
- Vertex region_exclude = graph.addVertex(T.label, "cloud-region", T.id, "7", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-2",
- "cloud-region-owner", "cloud-region-owner-2","cloud-region-version","cloud-region-version-2");
- Vertex tenant_exclude = graph.addVertex(T.label, "tenant", T.id, "8", "aai-node-type", "tenant", "tenant-id", "tenant-id-2",
- "tenant-name", "tenant-name-2");
- Vertex vserver_exclude = graph.addVertex(T.label, "vserver", T.id, "9", "aai-node-type", "vserver", "vserver-id", "vserver-id-2",
- "vserver-name", "vserver-name-2");
- Vertex vnf_exclude = graph.addVertex(T.label, "generic-vnf", T.id, "10", "aai-node-type", "generic-vnf", "vnf-id", "vnf-uuid-2",
- "vnf-name", "vnf-name=2");
- Vertex vnfc_exclude = graph.addVertex(T.label, "vnfc", T.id, "14", "aai-node-type", "vnfc", "vnfc-name", "VnfcName2", "nfc-naming-code",
- "NfcNamingCode2", "nfc-function", "NfcFunction2", "in-maint", "false", "is-closed-loop-disabled", "false");
- Vertex vnfc_exclude2 = graph.addVertex(T.label, "vnfc", T.id, "16", "aai-node-type", "vnfc", "vnfc-name", "VnfcName4", "nfc-naming-code",
- "NfcNamingCode4", "nfc-function", "NfcFunction4", "in-maint", "false", "is-closed-loop-disabled", "false");
- Vertex pserver_exclude = graph.addVertex(T.label, "pserver", T.id, "11", "aai-node-type", "pserver", "hostname", "pserver-hostname-2");
- Vertex pserver2_exclude = graph.addVertex(T.label, "pserver", T.id, "12", "aai-node-type", "pserver", "hostname", "pserver-hostname-3");
+ Vertex region_exclude = graph.addVertex(T.label, "cloud-region", T.id, "7", "aai-node-type",
+ "cloud-region", "cloud-region-id", "cloud-region-id-2", "cloud-region-owner",
+ "cloud-region-owner-2", "cloud-region-version", "cloud-region-version-2");
+ Vertex tenant_exclude = graph.addVertex(T.label, "tenant", T.id, "8", "aai-node-type",
+ "tenant", "tenant-id", "tenant-id-2", "tenant-name", "tenant-name-2");
+ Vertex vserver_exclude = graph.addVertex(T.label, "vserver", T.id, "9", "aai-node-type",
+ "vserver", "vserver-id", "vserver-id-2", "vserver-name", "vserver-name-2");
+ Vertex vnf_exclude = graph.addVertex(T.label, "generic-vnf", T.id, "10", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-uuid-2", "vnf-name", "vnf-name=2");
+ Vertex vnfc_exclude = graph.addVertex(T.label, "vnfc", T.id, "14", "aai-node-type", "vnfc",
+ "vnfc-name", "VnfcName2", "nfc-naming-code", "NfcNamingCode2", "nfc-function",
+ "NfcFunction2", "in-maint", "false", "is-closed-loop-disabled", "false");
+ Vertex vnfc_exclude2 = graph.addVertex(T.label, "vnfc", T.id, "16", "aai-node-type", "vnfc",
+ "vnfc-name", "VnfcName4", "nfc-naming-code", "NfcNamingCode4", "nfc-function",
+ "NfcFunction4", "in-maint", "false", "is-closed-loop-disabled", "false");
+ Vertex pserver_exclude = graph.addVertex(T.label, "pserver", T.id, "11", "aai-node-type",
+ "pserver", "hostname", "pserver-hostname-2");
+ Vertex pserver2_exclude = graph.addVertex(T.label, "pserver", T.id, "12", "aai-node-type",
+ "pserver", "hostname", "pserver-hostname-3");
GraphTraversalSource g = graph.traversal();
rules.addTreeEdge(g, region, tenant);
@@ -79,7 +88,7 @@ public class TopologySummaryFromCloudRegionQueryTest extends QueryTest{
rules.addEdge(g, vserver, pserver);
rules.addEdge(g, vserver, vnf);
rules.addEdge(g, vnf, vnfc);
- rules.addEdge(g, vserver, vnfc2);
+ rules.addEdge(g, vserver, vnfc2);
rules.addEdge(g, region, pserver2);
rules.addTreeEdge(g, region_exclude, tenant_exclude);
@@ -107,7 +116,8 @@ public class TopologySummaryFromCloudRegionQueryTest extends QueryTest{
@Override
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("cloud-region-id", "cloud-region-id-1").has("cloud-region-owner", "cloud-region-owner-1");
+ g.has("cloud-region-id", "cloud-region-id-1").has("cloud-region-owner",
+ "cloud-region-owner-1");
}
@Override
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologySummaryFromTenantTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologySummaryFromTenantTest.java
index 36c7396..23a3754 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologySummaryFromTenantTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologySummaryFromTenantTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -31,63 +31,74 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class TopologySummaryFromTenantTest extends QueryTest {
- public TopologySummaryFromTenantTest() throws AAIException,NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
+ public TopologySummaryFromTenantTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex tenant = graph.addVertex(T.label, "tenant-id", T.id, "0", "aai-node-type", "tenant", "tenant-id", "TenantID", "tenant-name", "TenantName");
- Vertex cloudRegion = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type", "cloud-region", "cloud-owner", "CloudOwner", "cloud-region-id", "CloudRegionId");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "2", "aai-node-type", "vserver", "vserver-id", "vservId-1", "vserver-name", "vserv-name-1", "vserver-selflink", "me/self");
- Vertex genericVnf = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type", "generic-vnf", "vnf-id", "VnfID", "vnf-name", "VnfName", "vnf-type", "VnfType");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver", "pserver-id", "PserverID", "hostname", "PserverHostName");
-
- Vertex tenant2 = graph.addVertex(T.label, "tenant-id2", T.id, "5", "aai-node-type", "tenant", "tenant-id", "TenantID2", "tenant-name", "TenantName2");
- Vertex cloudRegion2 = graph.addVertex(T.label, "cloud-region2", T.id, "6", "aai-node-type", "cloud-region", "cloud-owner", "CloudOwner2", "cloud-region-id", "CloudRegionId2");
- Vertex vserver2 = graph.addVertex(T.label, "vserver2", T.id, "7", "aai-node-type", "vserver", "vserver-id", "vservId-2", "vserver-name", "vserv-name-2", "vserver-selflink", "me/self"); //false
- Vertex genericVnf2 = graph.addVertex(T.label, "generic-vnf2", T.id, "8", "aai-node-type", "generic-vnf", "vnf-id", "VnfID2", "vnf-name", "VnfName2", "vnf-type", "VnfType"); //false
- Vertex pserver2 = graph.addVertex(T.label, "pserver2", T.id, "9", "aai-node-type", "pserver", "pserver-id", "PserverID2", "hostname", "PserverHostName2"); //false
+ @Test
+ public void run() {
+ super.run();
+ }
- GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, tenant, cloudRegion);
- rules.addTreeEdge(g, tenant, vserver);
- rules.addEdge(g, vserver, genericVnf);
- rules.addEdge(g, vserver, pserver);
-
- //tenant2
- rules.addTreeEdge(g, tenant2, cloudRegion2);//false
- rules.addTreeEdge(g, tenant2, vserver2);//false
- rules.addEdge(g, vserver2, genericVnf2); //false
- rules.addEdge(g, vserver2, pserver2); //false
-
-
- expectedResult.add(tenant);
- expectedResult.add(cloudRegion);
- expectedResult.add(vserver);
- expectedResult.add(genericVnf);
- expectedResult.add(pserver);
-
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex tenant = graph.addVertex(T.label, "tenant-id", T.id, "0", "aai-node-type", "tenant",
+ "tenant-id", "TenantID", "tenant-name", "TenantName");
+ Vertex cloudRegion = graph.addVertex(T.label, "cloud-region", T.id, "1", "aai-node-type",
+ "cloud-region", "cloud-owner", "CloudOwner", "cloud-region-id", "CloudRegionId");
+ Vertex vserver =
+ graph.addVertex(T.label, "vserver", T.id, "2", "aai-node-type", "vserver", "vserver-id",
+ "vservId-1", "vserver-name", "vserv-name-1", "vserver-selflink", "me/self");
+ Vertex genericVnf = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type",
+ "generic-vnf", "vnf-id", "VnfID", "vnf-name", "VnfName", "vnf-type", "VnfType");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver",
+ "pserver-id", "PserverID", "hostname", "PserverHostName");
- @Override
- protected String getQueryName() {
- return "topology-summary-fromTenant";
- }
+ Vertex tenant2 = graph.addVertex(T.label, "tenant-id2", T.id, "5", "aai-node-type",
+ "tenant", "tenant-id", "TenantID2", "tenant-name", "TenantName2");
+ Vertex cloudRegion2 = graph.addVertex(T.label, "cloud-region2", T.id, "6", "aai-node-type",
+ "cloud-region", "cloud-owner", "CloudOwner2", "cloud-region-id", "CloudRegionId2");
+ Vertex vserver2 = graph.addVertex(T.label, "vserver2", T.id, "7", "aai-node-type",
+ "vserver", "vserver-id", "vservId-2", "vserver-name", "vserv-name-2",
+ "vserver-selflink", "me/self"); // false
+ Vertex genericVnf2 = graph.addVertex(T.label, "generic-vnf2", T.id, "8", "aai-node-type",
+ "generic-vnf", "vnf-id", "VnfID2", "vnf-name", "VnfName2", "vnf-type", "VnfType"); // false
+ Vertex pserver2 = graph.addVertex(T.label, "pserver2", T.id, "9", "aai-node-type",
+ "pserver", "pserver-id", "PserverID2", "hostname", "PserverHostName2"); // false
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "tenant").has("tenant-id","TenantID");
- }
+ GraphTraversalSource g = graph.traversal();
+ rules.addTreeEdge(g, tenant, cloudRegion);
+ rules.addTreeEdge(g, tenant, vserver);
+ rules.addEdge(g, vserver, genericVnf);
+ rules.addEdge(g, vserver, pserver);
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ // tenant2
+ rules.addTreeEdge(g, tenant2, cloudRegion2);// false
+ rules.addTreeEdge(g, tenant2, vserver2);// false
+ rules.addEdge(g, vserver2, genericVnf2); // false
+ rules.addEdge(g, vserver2, pserver2); // false
+
+ expectedResult.add(tenant);
+ expectedResult.add(cloudRegion);
+ expectedResult.add(vserver);
+ expectedResult.add(genericVnf);
+ expectedResult.add(pserver);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "topology-summary-fromTenant";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "tenant").has("tenant-id", "TenantID");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologySummaryQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologySummaryQueryTest.java
index 88af274..5e0f803 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologySummaryQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/TopologySummaryQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,91 +26,100 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class TopologySummaryQueryTest extends QueryTest {
- public TopologySummaryQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public TopologySummaryQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex vnf = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfuuid");
+ Vertex vnfint = graph.addVertex(T.label, "l-interface", T.id, "10", "aai-node-type",
+ "l-interface", "interface-name", "xe0/0/0");
+ Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "1", "aai-node-type", "vnfc");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "2", "aai-node-type", "vserver");
+ Vertex vserverint = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type",
+ "l-interface", "interface-name", "xe0/0/0");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "3", "aai-node-type", "tenant");
+ Vertex region =
+ graph.addVertex(T.label, "could-region", T.id, "4", "aai-node-type", "cloud-region");
+ Vertex image = graph.addVertex(T.label, "image", T.id, "5", "aai-node-type", "image");
+ Vertex flavor = graph.addVertex(T.label, "flavor", T.id, "6", "aai-node-type", "flavor");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "7", "aai-node-type", "pserver");
+ Vertex pserverint = graph.addVertex(T.label, "p-interface", T.id, "9", "aai-node-type",
+ "p-interface", "interface-name", "xe0/0/0");
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "8", "aai-node-type", "complex");
+ Vertex lineofbusiness = graph.addVertex(T.label, "line-of-business", T.id, "12",
+ "aai-node-type", "line-of-business");
+ Vertex platform =
+ graph.addVertex(T.label, "platform", T.id, "13", "aai-node-type", "platform");
+ Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "14",
+ "aai-node-type", "service-instance");
+ Vertex owningentity =
+ graph.addVertex(T.label, "owning-entity", T.id, "15", "aai-node-type", "owning-entity");
+ Vertex project =
+ graph.addVertex(T.label, "project", T.id, "16", "aai-node-type", "project");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, vnf, vnfc);
+ rules.addEdge(g, vnf, vserver);
+ rules.addEdge(g, vnfc, vserver);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addTreeEdge(g, tenant, region);
+ rules.addEdge(g, vserver, image);
+ rules.addEdge(g, vserver, flavor);
+ rules.addEdge(g, vserver, pserver);
+ rules.addEdge(g, pserver, complex);
+ rules.addEdge(g, region, complex);
+ rules.addTreeEdge(g, pserver, pserverint);
+ rules.addTreeEdge(g, vnf, vnfint);
+ rules.addTreeEdge(g, vserver, vserverint);
+ rules.addEdge(g, vnf, lineofbusiness);
+ rules.addEdge(g, vnf, platform);
+ rules.addEdge(g, vnf, serviceinstance);
+ rules.addEdge(g, serviceinstance, owningentity);
+ rules.addEdge(g, serviceinstance, project);
+
+ expectedResult.add(vnf);
+ expectedResult.add(vnfc);
+ expectedResult.add(vserver);
+ expectedResult.add(tenant);
+ expectedResult.add(region);
+ expectedResult.add(image);
+ expectedResult.add(flavor);
+ expectedResult.add(pserver);
+ expectedResult.add(complex);
+ expectedResult.add(lineofbusiness);
+ expectedResult.add(platform);
+ expectedResult.add(owningentity);
+ expectedResult.add(project);
+
+ }
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex vnf = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf", "vnf-id", "vnfuuid");
- Vertex vnfint = graph.addVertex(T.label, "l-interface", T.id, "10", "aai-node-type", "l-interface", "interface-name", "xe0/0/0");
- Vertex vnfc = graph.addVertex(T.label, "vnfc", T.id, "1", "aai-node-type", "vnfc");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "2", "aai-node-type", "vserver");
- Vertex vserverint = graph.addVertex(T.label, "l-interface", T.id, "11", "aai-node-type", "l-interface", "interface-name", "xe0/0/0");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "3", "aai-node-type", "tenant");
- Vertex region = graph.addVertex(T.label, "could-region", T.id, "4", "aai-node-type", "cloud-region");
- Vertex image = graph.addVertex(T.label, "image", T.id, "5", "aai-node-type", "image");
- Vertex flavor = graph.addVertex(T.label, "flavor", T.id, "6", "aai-node-type", "flavor");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "7", "aai-node-type", "pserver");
- Vertex pserverint = graph.addVertex(T.label, "p-interface", T.id, "9", "aai-node-type", "p-interface", "interface-name", "xe0/0/0");
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "8", "aai-node-type", "complex");
- Vertex lineofbusiness = graph.addVertex(T.label, "line-of-business", T.id, "12", "aai-node-type", "line-of-business");
- Vertex platform = graph.addVertex(T.label, "platform", T.id, "13", "aai-node-type", "platform");
- Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "14", "aai-node-type", "service-instance");
- Vertex owningentity = graph.addVertex(T.label, "owning-entity", T.id, "15", "aai-node-type", "owning-entity");
- Vertex project = graph.addVertex(T.label, "project", T.id, "16", "aai-node-type", "project");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, vnf, vnfc);
- rules.addEdge(g, vnf, vserver);
- rules.addEdge(g, vnfc, vserver);
- rules.addTreeEdge(g, vserver, tenant);
- rules.addTreeEdge(g, tenant, region);
- rules.addEdge(g, vserver, image);
- rules.addEdge(g, vserver, flavor);
- rules.addEdge(g, vserver, pserver);
- rules.addEdge(g, pserver, complex);
- rules.addEdge(g, region, complex);
- rules.addTreeEdge(g, pserver, pserverint);
- rules.addTreeEdge(g, vnf, vnfint);
- rules.addTreeEdge(g, vserver, vserverint);
- rules.addEdge(g, vnf, lineofbusiness);
- rules.addEdge(g, vnf, platform);
- rules.addEdge(g, vnf, serviceinstance);
- rules.addEdge(g, serviceinstance, owningentity);
- rules.addEdge(g, serviceinstance, project);
-
- expectedResult.add(vnf);
- expectedResult.add(vnfc);
- expectedResult.add(vserver);
- expectedResult.add(tenant);
- expectedResult.add(region);
- expectedResult.add(image);
- expectedResult.add(flavor);
- expectedResult.add(pserver);
- expectedResult.add(complex);
- expectedResult.add(lineofbusiness);
- expectedResult.add(platform);
- expectedResult.add(owningentity);
- expectedResult.add(project);
-
- }
+ @Override
+ protected String getQueryName() {
+ return "topology-summary";
+ }
- @Override
- protected String getQueryName() {
- return "topology-summary";
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("vnf-id", "vnfuuid");
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("vnf-id", "vnfuuid");
-
- }
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/TreeQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/TreeQueryTest.java
index 109cfc1..5912281 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/TreeQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/TreeQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,21 +19,21 @@
*/
package org.onap.aai.rest.search;
+import java.util.List;
+
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.onap.aai.exceptions.AAIException;
-import java.util.List;
-
public abstract class TreeQueryTest extends QueryTest {
- protected List<Tree> treeList;
+ protected List<Tree> treeList;
- public TreeQueryTest() throws AAIException {
- super();
- }
+ public TreeQueryTest() throws AAIException {
+ super();
+ }
- @Override
- public void run() {
- treeList = (List<Tree>)shell.executeTraversal(query, params).toList();
- }
+ @Override
+ public void run() {
+ treeList = (List<Tree>) shell.executeTraversal(query, params).toList();
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/UcpeInstanceQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/UcpeInstanceQueryTest.java
index 8e3bb5f..478e259 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/UcpeInstanceQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/UcpeInstanceQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,58 +26,63 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class UcpeInstanceQueryTest extends QueryTest {
- public UcpeInstanceQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public UcpeInstanceQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex",
+ "physical-location-id", "clli");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver",
+ "hostname", "pservername");
+ Vertex pnf = graph.addVertex(T.label, "pnf", T.id, "11", "aai-node-type", "pnf", "pnf-name",
+ "pnfname");
+ Vertex vnf = graph.addVertex(T.label, "generic-vnf", T.id, "7", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfuuid");
+ Vertex pserverint = graph.addVertex(T.label, "p-interface", T.id, "2", "aai-node-type",
+ "p-interface", "interface-name", "xe0/0/0");
+ Vertex pnfint = graph.addVertex(T.label, "p-interface", T.id, "12", "aai-node-type",
+ "p-interface", "interface-name", "ge0/0/0");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, pserver, complex);
+ rules.addEdge(g, pnf, complex);
+ rules.addEdge(g, vnf, pserver);
+ rules.addTreeEdge(g, pserver, pserverint);
+ rules.addTreeEdge(g, pnf, pnfint);
+
+ expectedResult.add(complex);
+ expectedResult.add(pserver);
+ // expectedResult.add(pnf);
+
+ }
- @Test
- public void run() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex", "physical-location-id", "clli");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver", "hostname", "pservername");
- Vertex pnf = graph.addVertex(T.label, "pnf", T.id, "11", "aai-node-type", "pnf", "pnf-name", "pnfname");
- Vertex vnf = graph.addVertex(T.label, "generic-vnf", T.id, "7", "aai-node-type", "generic-vnf", "vnf-id", "vnfuuid");
- Vertex pserverint = graph.addVertex(T.label, "p-interface", T.id, "2", "aai-node-type", "p-interface", "interface-name", "xe0/0/0");
- Vertex pnfint = graph.addVertex(T.label, "p-interface", T.id, "12", "aai-node-type", "p-interface", "interface-name", "ge0/0/0");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, pserver, complex);
- rules.addEdge(g, pnf, complex);
- rules.addEdge(g, vnf, pserver);
- rules.addTreeEdge(g, pserver, pserverint);
- rules.addTreeEdge(g, pnf, pnfint);
-
- expectedResult.add(complex);
- expectedResult.add(pserver);
- //expectedResult.add(pnf);
-
- }
+ @Override
+ protected String getQueryName() {
+ return "ucpe-instance";
+ }
- @Override
- protected String getQueryName() {
- return "ucpe-instance";
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("hostname", "pservername");
+ // g.has("pnf-name", "pnfname");
+ }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("hostname", "pservername");
- //g.has("pnf-name", "pnfname");
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
-
- }
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/UcpeTopologyQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/UcpeTopologyQueryTest.java
index 4503717..cf2b1c7 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/UcpeTopologyQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/UcpeTopologyQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -27,96 +27,114 @@ import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Ignore;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class UcpeTopologyQueryTest extends QueryTest {
- public UcpeTopologyQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
-
- //Set up the test graph
- Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex", "physical-location-id", "clli");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver", "hostname", "pservername");
- Vertex pserverint1 = graph.addVertex(T.label, "p-interface", T.id, "2", "aai-node-type", "p-interface", "interface-name", "xe0/0/0");
- Vertex pserverint2 = graph.addVertex(T.label, "p-interface", T.id, "3", "aai-node-type", "p-interface", "interface-name", "xe0/0/0");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "4", "aai-node-type", "vserver", "vserver-name", "vservername");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "5", "aai-node-type", "tenant", "tenant-id", "tenantuuid", "tenant-name", "tenantname");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "6", "aai-node-type", "cloud-region", "cloud-region-id", "clouduuid", "cloud-region-owner", "cloudOwnername");
- Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "7", "aai-node-type", "generic-vnf", "vnf-id", "vnf1uuid");
- Vertex vnf1image = graph.addVertex(T.label, "vnf-image", T.id, "8", "aai-node-type", "vnf-image", "att-uuid", "vnf1imageuuid");
- Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "9", "aai-node-type", "generic-vnf", "vnf-id", "vnf1uuid");
- Vertex vnf2image = graph.addVertex(T.label, "vnf-image", T.id, "10", "aai-node-type", "vnf-image", "att-uuid", "vnf2imageuuid");
- Vertex pnf = graph.addVertex(T.label, "pnf", T.id, "11", "aai-node-type", "pnf", "pnf-name", "pnf1name");
- Vertex pnfint = graph.addVertex(T.label, "p-interface", T.id, "12", "aai-node-type", "p-interface", "interface-name", "ge0/0/0");
- Vertex plink1 = graph.addVertex(T.label, "physical-link", T.id, "13", "aai-node-type", "physical-link", "link-name", "ge0/0/0-to-xe0/0/0");
- Vertex servinst1 = graph.addVertex(T.label, "service-instance", T.id, "14", "aai-node-type", "service-instance", "service-instance-id", "servinst1uuid");
- Vertex servsub1 = graph.addVertex(T.label, "service-subscription", T.id, "15", "aai-node-type", "service-subscription", "service-type", "servType1");
- Vertex customer = graph.addVertex(T.label, "customer", T.id, "16", "aai-node-type", "customer", "global-customer-id", "custuuid");
- Vertex servinst2 = graph.addVertex(T.label, "service-instance", T.id, "17", "aai-node-type", "service-instance", "service-instance-id", "servinst2uuid");
- Vertex servsub2 = graph.addVertex(T.label, "service-subscription", T.id, "18", "aai-node-type", "service-subscription", "service-type", "servType2");
+ public UcpeTopologyQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+
+ // Set up the test graph
+ Vertex complex = graph.addVertex(T.label, "complex", T.id, "0", "aai-node-type", "complex",
+ "physical-location-id", "clli");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver",
+ "hostname", "pservername");
+ Vertex pserverint1 = graph.addVertex(T.label, "p-interface", T.id, "2", "aai-node-type",
+ "p-interface", "interface-name", "xe0/0/0");
+ Vertex pserverint2 = graph.addVertex(T.label, "p-interface", T.id, "3", "aai-node-type",
+ "p-interface", "interface-name", "xe0/0/0");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "4", "aai-node-type", "vserver",
+ "vserver-name", "vservername");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "5", "aai-node-type", "tenant",
+ "tenant-id", "tenantuuid", "tenant-name", "tenantname");
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "6", "aai-node-type",
+ "cloud-region", "cloud-region-id", "clouduuid", "cloud-region-owner", "cloudOwnername");
+ Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "7", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf1uuid");
+ Vertex vnf1image = graph.addVertex(T.label, "vnf-image", T.id, "8", "aai-node-type",
+ "vnf-image", "att-uuid", "vnf1imageuuid");
+ Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "9", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf1uuid");
+ Vertex vnf2image = graph.addVertex(T.label, "vnf-image", T.id, "10", "aai-node-type",
+ "vnf-image", "att-uuid", "vnf2imageuuid");
+ Vertex pnf = graph.addVertex(T.label, "pnf", T.id, "11", "aai-node-type", "pnf", "pnf-name",
+ "pnf1name");
+ Vertex pnfint = graph.addVertex(T.label, "p-interface", T.id, "12", "aai-node-type",
+ "p-interface", "interface-name", "ge0/0/0");
+ Vertex plink1 = graph.addVertex(T.label, "physical-link", T.id, "13", "aai-node-type",
+ "physical-link", "link-name", "ge0/0/0-to-xe0/0/0");
+ Vertex servinst1 = graph.addVertex(T.label, "service-instance", T.id, "14", "aai-node-type",
+ "service-instance", "service-instance-id", "servinst1uuid");
+ Vertex servsub1 = graph.addVertex(T.label, "service-subscription", T.id, "15",
+ "aai-node-type", "service-subscription", "service-type", "servType1");
+ Vertex customer = graph.addVertex(T.label, "customer", T.id, "16", "aai-node-type",
+ "customer", "global-customer-id", "custuuid");
+ Vertex servinst2 = graph.addVertex(T.label, "service-instance", T.id, "17", "aai-node-type",
+ "service-instance", "service-instance-id", "servinst2uuid");
+ Vertex servsub2 = graph.addVertex(T.label, "service-subscription", T.id, "18",
+ "aai-node-type", "service-subscription", "service-type", "servType2");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, pserver, complex);
+ rules.addTreeEdge(g, pserver, pserverint1);
+ rules.addTreeEdge(g, pserver, pserverint2);
+ rules.addEdge(g, pnf, complex);
+ rules.addTreeEdge(g, pnf, pnfint);
+ rules.addEdge(g, pserverint1, plink1);
+ rules.addEdge(g, pnfint, plink1);
+ rules.addEdge(g, vserver, pserver);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addTreeEdge(g, tenant, cloudregion);
+ rules.addEdge(g, pserver, vnf1);
+ rules.addEdge(g, vserver, vnf2);
+ rules.addEdge(g, vnf1, vnf1image);
+ rules.addEdge(g, vnf2, vnf2image);
+ rules.addEdge(g, vnf1, servinst1);
+ rules.addTreeEdge(g, servinst1, servsub1);
+ rules.addTreeEdge(g, servsub1, customer);
+ rules.addEdge(g, vnf2, servinst2);
+ rules.addTreeEdge(g, servinst2, servsub2);
+ rules.addTreeEdge(g, servsub2, customer);
+
+ expectedResult.add(pnf);
+ expectedResult.add(complex);
+ expectedResult.add(pnfint);
+ expectedResult.add(pserver);
+ expectedResult.add(pserverint1);
+ expectedResult.add(plink1);
+ expectedResult.add(vnf1);
+ expectedResult.add(vnf1image);
+ expectedResult.add(vnf2);
+ expectedResult.add(vnf2image);
+ expectedResult.add(servinst1);
+ expectedResult.add(servinst2);
+ expectedResult.add(servsub1);
+ expectedResult.add(servsub2);
+ expectedResult.add(customer);
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, pserver, complex);
- rules.addTreeEdge(g, pserver, pserverint1);
- rules.addTreeEdge(g, pserver, pserverint2);
- rules.addEdge(g, pnf, complex);
- rules.addTreeEdge(g, pnf, pnfint);
- rules.addEdge(g, pserverint1, plink1);
- rules.addEdge(g, pnfint, plink1);
- rules.addEdge(g, vserver, pserver);
- rules.addTreeEdge(g, vserver, tenant);
- rules.addTreeEdge(g, tenant, cloudregion);
- rules.addEdge(g, pserver, vnf1);
- rules.addEdge(g, vserver, vnf2);
- rules.addEdge(g, vnf1, vnf1image);
- rules.addEdge(g, vnf2, vnf2image);
- rules.addEdge(g, vnf1, servinst1);
- rules.addTreeEdge(g, servinst1, servsub1);
- rules.addTreeEdge(g, servsub1, customer);
- rules.addEdge(g, vnf2, servinst2);
- rules.addTreeEdge(g, servinst2, servsub2);
- rules.addTreeEdge(g, servsub2, customer);
+ }
- expectedResult.add(pnf);
- expectedResult.add(complex);
- expectedResult.add(pnfint);
- expectedResult.add(pserver);
- expectedResult.add(pserverint1);
- expectedResult.add(plink1);
- expectedResult.add(vnf1);
- expectedResult.add(vnf1image);
- expectedResult.add(vnf2);
- expectedResult.add(vnf2image);
- expectedResult.add(servinst1);
- expectedResult.add(servinst2);
- expectedResult.add(servsub1);
- expectedResult.add(servsub2);
- expectedResult.add(customer);
+ @Override
+ protected String getQueryName() {
+ return "ucpe-topology";
+ }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("hostname", "pservername");
+ }
- }
- @Override
- protected String getQueryName() {
- return "ucpe-topology";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("hostname", "pservername");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VfModuleFromServiceInstanceTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VfModuleFromServiceInstanceTest.java
index 0d2d11a..9124821 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VfModuleFromServiceInstanceTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VfModuleFromServiceInstanceTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,7 +19,6 @@
*/
package org.onap.aai.rest.search;
-
import java.util.Map;
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
@@ -32,53 +31,58 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class VfModuleFromServiceInstanceTest extends QueryTest {
- public VfModuleFromServiceInstanceTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void test() {
- super.run();
- }
-
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "0", "aai-node-type", "service-instance", "service-instance-id", "s-instance-id1");
- Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "2", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-0", "vf-module-name", "vf-module-name0");
-
- Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-0", "vnf-name", "vnf-name-0");
-
-
- Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "10", "aai-node-type", "service-instance", "service-instance-id", "s-instance-id11");
- Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "12", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-01", "vf-module-name", "vf-module-name01");
-
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "11", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-01", "vnf-name", "vnf-name-01");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, serviceinstance, gnvf);
- rules.addTreeEdge(g, gnvf, vfmodule);
-
- rules.addEdge(g, serviceinstance1, gnvf1); //false
- rules.addTreeEdge(g, gnvf1, vfmodule1); //false
-
- expectedResult.add(vfmodule);
-
- }
-
- @Override
- protected String getQueryName() {
- return "vfModule-fromServiceInstance";
- }
-
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "service-instance").has("service-instance-id", "s-instance-id1");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ public VfModuleFromServiceInstanceTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void test() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "0",
+ "aai-node-type", "service-instance", "service-instance-id", "s-instance-id1");
+ Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "2", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-0", "vf-module-name", "vf-module-name0");
+
+ Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-0", "vnf-name", "vnf-name-0");
+
+ Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "10",
+ "aai-node-type", "service-instance", "service-instance-id", "s-instance-id11");
+ Vertex vfmodule1 = graph.addVertex(T.label, "vf-module", T.id, "12", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-01", "vf-module-name", "vf-module-name01");
+
+ Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "11", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-01", "vnf-name", "vnf-name-01");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, serviceinstance, gnvf);
+ rules.addTreeEdge(g, gnvf, vfmodule);
+
+ rules.addEdge(g, serviceinstance1, gnvf1); // false
+ rules.addTreeEdge(g, gnvf1, vfmodule1); // false
+
+ expectedResult.add(vfmodule);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "vfModule-fromServiceInstance";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "service-instance").has("service-instance-id", "s-instance-id1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfInstancesFromServiceInstancebyModelVersionTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfInstancesFromServiceInstancebyModelVersionTest.java
index 03b4998..cf1e39e 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfInstancesFromServiceInstancebyModelVersionTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfInstancesFromServiceInstancebyModelVersionTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,54 +30,72 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class VnfInstancesFromServiceInstancebyModelVersionTest extends QueryTest {
- public VnfInstancesFromServiceInstancebyModelVersionTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
-
- //Set up the test graph
- Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name", "service-instance-name-1");
- Vertex servicesubscription = graph.addVertex(T.label, "service-subscription", T.id, "2", "aai-node-type", "service-subscription", "service-subscription-id", "service-subscription-id-1","service-subscription-name","service-subscription-name1");
- Vertex customer = graph.addVertex(T.label, "customer", T.id, "3", "aai-node-type", "customer", "customer-id", "customer-id-1", "customer-name", "customer-name1");
-
- Vertex model1 = graph.addVertex(T.label, "model", T.id, "4", "aai-node-type", "model", "model-invariant-id", "modinvariant-id1", "model-type", "modtype");
- Vertex modelver1 = graph.addVertex(T.label, "model-ver", T.id, "5", "aai-node-type", "model-ver", "model-version-id", "modver-id1", "model-name", "modname1", "model-version", "v1.0");
- Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "6", "aai-node-type", "generic-vnf", "vnf-id", "vnfid1", "vnf-name", "vnfname1", "vnf-type", "vnftype1", "model-invariant-id-local", "modinvariant-id1", "model-version-id-local", "modver-id1");
-
-// Vertex model2 = graph.addVertex(T.label, "model", T.id, "7", "aai-node-type", "model", "model-invariant-id", "modinvariant-id2", "model-type", "modtype");
-// Vertex modelver2 = graph.addVertex(T.label, "model-ver", T.id, "8", "aai-node-type", "model-ver", "model-version-id", "modver-id2", "model-name", "modname2", "model-version", "v1.0");
- Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "9", "aai-node-type", "generic-vnf", "vnf-id", "vnfid2", "vnf-name", "vnfname2", "vnf-type", "vnftype2", "model-invariant-id-local", "modinvariant-id1", "model-version-id-local", "modver-id1");
+ public VnfInstancesFromServiceInstancebyModelVersionTest()
+ throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
-
- GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, model1, modelver1);//true
- rules.addEdge(g, vnf1, serviceinstance);//true
- rules.addEdge(g, vnf2, serviceinstance);//false
- rules.addTreeEdge(g, serviceinstance, servicesubscription);//true
- rules.addTreeEdge(g, servicesubscription, customer);//true
-
- expectedResult.add(vnf1);
+ @Test
+ public void run() {
+ super.run();
+ }
- }
- @Override
- protected String getQueryName() {
- return "vnf-instances-fromServiceInstancebyModelVersion";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "service-instance").has("service-instance-id", "service-instance-id-1");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("vnfType", "vnftype1");
- params.put("modelVersionId", "modver-id1");
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+
+ // Set up the test graph
+ Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
+ Vertex servicesubscription = graph.addVertex(T.label, "service-subscription", T.id, "2",
+ "aai-node-type", "service-subscription", "service-subscription-id",
+ "service-subscription-id-1", "service-subscription-name", "service-subscription-name1");
+ Vertex customer = graph.addVertex(T.label, "customer", T.id, "3", "aai-node-type",
+ "customer", "customer-id", "customer-id-1", "customer-name", "customer-name1");
+
+ Vertex model1 = graph.addVertex(T.label, "model", T.id, "4", "aai-node-type", "model",
+ "model-invariant-id", "modinvariant-id1", "model-type", "modtype");
+ Vertex modelver1 = graph.addVertex(T.label, "model-ver", T.id, "5", "aai-node-type",
+ "model-ver", "model-version-id", "modver-id1", "model-name", "modname1",
+ "model-version", "v1.0");
+ Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "6", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid1", "vnf-name", "vnfname1", "vnf-type", "vnftype1",
+ "model-invariant-id-local", "modinvariant-id1", "model-version-id-local", "modver-id1");
+
+ // Vertex model2 = graph.addVertex(T.label, "model", T.id, "7", "aai-node-type", "model",
+ // "model-invariant-id", "modinvariant-id2", "model-type", "modtype");
+ // Vertex modelver2 = graph.addVertex(T.label, "model-ver", T.id, "8", "aai-node-type",
+ // "model-ver", "model-version-id", "modver-id2", "model-name", "modname2", "model-version",
+ // "v1.0");
+ Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "9", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid2", "vnf-name", "vnfname2", "vnf-type", "vnftype2",
+ "model-invariant-id-local", "modinvariant-id1", "model-version-id-local", "modver-id1");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addTreeEdge(g, model1, modelver1);// true
+ rules.addEdge(g, vnf1, serviceinstance);// true
+ rules.addEdge(g, vnf2, serviceinstance);// false
+ rules.addTreeEdge(g, serviceinstance, servicesubscription);// true
+ rules.addTreeEdge(g, servicesubscription, customer);// true
+
+ expectedResult.add(vnf1);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "vnf-instances-fromServiceInstancebyModelVersion";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "service-instance").has("service-instance-id",
+ "service-instance-id-1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("vnfType", "vnftype1");
+ params.put("modelVersionId", "modver-id1");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfSummaryFromVnfTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfSummaryFromVnfTest.java
index c5dcf57..7cdbe72 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfSummaryFromVnfTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfSummaryFromVnfTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,86 +26,104 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class VnfSummaryFromVnfTest extends QueryTest {
- public VnfSummaryFromVnfTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public VnfSummaryFromVnfTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfId1", "vnf-name", "vnf-name-1", "vnf-type", "vnfType1");
+ Vertex genericvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfId2", "vnf-name", "vnf-name-2", "vnf-type", "vnfType2");
+ Vertex platform = graph.addVertex(T.label, "platform", T.id, "3", "aai-node-type",
+ "platform", "platform-name", "platform-name-1");
+ Vertex platform2 = graph.addVertex(T.label, "platform", T.id, "4", "aai-node-type",
+ "platform", "platform-name", "platform-name-2");
+ Vertex lineofbus = graph.addVertex(T.label, "line-of-business", T.id, "5", "aai-node-type",
+ "line-of-business", "line-of-business-name", "line-of-business-name-1");
+ Vertex lineofbus2 = graph.addVertex(T.label, "line-of-business", T.id, "6", "aai-node-type",
+ "line-of-business", "line-of-business-name", "line-of-business-name-2");
+ Vertex serviceinst = graph.addVertex(T.label, "service-instance", T.id, "7",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1");
+ Vertex serviceinst2 = graph.addVertex(T.label, "service-instance", T.id, "8",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2");
+ Vertex owningent = graph.addVertex(T.label, "owning-entity", T.id, "9", "aai-node-type",
+ "owning-entity", "owning-entity-id", "owning-entity-id-1");
+ Vertex owningent2 = graph.addVertex(T.label, "owning-entity", T.id, "10", "aai-node-type",
+ "owning-entity", "owning-entity-id", "owning-entity-id-2");
+ Vertex project = graph.addVertex(T.label, "project", T.id, "11", "aai-node-type", "project",
+ "project-name", "project-name-1");
+ Vertex project2 = graph.addVertex(T.label, "project", T.id, "12", "aai-node-type",
+ "project", "project-name", "project-name-2");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "13", "aai-node-type", "pserver",
+ "hostname", "hostname-1");
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "14", "aai-node-type",
+ "pserver", "hostname", "hostname-2");
+ Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "15", "aai-node-type",
+ "pserver", "hostname", "hostname-2");
+ Vertex pserver4 = graph.addVertex(T.label, "pserver", T.id, "16", "aai-node-type",
+ "pserver", "hostname", "hostname-2");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "17", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-1");
+ Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "18", "aai-node-type",
+ "vserver", "vserver-id", "vserver-id-2");
- //Set up the test graph
- Vertex genericvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf", "vnf-id", "vnfId1", "vnf-name", "vnf-name-1", "vnf-type", "vnfType1");
- Vertex genericvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type", "generic-vnf", "vnf-id", "vnfId2", "vnf-name", "vnf-name-2", "vnf-type", "vnfType2");
- Vertex platform = graph.addVertex(T.label, "platform", T.id, "3", "aai-node-type", "platform", "platform-name", "platform-name-1");
- Vertex platform2 = graph.addVertex(T.label, "platform", T.id, "4", "aai-node-type", "platform", "platform-name", "platform-name-2");
- Vertex lineofbus = graph.addVertex(T.label, "line-of-business", T.id, "5", "aai-node-type", "line-of-business", "line-of-business-name", "line-of-business-name-1");
- Vertex lineofbus2 = graph.addVertex(T.label, "line-of-business", T.id, "6", "aai-node-type", "line-of-business", "line-of-business-name", "line-of-business-name-2");
- Vertex serviceinst = graph.addVertex(T.label, "service-instance", T.id, "7", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1");
- Vertex serviceinst2 = graph.addVertex(T.label, "service-instance", T.id, "8", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2");
- Vertex owningent = graph.addVertex(T.label, "owning-entity", T.id, "9", "aai-node-type", "owning-entity", "owning-entity-id", "owning-entity-id-1");
- Vertex owningent2 = graph.addVertex(T.label, "owning-entity", T.id, "10", "aai-node-type", "owning-entity", "owning-entity-id", "owning-entity-id-2");
- Vertex project = graph.addVertex(T.label, "project", T.id, "11", "aai-node-type", "project", "project-name", "project-name-1");
- Vertex project2 = graph.addVertex(T.label, "project", T.id, "12", "aai-node-type", "project", "project-name", "project-name-2");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "13", "aai-node-type", "pserver", "hostname", "hostname-1");
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "14", "aai-node-type", "pserver", "hostname", "hostname-2");
- Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "15", "aai-node-type", "pserver", "hostname", "hostname-2");
- Vertex pserver4 = graph.addVertex(T.label, "pserver", T.id, "16", "aai-node-type", "pserver", "hostname", "hostname-2");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "17", "aai-node-type", "vserver", "vserver-id", "vserver-id-1");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "18", "aai-node-type", "vserver", "vserver-id", "vserver-id-2");
+ GraphTraversalSource g = graph.traversal();
- GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, genericvnf1, platform);
+ rules.addEdge(g, genericvnf1, lineofbus);
+ rules.addEdge(g, genericvnf1, serviceinst);
+ rules.addEdge(g, serviceinst, owningent);
+ rules.addEdge(g, serviceinst, project);
+ rules.addEdge(g, genericvnf1, pserver);
+ rules.addEdge(g, genericvnf1, vserver);
+ rules.addEdge(g, vserver, pserver2);
- rules.addEdge(g, genericvnf1, platform);
- rules.addEdge(g, genericvnf1, lineofbus);
- rules.addEdge(g, genericvnf1, serviceinst);
- rules.addEdge(g, serviceinst, owningent);
- rules.addEdge(g, serviceinst, project);
- rules.addEdge(g, genericvnf1, pserver);
- rules.addEdge(g, genericvnf1, vserver);
- rules.addEdge(g, vserver, pserver2);
+ rules.addEdge(g, genericvnf2, platform2);// false
+ rules.addEdge(g, genericvnf2, lineofbus2);// false
+ rules.addEdge(g, genericvnf2, serviceinst2);// false
+ rules.addEdge(g, serviceinst2, owningent2);// false
+ rules.addEdge(g, serviceinst2, project2);// false
+ rules.addEdge(g, genericvnf2, pserver3);// false
+ rules.addEdge(g, genericvnf2, vserver2);// false
+ rules.addEdge(g, vserver2, pserver4);// false
- rules.addEdge(g, genericvnf2, platform2);//false
- rules.addEdge(g, genericvnf2, lineofbus2);//false
- rules.addEdge(g, genericvnf2, serviceinst2);//false
- rules.addEdge(g, serviceinst2, owningent2);//false
- rules.addEdge(g, serviceinst2, project2);//false
- rules.addEdge(g, genericvnf2, pserver3);//false
- rules.addEdge(g, genericvnf2, vserver2);//false
- rules.addEdge(g, vserver2, pserver4);//false
+ expectedResult.add(genericvnf1);
+ expectedResult.add(platform);
+ expectedResult.add(lineofbus);
+ expectedResult.add(serviceinst);
+ expectedResult.add(owningent);
+ expectedResult.add(project);
+ expectedResult.add(pserver);
+ expectedResult.add(vserver);
+ expectedResult.add(pserver2);
- expectedResult.add(genericvnf1);
- expectedResult.add(platform);
- expectedResult.add(lineofbus);
- expectedResult.add(serviceinst);
- expectedResult.add(owningent);
- expectedResult.add(project);
- expectedResult.add(pserver);
- expectedResult.add(vserver);
- expectedResult.add(pserver2);
+ }
- }
+ @Override
+ protected String getQueryName() {
+ return "vnf-summary-fromVnf";
+ }
- @Override
- protected String getQueryName() {
- return "vnf-summary-fromVnf";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("vnf-name","vnf-name-1");
- }
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("vnf-name", "vnf-name-1");
+ }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
-} \ No newline at end of file
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfToEsrSystemInfoQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfToEsrSystemInfoQueryTest.java
index 0e82c0b..2d33395 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfToEsrSystemInfoQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfToEsrSystemInfoQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,67 +30,76 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class VnfToEsrSystemInfoQueryTest extends OnapQueryTest {
- public VnfToEsrSystemInfoQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public VnfToEsrSystemInfoQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
-
- Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vserver-id-1","vserver-name","vserver-name-1");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "4", "aai-node-type", "tenant", "tenant-id", "tenantid01", "tenant-name", "tenantName01");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1");
- Vertex esr = graph.addVertex(T.label, "esr-system-info", T.id, "6", "aai-node-type", "esr-system-info", "esr-system-info-id", "esr-system-info-1");
-
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-2");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "9", "aai-node-type", "vserver", "vserver-id", "vserver-id-2","vserver-name","vserver-name-2");
- Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "10", "aai-node-type", "tenant", "tenant-id", "tenantid02", "tenant-name", "tenantName02");
- Vertex cloudregion1 = graph.addVertex(T.label, "cloud-region", T.id, "11", "aai-node-type", "cloud-region", "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-2");
- Vertex esr1 = graph.addVertex(T.label, "esr-system-info", T.id, "12", "aai-node-type", "esr-system-info", "esr-system-info-id", "esr-system-info-2");
-
-
-
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, gnvf, vserver);
- rules.addTreeEdge(g, vserver,tenant);
- rules.addTreeEdge(g, tenant,cloudregion);
- rules.addTreeEdge(g, cloudregion, esr);
-
- //Not expected in result
- rules.addEdge(g, gnvf1, vserver1);
- rules.addTreeEdge(g, vserver1,tenant1);
- rules.addTreeEdge(g, tenant1,cloudregion1);
- rules.addTreeEdge(g, cloudregion1, esr1);
- //Not expected in result
-
- expectedResult.add(gnvf);
- expectedResult.add(vserver);
- expectedResult.add(tenant);
- expectedResult.add(cloudregion);
- expectedResult.add(esr);
-
-
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- @Override
- protected String getQueryName() {
- return "vnf-to-esr-system-info";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "generic-vnf").has("vnf-id", "vnf-id-1");
-
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ Vertex gnvf = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "4", "aai-node-type", "tenant",
+ "tenant-id", "tenantid01", "tenant-name", "tenantName01");
+ Vertex cloudregion =
+ graph.addVertex(T.label, "cloud-region", T.id, "5", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloud-region-id-1", "cloud-region-owner", "cloud-owner-name-1");
+ Vertex esr = graph.addVertex(T.label, "esr-system-info", T.id, "6", "aai-node-type",
+ "esr-system-info", "esr-system-info-id", "esr-system-info-1");
+
+ Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-2");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "9", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-2", "vserver-name", "vserver-name-2");
+ Vertex tenant1 = graph.addVertex(T.label, "tenant", T.id, "10", "aai-node-type", "tenant",
+ "tenant-id", "tenantid02", "tenant-name", "tenantName02");
+ Vertex cloudregion1 =
+ graph.addVertex(T.label, "cloud-region", T.id, "11", "aai-node-type", "cloud-region",
+ "cloud-region-id", "cloud-region-id-2", "cloud-region-owner", "cloud-owner-name-2");
+ Vertex esr1 = graph.addVertex(T.label, "esr-system-info", T.id, "12", "aai-node-type",
+ "esr-system-info", "esr-system-info-id", "esr-system-info-2");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, gnvf, vserver);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addTreeEdge(g, tenant, cloudregion);
+ rules.addTreeEdge(g, cloudregion, esr);
+
+ // Not expected in result
+ rules.addEdge(g, gnvf1, vserver1);
+ rules.addTreeEdge(g, vserver1, tenant1);
+ rules.addTreeEdge(g, tenant1, cloudregion1);
+ rules.addTreeEdge(g, cloudregion1, esr1);
+ // Not expected in result
+
+ expectedResult.add(gnvf);
+ expectedResult.add(vserver);
+ expectedResult.add(tenant);
+ expectedResult.add(cloudregion);
+ expectedResult.add(esr);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "vnf-to-esr-system-info";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "generic-vnf").has("vnf-id", "vnf-id-1");
+
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfToServiceInstanceQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfToServiceInstanceQueryTest.java
index dfd36b7..6a83c36 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfToServiceInstanceQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfToServiceInstanceQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,46 +30,54 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class VnfToServiceInstanceQueryTest extends QueryTest {
- public VnfToServiceInstanceQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
-
- //Set up the test graph
- Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name", "service-instance-name-1");
- Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "2", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2", "service-instance-name", "service-instance-name-2");
-
- Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type", "generic-vnf", "vnf-id", "vnfid1", "vnf-name", "vnfname1", "vnf-type", "vnftype1");
- Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type", "generic-vnf", "vnf-id", "vnfid2", "vnf-name", "vnfname2", "vnf-type", "vnftype1");
-
- GraphTraversalSource g = graph.traversal();
+ public VnfToServiceInstanceQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- rules.addEdge(g, vnf1, serviceinstance1);//true
- rules.addEdge(g, vnf2, serviceinstance1);
+ @Test
+ public void run() {
+ super.run();
+ }
- expectedResult.add(vnf1);
- expectedResult.add(serviceinstance1);
- expectedResult.add(vnf2);
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- }
- @Override
- protected String getQueryName() {
- return "vnf-to-service-instance";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "generic-vnf").has("vnf-id", "vnfid1");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ // Set up the test graph
+ Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
+ Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "2",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2",
+ "service-instance-name", "service-instance-name-2");
+
+ Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid1", "vnf-name", "vnfname1", "vnf-type", "vnftype1");
+ Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid2", "vnf-name", "vnfname2", "vnf-type", "vnftype1");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addEdge(g, vnf1, serviceinstance1);// true
+ rules.addEdge(g, vnf2, serviceinstance1);
+
+ expectedResult.add(vnf1);
+ expectedResult.add(serviceinstance1);
+ expectedResult.add(vnf2);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "vnf-to-service-instance";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "generic-vnf").has("vnf-id", "vnfid1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfTopologyFromServiceInstanceTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfTopologyFromServiceInstanceTest.java
index 5d593dc..aa9cc34 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfTopologyFromServiceInstanceTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfTopologyFromServiceInstanceTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -34,8 +34,8 @@ public class VnfTopologyFromServiceInstanceTest extends QueryTest {
public VnfTopologyFromServiceInstanceTest() throws AAIException, NoEdgeRuleFoundException {
super();
}
-
- @Ignore //TODO: Fix this when verification uses correct schema
+
+ @Ignore // TODO: Fix this when verification uses correct schema
@Test
public void run() {
super.run();
@@ -43,64 +43,113 @@ public class VnfTopologyFromServiceInstanceTest extends QueryTest {
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
- Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name", "service-instance-name-1");
- Vertex servicesubscription = graph.addVertex(T.label, "service-subscription", T.id, "2", "aai-node-type", "service-subscription", "service-subscription-id", "service-subscription-id-1","service-subscription-name","service-subscription-name1");
- Vertex customer = graph.addVertex(T.label, "customer", T.id, "3", "aai-node-type", "customer", "customer-id", "customer-id-1", "customer-name", "customer-name1");
- Vertex allottedresource = graph.addVertex(T.label, "allotted-resource", T.id, "4", "aai-node-type", "allotted-resource", "allotted-resource-id", "allotted-resource-id-1", "allotted-resource-name", "allotted-resource-name1");
- Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "5", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
- Vertex volumegroup = graph.addVertex(T.label, "volume-group", T.id, "6", "aai-node-type", "volume-group", "volume-group-id", "volume-group-id-1", "volume-group-name", "volume-group-name1");
- Vertex linter1 = graph.addVertex(T.label, "l-interface", T.id, "7", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id-1", "l-interface-name", "l-interface-name1");
- Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "8", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address-list-id", "l3-interface-ipv4-address-list-id-1", "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
- Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "9", "aai-node-type", "l3-network", "ll3-network-id", "l3-network-id-1", "l3-network-name", "l3-network-name1");
- Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "10", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-1", "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type", "vserver", "vserver-name1", "vservername1");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "12", "aai-node-type", "tenant", "tenant-name1", "tenant-name-1","tenant-id", "tenant-id-1");
- Vertex region1 = graph.addVertex(T.label, "cloud-region", T.id, "13", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner1");
- Vertex range1 = graph.addVertex(T.label, "vlan-range", T.id, "26", "aai-node-type", "vlan-range", "vlan-range-id", "vlanRange1");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "14", "aai-node-type", "pserver", "hostname", "pservername");
- Vertex linter2 = graph.addVertex(T.label, "l-interface", T.id, "15", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id-2", "l-interface-name", "l-interface-name2");
- Vertex l3inter2ipv4addresslist = graph.addVertex(T.label, "interface-ipv6-address-list", T.id, "16", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-2", "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name2");
- Vertex l3network2 = graph.addVertex(T.label, "l3-network", T.id, "17", "aai-node-type", "l3-network", "ll3-network-id", "l3-network-id-2", "l3-network-name", "l3-network-name2");
- Vertex l3inter2ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "18", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-2", "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name2");
- Vertex l3network3 = graph.addVertex(T.label, "l3-network", T.id, "19", "aai-node-type", "l3-network", "ll3-network-id", "l3-network-id-3", "l3-network-name", "l3-network-name3");
- Vertex l3network4 = graph.addVertex(T.label, "l3-network", T.id, "20", "aai-node-type", "l3-network", "ll3-network-id", "l3-network-id-4", "l3-network-name", "l3-network-name4");
- Vertex l3network5 = graph.addVertex(T.label, "l3-network", T.id, "23", "aai-node-type", "l3-network", "ll3-network-id", "l3-network-id-5", "l3-network-name", "l3-network-name5");
- Vertex l3network6 = graph.addVertex(T.label, "l3-network", T.id, "24", "aai-node-type", "l3-network", "ll3-network-id", "l3-network-id-6", "l3-network-name", "l3-network-name6");
- Vertex configuration = graph.addVertex(T.label, "configuration", T.id, "21", "aai-node-type", "configuration", "configuration-id", "configuration-id-1", "configuration-type", "configuration-type-1");
- Vertex vlantag = graph.addVertex(T.label, "vlan-tag", T.id, "22", "aai-node-type", "vlan-tag", "vlan-tag-id", "vlan-tag-id-1");
- Vertex region2 = graph.addVertex(T.label, "cloud-region", T.id, "28", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner2");
- Vertex range2 = graph.addVertex(T.label, "vlan-range", T.id, "29", "aai-node-type", "vlan-range", "vlan-range-id", "vlanRange2");
- Vertex vlantag2 = graph.addVertex(T.label, "vlan-tag", T.id, "25", "aai-node-type", "vlan-tag", "vlan-tag-id", "vlan-tag-id-2");
-
+ // Set up the test graph
+ Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
+ Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
+ Vertex servicesubscription = graph.addVertex(T.label, "service-subscription", T.id, "2",
+ "aai-node-type", "service-subscription", "service-subscription-id",
+ "service-subscription-id-1", "service-subscription-name", "service-subscription-name1");
+ Vertex customer = graph.addVertex(T.label, "customer", T.id, "3", "aai-node-type",
+ "customer", "customer-id", "customer-id-1", "customer-name", "customer-name1");
+ Vertex allottedresource = graph.addVertex(T.label, "allotted-resource", T.id, "4",
+ "aai-node-type", "allotted-resource", "allotted-resource-id", "allotted-resource-id-1",
+ "allotted-resource-name", "allotted-resource-name1");
+ Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "5", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
+ Vertex volumegroup =
+ graph.addVertex(T.label, "volume-group", T.id, "6", "aai-node-type", "volume-group",
+ "volume-group-id", "volume-group-id-1", "volume-group-name", "volume-group-name1");
+ Vertex linter1 =
+ graph.addVertex(T.label, "l-interface", T.id, "7", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id-1", "l-interface-name", "l-interface-name1");
+ Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "8", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address-list-id", "l3-interface-ipv4-address-list-id-1",
+ "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
+ Vertex l3network1 =
+ graph.addVertex(T.label, "l3-network", T.id, "9", "aai-node-type", "l3-network",
+ "ll3-network-id", "l3-network-id-1", "l3-network-name", "l3-network-name1");
+ Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "10", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-1",
+ "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type", "vserver",
+ "vserver-name1", "vservername1");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "12", "aai-node-type", "tenant",
+ "tenant-name1", "tenant-name-1", "tenant-id", "tenant-id-1");
+ Vertex region1 = graph.addVertex(T.label, "cloud-region", T.id, "13", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloudOwner1");
+ Vertex range1 = graph.addVertex(T.label, "vlan-range", T.id, "26", "aai-node-type",
+ "vlan-range", "vlan-range-id", "vlanRange1");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "14", "aai-node-type", "pserver",
+ "hostname", "pservername");
+ Vertex linter2 =
+ graph.addVertex(T.label, "l-interface", T.id, "15", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id-2", "l-interface-name", "l-interface-name2");
+ Vertex l3inter2ipv4addresslist = graph.addVertex(T.label, "interface-ipv6-address-list",
+ T.id, "16", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-2",
+ "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name2");
+ Vertex l3network2 =
+ graph.addVertex(T.label, "l3-network", T.id, "17", "aai-node-type", "l3-network",
+ "ll3-network-id", "l3-network-id-2", "l3-network-name", "l3-network-name2");
+ Vertex l3inter2ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "18", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-2",
+ "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name2");
+ Vertex l3network3 =
+ graph.addVertex(T.label, "l3-network", T.id, "19", "aai-node-type", "l3-network",
+ "ll3-network-id", "l3-network-id-3", "l3-network-name", "l3-network-name3");
+ Vertex l3network4 =
+ graph.addVertex(T.label, "l3-network", T.id, "20", "aai-node-type", "l3-network",
+ "ll3-network-id", "l3-network-id-4", "l3-network-name", "l3-network-name4");
+ Vertex l3network5 =
+ graph.addVertex(T.label, "l3-network", T.id, "23", "aai-node-type", "l3-network",
+ "ll3-network-id", "l3-network-id-5", "l3-network-name", "l3-network-name5");
+ Vertex l3network6 =
+ graph.addVertex(T.label, "l3-network", T.id, "24", "aai-node-type", "l3-network",
+ "ll3-network-id", "l3-network-id-6", "l3-network-name", "l3-network-name6");
+ Vertex configuration = graph.addVertex(T.label, "configuration", T.id, "21",
+ "aai-node-type", "configuration", "configuration-id", "configuration-id-1",
+ "configuration-type", "configuration-type-1");
+ Vertex vlantag = graph.addVertex(T.label, "vlan-tag", T.id, "22", "aai-node-type",
+ "vlan-tag", "vlan-tag-id", "vlan-tag-id-1");
+ Vertex region2 = graph.addVertex(T.label, "cloud-region", T.id, "28", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloudOwner2");
+ Vertex range2 = graph.addVertex(T.label, "vlan-range", T.id, "29", "aai-node-type",
+ "vlan-range", "vlan-range-id", "vlanRange2");
+ Vertex vlantag2 = graph.addVertex(T.label, "vlan-tag", T.id, "25", "aai-node-type",
+ "vlan-tag", "vlan-tag-id", "vlan-tag-id-2");
GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, gnvf1, serviceinstance);//false
- rules.addTreeEdge(g, serviceinstance, servicesubscription);//true
- rules.addTreeEdge(g, servicesubscription, customer);//true
- rules.addTreeEdge(g, serviceinstance, allottedresource);//true
- rules.addEdge(g, serviceinstance, configuration);//true
- rules.addTreeEdge(g, gnvf1, vfmodule);//true
- rules.addEdge(g, gnvf1, volumegroup);//false
- rules.addEdge(g, gnvf1, l3network5);//true
- rules.addEdge(g, l3network5, vlantag, "org.onap.relationships.inventory.Uses");//true
- rules.addEdge(g, l3network5, l3network6);//true
- rules.addEdge(g, l3network6, vlantag2, "org.onap.relationships.inventory.Uses");//true
- rules.addTreeEdge(g, gnvf1, linter1);//true
- rules.addTreeEdge(g, linter1, l3inter1ipv4addresslist);//true
- rules.addEdge(g, l3inter1ipv4addresslist, l3network1);//false
- rules.addTreeEdge(g, linter1, l3inter1ipv6addresslist);//true
- rules.addEdge(g, l3inter1ipv6addresslist, l3network2);//false
- rules.addEdge(g, gnvf1, vserver);//false
- rules.addTreeEdge(g, vserver, tenant);//true
- rules.addTreeEdge(g, tenant, region1);//true
- rules.addEdge(g, vserver, pserver);//false
- rules.addTreeEdge(g, vserver, linter2);//false
- rules.addTreeEdge(g, linter2, l3inter2ipv4addresslist);//false
- rules.addEdge(g, l3inter2ipv4addresslist, l3network3);//false
- rules.addTreeEdge(g, linter2, l3inter2ipv6addresslist);//true
- rules.addEdge(g, l3inter2ipv6addresslist, l3network4);//true
+ rules.addEdge(g, gnvf1, serviceinstance);// false
+ rules.addTreeEdge(g, serviceinstance, servicesubscription);// true
+ rules.addTreeEdge(g, servicesubscription, customer);// true
+ rules.addTreeEdge(g, serviceinstance, allottedresource);// true
+ rules.addEdge(g, serviceinstance, configuration);// true
+ rules.addTreeEdge(g, gnvf1, vfmodule);// true
+ rules.addEdge(g, gnvf1, volumegroup);// false
+ rules.addEdge(g, gnvf1, l3network5);// true
+ rules.addEdge(g, l3network5, vlantag, "org.onap.relationships.inventory.Uses");// true
+ rules.addEdge(g, l3network5, l3network6);// true
+ rules.addEdge(g, l3network6, vlantag2, "org.onap.relationships.inventory.Uses");// true
+ rules.addTreeEdge(g, gnvf1, linter1);// true
+ rules.addTreeEdge(g, linter1, l3inter1ipv4addresslist);// true
+ rules.addEdge(g, l3inter1ipv4addresslist, l3network1);// false
+ rules.addTreeEdge(g, linter1, l3inter1ipv6addresslist);// true
+ rules.addEdge(g, l3inter1ipv6addresslist, l3network2);// false
+ rules.addEdge(g, gnvf1, vserver);// false
+ rules.addTreeEdge(g, vserver, tenant);// true
+ rules.addTreeEdge(g, tenant, region1);// true
+ rules.addEdge(g, vserver, pserver);// false
+ rules.addTreeEdge(g, vserver, linter2);// false
+ rules.addTreeEdge(g, linter2, l3inter2ipv4addresslist);// false
+ rules.addEdge(g, l3inter2ipv4addresslist, l3network3);// false
+ rules.addTreeEdge(g, linter2, l3inter2ipv6addresslist);// true
+ rules.addEdge(g, l3inter2ipv6addresslist, l3network4);// true
rules.addTreeEdge(g, region1, range1);
rules.addTreeEdge(g, region2, range2);
rules.addTreeEdge(g, range1, vlantag);
@@ -134,13 +183,15 @@ public class VnfTopologyFromServiceInstanceTest extends QueryTest {
@Override
protected String getQueryName() {
- return "vnf-topology-fromServiceInstance";
+ return "vnf-topology-fromServiceInstance";
}
+
@Override
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
g.has("service-instance-name", "service-instance-name-1");
}
+
@Override
protected void addParam(Map<String, Object> params) {
return;
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfTopologyFromVfModuleTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfTopologyFromVfModuleTest.java
index 4f1260e..54c45ca 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfTopologyFromVfModuleTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfTopologyFromVfModuleTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,7 +26,6 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
@@ -42,57 +41,93 @@ public class VnfTopologyFromVfModuleTest extends QueryTest {
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
-
-
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
- Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name", "service-instance-name-1");
- Vertex servicesubscription = graph.addVertex(T.label, "service-subscription", T.id, "2", "aai-node-type", "service-subscription", "service-subscription-id", "service-subscription-id-1","service-subscription-name","service-subscription-name1");
- Vertex customer = graph.addVertex(T.label, "customer", T.id, "3", "aai-node-type", "customer", "customer-id", "customer-id-1", "customer-name", "customer-name1");
- Vertex allottedresource = graph.addVertex(T.label, "allotted-resource", T.id, "4", "aai-node-type", "allotted-resource", "allotted-resource-id", "allotted-resource-id-1", "allotted-resource-name", "allotted-resource-name1");
- Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "5", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
- Vertex volumegroup = graph.addVertex(T.label, "volume-group", T.id, "6", "aai-node-type", "volume-group", "volume-group-id", "volume-group-id-1", "volume-group-name", "volume-group-name1");
- Vertex linter1 = graph.addVertex(T.label, "l-interface", T.id, "7", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id-1", "l-interface-name", "l-interface-name1");
- Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "8", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address-list-id", "l3-interface-ipv4-address-list-id-1", "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
- Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "9", "aai-node-type", "l3-network", "ll3-network-id", "l3-network-id-1", "l3-network-name", "l3-network-name1");
- Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "10", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-1", "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type", "vserver", "vserver-name1", "vservername1");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "12", "aai-node-type", "tenant", "tenant-name1", "tenant-name-1","tenant-id", "tenant-id-1");
- Vertex region1 = graph.addVertex(T.label, "cloud-region", T.id, "13", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner1");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "14", "aai-node-type", "pserver", "hostname", "pservername");
- Vertex linter2 = graph.addVertex(T.label, "l-interface", T.id, "15", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id-2", "l-interface-name", "l-interface-name2");
- Vertex l3inter2ipv4addresslist = graph.addVertex(T.label, "interface-ipv6-address-list", T.id, "16", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-2", "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name2");
- Vertex l3network2 = graph.addVertex(T.label, "l3-network", T.id, "17", "aai-node-type", "l3-network", "ll3-network-id", "l3-network-id-2", "l3-network-name", "l3-network-name2");
- Vertex l3inter2ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "18", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-2", "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name2");
- Vertex l3network3 = graph.addVertex(T.label, "l3-network", T.id, "19", "aai-node-type", "l3-network", "ll3-network-id", "l3-network-id-3", "l3-network-name", "l3-network-name3");
- Vertex l3network4 = graph.addVertex(T.label, "l3-network", T.id, "20", "aai-node-type", "l3-network", "ll3-network-id", "l3-network-id-4", "l3-network-name", "l3-network-name4");
- Vertex vfmoduleStart = graph.addVertex(T.label, "vf-module", T.id, "21", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-2", "vf-module-name", "vf-module-name2");
-
-
+ // Set up the test graph
+
+ Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
+ Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
+ Vertex servicesubscription = graph.addVertex(T.label, "service-subscription", T.id, "2",
+ "aai-node-type", "service-subscription", "service-subscription-id",
+ "service-subscription-id-1", "service-subscription-name", "service-subscription-name1");
+ Vertex customer = graph.addVertex(T.label, "customer", T.id, "3", "aai-node-type",
+ "customer", "customer-id", "customer-id-1", "customer-name", "customer-name1");
+ Vertex allottedresource = graph.addVertex(T.label, "allotted-resource", T.id, "4",
+ "aai-node-type", "allotted-resource", "allotted-resource-id", "allotted-resource-id-1",
+ "allotted-resource-name", "allotted-resource-name1");
+ Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "5", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
+ Vertex volumegroup =
+ graph.addVertex(T.label, "volume-group", T.id, "6", "aai-node-type", "volume-group",
+ "volume-group-id", "volume-group-id-1", "volume-group-name", "volume-group-name1");
+ Vertex linter1 =
+ graph.addVertex(T.label, "l-interface", T.id, "7", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id-1", "l-interface-name", "l-interface-name1");
+ Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "8", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address-list-id", "l3-interface-ipv4-address-list-id-1",
+ "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
+ Vertex l3network1 =
+ graph.addVertex(T.label, "l3-network", T.id, "9", "aai-node-type", "l3-network",
+ "ll3-network-id", "l3-network-id-1", "l3-network-name", "l3-network-name1");
+ Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "10", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-1",
+ "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type", "vserver",
+ "vserver-name1", "vservername1");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "12", "aai-node-type", "tenant",
+ "tenant-name1", "tenant-name-1", "tenant-id", "tenant-id-1");
+ Vertex region1 = graph.addVertex(T.label, "cloud-region", T.id, "13", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloudOwner1");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "14", "aai-node-type", "pserver",
+ "hostname", "pservername");
+ Vertex linter2 =
+ graph.addVertex(T.label, "l-interface", T.id, "15", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id-2", "l-interface-name", "l-interface-name2");
+ Vertex l3inter2ipv4addresslist = graph.addVertex(T.label, "interface-ipv6-address-list",
+ T.id, "16", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-2",
+ "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name2");
+ Vertex l3network2 =
+ graph.addVertex(T.label, "l3-network", T.id, "17", "aai-node-type", "l3-network",
+ "ll3-network-id", "l3-network-id-2", "l3-network-name", "l3-network-name2");
+ Vertex l3inter2ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "18", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-2",
+ "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name2");
+ Vertex l3network3 =
+ graph.addVertex(T.label, "l3-network", T.id, "19", "aai-node-type", "l3-network",
+ "ll3-network-id", "l3-network-id-3", "l3-network-name", "l3-network-name3");
+ Vertex l3network4 =
+ graph.addVertex(T.label, "l3-network", T.id, "20", "aai-node-type", "l3-network",
+ "ll3-network-id", "l3-network-id-4", "l3-network-name", "l3-network-name4");
+ Vertex vfmoduleStart = graph.addVertex(T.label, "vf-module", T.id, "21", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-2", "vf-module-name", "vf-module-name2");
GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, gnvf1, vfmoduleStart);//true
- rules.addEdge(g, gnvf1, serviceinstance);//false
- rules.addTreeEdge(g, serviceinstance, servicesubscription);//true
- rules.addTreeEdge(g, servicesubscription, customer);//true
- rules.addTreeEdge(g, serviceinstance, allottedresource);//true
- rules.addTreeEdge(g, gnvf1, vfmodule);//true
- rules.addEdge(g, gnvf1, volumegroup);//false
- rules.addTreeEdge(g, gnvf1, linter1);//true
- rules.addTreeEdge(g, linter1, l3inter1ipv4addresslist);//true
- rules.addEdge(g, l3inter1ipv4addresslist, l3network1);//false
- rules.addTreeEdge(g, linter1, l3inter1ipv6addresslist);//true
- rules.addEdge(g, l3inter1ipv6addresslist, l3network2);//false
- rules.addEdge(g, gnvf1, vserver);//false
- rules.addTreeEdge(g, vserver, tenant);//true
- rules.addTreeEdge(g, tenant, region1);//true
- rules.addEdge(g, vserver, pserver);//false
- rules.addTreeEdge(g, vserver, linter2);//false
- rules.addTreeEdge(g, linter2, l3inter2ipv4addresslist);//false
- rules.addEdge(g, l3inter2ipv4addresslist, l3network3);//false
- rules.addTreeEdge(g, linter2, l3inter2ipv6addresslist);//true
- rules.addEdge(g, l3inter2ipv6addresslist, l3network4);//true
-
+ rules.addTreeEdge(g, gnvf1, vfmoduleStart);// true
+ rules.addEdge(g, gnvf1, serviceinstance);// false
+ rules.addTreeEdge(g, serviceinstance, servicesubscription);// true
+ rules.addTreeEdge(g, servicesubscription, customer);// true
+ rules.addTreeEdge(g, serviceinstance, allottedresource);// true
+ rules.addTreeEdge(g, gnvf1, vfmodule);// true
+ rules.addEdge(g, gnvf1, volumegroup);// false
+ rules.addTreeEdge(g, gnvf1, linter1);// true
+ rules.addTreeEdge(g, linter1, l3inter1ipv4addresslist);// true
+ rules.addEdge(g, l3inter1ipv4addresslist, l3network1);// false
+ rules.addTreeEdge(g, linter1, l3inter1ipv6addresslist);// true
+ rules.addEdge(g, l3inter1ipv6addresslist, l3network2);// false
+ rules.addEdge(g, gnvf1, vserver);// false
+ rules.addTreeEdge(g, vserver, tenant);// true
+ rules.addTreeEdge(g, tenant, region1);// true
+ rules.addEdge(g, vserver, pserver);// false
+ rules.addTreeEdge(g, vserver, linter2);// false
+ rules.addTreeEdge(g, linter2, l3inter2ipv4addresslist);// false
+ rules.addEdge(g, l3inter2ipv4addresslist, l3network3);// false
+ rules.addTreeEdge(g, linter2, l3inter2ipv6addresslist);// true
+ rules.addEdge(g, l3inter2ipv6addresslist, l3network4);// true
expectedResult.add(gnvf1);
expectedResult.add(serviceinstance);
@@ -118,13 +153,15 @@ public class VnfTopologyFromVfModuleTest extends QueryTest {
@Override
protected String getQueryName() {
- return "vnf-topology-fromVfModule";
+ return "vnf-topology-fromVfModule";
}
+
@Override
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
g.has("vf-module-name", "vf-module-name2");
}
+
@Override
protected void addParam(Map<String, Object> params) {
return;
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfTopologyFromVnfTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfTopologyFromVnfTest.java
index 4441d3f..6a5f2da 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfTopologyFromVnfTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfTopologyFromVnfTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,105 +26,142 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class VnfTopologyFromVnfTest extends QueryTest {
- public VnfTopologyFromVnfTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public VnfTopologyFromVnfTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type", "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
- Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name", "service-instance-name-1");
- Vertex servicesubscription = graph.addVertex(T.label, "service-subscription", T.id, "2", "aai-node-type", "service-subscription", "service-subscription-id", "service-subscription-id-1","service-subscription-name","service-subscription-name1");
- Vertex customer = graph.addVertex(T.label, "customer", T.id, "3", "aai-node-type", "customer", "customer-id", "customer-id-1", "customer-name", "customer-name1");
- Vertex allottedresource = graph.addVertex(T.label, "allotted-resource", T.id, "4", "aai-node-type", "allotted-resource", "allotted-resource-id", "allotted-resource-id-1", "allotted-resource-name", "allotted-resource-name1");
- Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "5", "aai-node-type", "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
- Vertex volumegroup = graph.addVertex(T.label, "volume-group", T.id, "6", "aai-node-type", "volume-group", "volume-group-id", "volume-group-id-1", "volume-group-name", "volume-group-name1");
- Vertex linter1 = graph.addVertex(T.label, "l-interface", T.id, "7", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id-1", "l-interface-name", "l-interface-name1");
- Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list", T.id, "8", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address-list-id", "l3-interface-ipv4-address-list-id-1", "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
- Vertex l3network1 = graph.addVertex(T.label, "l3-network", T.id, "9", "aai-node-type", "l3-network", "ll3-network-id", "l3-network-id-1", "l3-network-name", "l3-network-name1");
- Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "10", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-1", "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type", "vserver", "vserver-name1", "vservername1");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "12", "aai-node-type", "tenant", "tenant-name1", "tenant-name-1","tenant-id", "tenant-id-1");
- Vertex region1 = graph.addVertex(T.label, "cloud-region", T.id, "13", "aai-node-type", "cloud-region", "cloud-owner", "cloudOwner1");
- Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "14", "aai-node-type", "pserver", "hostname", "pservername");
- Vertex linter2 = graph.addVertex(T.label, "l-interface", T.id, "15", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id-2", "l-interface-name", "l-interface-name2");
- Vertex l3inter2ipv4addresslist = graph.addVertex(T.label, "interface-ipv6-address-list", T.id, "16", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-2", "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name2");
- Vertex l3network2 = graph.addVertex(T.label, "l3-network", T.id, "17", "aai-node-type", "l3-network", "ll3-network-id", "l3-network-id-2", "l3-network-name", "l3-network-name2");
- Vertex l3inter2ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list", T.id, "18", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-2", "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name2");
- Vertex l3network3 = graph.addVertex(T.label, "l3-network", T.id, "19", "aai-node-type", "l3-network", "ll3-network-id", "l3-network-id-3", "l3-network-name", "l3-network-name3");
- Vertex l3network4 = graph.addVertex(T.label, "l3-network", T.id, "20", "aai-node-type", "l3-network", "ll3-network-id", "l3-network-id-4", "l3-network-name", "l3-network-name4");
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex gnvf1 = graph.addVertex(T.label, "generic-vnf", T.id, "0", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnf-id-1", "vnf-name", "vnf-name-1");
+ Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
+ Vertex servicesubscription = graph.addVertex(T.label, "service-subscription", T.id, "2",
+ "aai-node-type", "service-subscription", "service-subscription-id",
+ "service-subscription-id-1", "service-subscription-name", "service-subscription-name1");
+ Vertex customer = graph.addVertex(T.label, "customer", T.id, "3", "aai-node-type",
+ "customer", "customer-id", "customer-id-1", "customer-name", "customer-name1");
+ Vertex allottedresource = graph.addVertex(T.label, "allotted-resource", T.id, "4",
+ "aai-node-type", "allotted-resource", "allotted-resource-id", "allotted-resource-id-1",
+ "allotted-resource-name", "allotted-resource-name1");
+ Vertex vfmodule = graph.addVertex(T.label, "vf-module", T.id, "5", "aai-node-type",
+ "vf-module", "vf-module-id", "vf-module-id-1", "vf-module-name", "vf-module-name1");
+ Vertex volumegroup =
+ graph.addVertex(T.label, "volume-group", T.id, "6", "aai-node-type", "volume-group",
+ "volume-group-id", "volume-group-id-1", "volume-group-name", "volume-group-name1");
+ Vertex linter1 =
+ graph.addVertex(T.label, "l-interface", T.id, "7", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id-1", "l-interface-name", "l-interface-name1");
+ Vertex l3inter1ipv4addresslist = graph.addVertex(T.label, "interface-ipv4-address-list",
+ T.id, "8", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address-list-id", "l3-interface-ipv4-address-list-id-1",
+ "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
+ Vertex l3network1 =
+ graph.addVertex(T.label, "l3-network", T.id, "9", "aai-node-type", "l3-network",
+ "ll3-network-id", "l3-network-id-1", "l3-network-name", "l3-network-name1");
+ Vertex l3inter1ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "10", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-1",
+ "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name1");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type", "vserver",
+ "vserver-name1", "vservername1");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "12", "aai-node-type", "tenant",
+ "tenant-name1", "tenant-name-1", "tenant-id", "tenant-id-1");
+ Vertex region1 = graph.addVertex(T.label, "cloud-region", T.id, "13", "aai-node-type",
+ "cloud-region", "cloud-owner", "cloudOwner1");
+ Vertex pserver = graph.addVertex(T.label, "pserver", T.id, "14", "aai-node-type", "pserver",
+ "hostname", "pservername");
+ Vertex linter2 =
+ graph.addVertex(T.label, "l-interface", T.id, "15", "aai-node-type", "l-interface",
+ "l-interface-id", "l-interface-id-2", "l-interface-name", "l-interface-name2");
+ Vertex l3inter2ipv4addresslist = graph.addVertex(T.label, "interface-ipv6-address-list",
+ T.id, "16", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-2",
+ "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name2");
+ Vertex l3network2 =
+ graph.addVertex(T.label, "l3-network", T.id, "17", "aai-node-type", "l3-network",
+ "ll3-network-id", "l3-network-id-2", "l3-network-name", "l3-network-name2");
+ Vertex l3inter2ipv6addresslist = graph.addVertex(T.label, "l3-interface-ipv6-address-list",
+ T.id, "18", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address-list-id", "l3-interface-ipv6-address-list-id-2",
+ "l3-interface-ipv6-address-list-name", "l3-interface-ipv6-address-list-name2");
+ Vertex l3network3 =
+ graph.addVertex(T.label, "l3-network", T.id, "19", "aai-node-type", "l3-network",
+ "ll3-network-id", "l3-network-id-3", "l3-network-name", "l3-network-name3");
+ Vertex l3network4 =
+ graph.addVertex(T.label, "l3-network", T.id, "20", "aai-node-type", "l3-network",
+ "ll3-network-id", "l3-network-id-4", "l3-network-name", "l3-network-name4");
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, gnvf1, serviceinstance);// false
+ rules.addTreeEdge(g, serviceinstance, servicesubscription);// true
+ rules.addTreeEdge(g, servicesubscription, customer);// true
+ rules.addTreeEdge(g, serviceinstance, allottedresource);// true
+ rules.addTreeEdge(g, gnvf1, vfmodule);// true
+ rules.addEdge(g, gnvf1, volumegroup);// false
+ rules.addTreeEdge(g, gnvf1, linter1);// true
+ rules.addTreeEdge(g, linter1, l3inter1ipv4addresslist);// true
+ rules.addEdge(g, l3inter1ipv4addresslist, l3network1);// false
+ rules.addTreeEdge(g, linter1, l3inter1ipv6addresslist);// true
+ rules.addEdge(g, l3inter1ipv6addresslist, l3network2);// false
+ rules.addEdge(g, gnvf1, vserver);// false
+ rules.addTreeEdge(g, vserver, tenant);// true
+ rules.addTreeEdge(g, tenant, region1);// true
+ rules.addEdge(g, vserver, pserver);// false
+ rules.addTreeEdge(g, vserver, linter2);// false
+ rules.addTreeEdge(g, linter2, l3inter2ipv4addresslist);// false
+ rules.addEdge(g, l3inter2ipv4addresslist, l3network3);// false
+ rules.addTreeEdge(g, linter2, l3inter2ipv6addresslist);// true
+ rules.addEdge(g, l3inter2ipv6addresslist, l3network4);// true
+ expectedResult.add(gnvf1);
+ expectedResult.add(serviceinstance);
+ expectedResult.add(servicesubscription);
+ expectedResult.add(customer);
+ expectedResult.add(allottedresource);
+ expectedResult.add(vfmodule);
+ expectedResult.add(volumegroup);
+ expectedResult.add(linter1);
+ expectedResult.add(l3inter1ipv4addresslist);
+ expectedResult.add(l3network1);
+ expectedResult.add(l3inter1ipv6addresslist);
+ expectedResult.add(l3network2);
+ expectedResult.add(vserver);
+ expectedResult.add(tenant);
+ expectedResult.add(region1);
+ expectedResult.add(pserver);
+ expectedResult.add(linter2);
+ expectedResult.add(l3inter2ipv4addresslist);
+ expectedResult.add(l3network3);
+ expectedResult.add(l3inter2ipv6addresslist);
+ expectedResult.add(l3network4);
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, gnvf1, serviceinstance);//false
- rules.addTreeEdge(g, serviceinstance, servicesubscription);//true
- rules.addTreeEdge(g, servicesubscription, customer);//true
- rules.addTreeEdge(g, serviceinstance, allottedresource);//true
- rules.addTreeEdge(g, gnvf1, vfmodule);//true
- rules.addEdge(g, gnvf1, volumegroup);//false
- rules.addTreeEdge(g, gnvf1, linter1);//true
- rules.addTreeEdge(g, linter1, l3inter1ipv4addresslist);//true
- rules.addEdge(g, l3inter1ipv4addresslist, l3network1);//false
- rules.addTreeEdge(g, linter1, l3inter1ipv6addresslist);//true
- rules.addEdge(g, l3inter1ipv6addresslist, l3network2);//false
- rules.addEdge(g, gnvf1, vserver);//false
- rules.addTreeEdge(g, vserver, tenant);//true
- rules.addTreeEdge(g, tenant, region1);//true
- rules.addEdge(g, vserver, pserver);//false
- rules.addTreeEdge(g, vserver, linter2);//false
- rules.addTreeEdge(g, linter2, l3inter2ipv4addresslist);//false
- rules.addEdge(g, l3inter2ipv4addresslist, l3network3);//false
- rules.addTreeEdge(g, linter2, l3inter2ipv6addresslist);//true
- rules.addEdge(g, l3inter2ipv6addresslist, l3network4);//true
+ }
+ @Override
+ protected String getQueryName() {
+ return "vnf-topology-fromVnf";
+ }
- expectedResult.add(gnvf1);
- expectedResult.add(serviceinstance);
- expectedResult.add(servicesubscription);
- expectedResult.add(customer);
- expectedResult.add(allottedresource);
- expectedResult.add(vfmodule);
- expectedResult.add(volumegroup);
- expectedResult.add(linter1);
- expectedResult.add(l3inter1ipv4addresslist);
- expectedResult.add(l3network1);
- expectedResult.add(l3inter1ipv6addresslist);
- expectedResult.add(l3network2);
- expectedResult.add(vserver);
- expectedResult.add(tenant);
- expectedResult.add(region1);
- expectedResult.add(pserver);
- expectedResult.add(linter2);
- expectedResult.add(l3inter2ipv4addresslist);
- expectedResult.add(l3network3);
- expectedResult.add(l3inter2ipv6addresslist);
- expectedResult.add(l3network4);
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("vnf-name", "vnf-name-1");
- }
+ }
- @Override
- protected String getQueryName() {
- return "vnf-topology-fromVnf";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("vnf-name", "vnf-name-1");
-
- }
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfVserverFromCustomerTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfVserverFromCustomerTest.java
index 5d70867..971ac4f 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfVserverFromCustomerTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfVserverFromCustomerTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,60 +26,71 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class VnfVserverFromCustomerTest extends QueryTest {
- public VnfVserverFromCustomerTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex customer1 = graph.addVertex(T.label, "customer", T.id, "0", "aai-node-type", "customer", "global-customer-id", "customer1","subscriber-type","INFRA");
- Vertex service1 = graph.addVertex(T.label, "service-subscription", T.id, "1", "aai-node-type", "service-subscription", "service-type", "service1");
- Vertex instance = graph.addVertex(T.label, "service-instance", T.id, "2", "aai-node-type", "service-instance");
- Vertex vnf = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type", "generic-vnf");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "4", "aai-node-type", "vserver");
-
- Vertex customer2 = graph.addVertex(T.label, "customer", T.id, "5", "aai-node-type", "customer", "global-customer-id", "customer2","subscriber-type","INFRA2");
- Vertex service2 = graph.addVertex(T.label, "service-subscription", T.id, "6", "aai-node-type", "service-subscription", "service-type", "service2");
- Vertex instance2 = graph.addVertex(T.label, "service-instance", T.id, "7", "aai-node-type", "service-instance");
- Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type", "generic-vnf");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "9", "aai-node-type", "vserver");
-
- GraphTraversalSource g = graph.traversal();
- rules.addTreeEdge(g, customer1, service1);
- rules.addTreeEdge(g, service1, instance);
- rules.addEdge(g, vnf, instance);
- rules.addEdge(g, vnf, vserver);
-
- rules.addTreeEdge(g, customer2, service2); //false
- rules.addTreeEdge(g, service2, instance2); //false
- rules.addEdge(g, vnf2, instance2); //false
- rules.addEdge(g, vnf2, vserver2);//false
-
- expectedResult.add(vnf);
- expectedResult.add(vserver);
+ public VnfVserverFromCustomerTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex customer1 = graph.addVertex(T.label, "customer", T.id, "0", "aai-node-type",
+ "customer", "global-customer-id", "customer1", "subscriber-type", "INFRA");
+ Vertex service1 = graph.addVertex(T.label, "service-subscription", T.id, "1",
+ "aai-node-type", "service-subscription", "service-type", "service1");
+ Vertex instance = graph.addVertex(T.label, "service-instance", T.id, "2", "aai-node-type",
+ "service-instance");
+ Vertex vnf =
+ graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type", "generic-vnf");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "4", "aai-node-type", "vserver");
+
+ Vertex customer2 = graph.addVertex(T.label, "customer", T.id, "5", "aai-node-type",
+ "customer", "global-customer-id", "customer2", "subscriber-type", "INFRA2");
+ Vertex service2 = graph.addVertex(T.label, "service-subscription", T.id, "6",
+ "aai-node-type", "service-subscription", "service-type", "service2");
+ Vertex instance2 = graph.addVertex(T.label, "service-instance", T.id, "7", "aai-node-type",
+ "service-instance");
+ Vertex vnf2 =
+ graph.addVertex(T.label, "generic-vnf", T.id, "8", "aai-node-type", "generic-vnf");
+ Vertex vserver2 =
+ graph.addVertex(T.label, "vserver", T.id, "9", "aai-node-type", "vserver");
+
+ GraphTraversalSource g = graph.traversal();
+ rules.addTreeEdge(g, customer1, service1);
+ rules.addTreeEdge(g, service1, instance);
+ rules.addEdge(g, vnf, instance);
+ rules.addEdge(g, vnf, vserver);
+
+ rules.addTreeEdge(g, customer2, service2); // false
+ rules.addTreeEdge(g, service2, instance2); // false
+ rules.addEdge(g, vnf2, instance2); // false
+ rules.addEdge(g, vnf2, vserver2);// false
+
+ expectedResult.add(vnf);
+ expectedResult.add(vserver);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "vnf-vserver-fromCustomer";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "customer").has("subscriber-type", "INFRA");
+ }
- }
- @Override
- protected String getQueryName() {
- return "vnf-vserver-fromCustomer";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "customer").has("subscriber-type", "INFRA");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfsFromPserverQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfsFromPserverQueryTest.java
index 16b9499..bb07697 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfsFromPserverQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfsFromPserverQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -26,64 +26,75 @@ import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversalSo
import org.apache.tinkerpop.gremlin.structure.T;
import org.apache.tinkerpop.gremlin.structure.Vertex;
import org.junit.Test;
-
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class VnfsFromPserverQueryTest extends QueryTest {
- public VnfsFromPserverQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
-
- Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type", "generic-vnf", "vnf-id", "vnfid1", "vnf-name", "sample");
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "2", "aai-node-type", "pserver", "hostname", "pservername1");
-
- Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type", "generic-vnf", "vnf-id", "vnfid2");
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver", "hostname", "pservername2");
-
- Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver", "hostname", "pservername3");
- Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "6", "aai-node-type", "vserver", "vserver-name", "vservername");
- Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "7", "aai-node-type", "tenant", "tenant-id", "tenantuuid", "tenant-name", "tenantname");
- Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "8", "aai-node-type", "cloud-region", "cloud-region-id", "clouduuid", "cloud-region-owner", "cloudOwnername");
-
- Vertex vnf3 = graph.addVertex(T.label, "generic-vnf", T.id, "9", "aai-node-type", "generic-vnf", "vnf-id", "vnfid3", "vnf-name", "sample");
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addEdge(g, pserver1, vnf1);
- rules.addEdge(g, pserver1, vnf2);
- rules.addEdge(g, pserver1, vnf3);
-
- rules.addTreeEdge(g, tenant, cloudregion);
- rules.addTreeEdge(g, vserver, tenant);
- rules.addEdge(g, vserver, pserver3);
- rules.addEdge(g, vserver, vnf2);
-
- //expectedResult.add(vnf2);
- expectedResult.add(vnf1);
- //expectedResult.add(vnf3);
-
- }
- @Override
- protected String getQueryName() {
- return "vnfs-fromPserver";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- //g.has("vnf-id", "vnfid2");
- g.has("aai-node-type","generic-vnf").has("vnf-id", "vnfid1").has("vnf-name", "sample");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("hostname", "pservername1");
- }
+ public VnfsFromPserverQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
+
+ @Test
+ public void run() {
+ super.run();
+ }
+
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+
+ Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "1", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid1", "vnf-name", "sample");
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "2", "aai-node-type", "pserver",
+ "hostname", "pservername1");
+
+ Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "3", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid2");
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "4", "aai-node-type", "pserver",
+ "hostname", "pservername2");
+
+ Vertex pserver3 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver",
+ "hostname", "pservername3");
+ Vertex vserver = graph.addVertex(T.label, "vserver", T.id, "6", "aai-node-type", "vserver",
+ "vserver-name", "vservername");
+ Vertex tenant = graph.addVertex(T.label, "tenant", T.id, "7", "aai-node-type", "tenant",
+ "tenant-id", "tenantuuid", "tenant-name", "tenantname");
+ Vertex cloudregion = graph.addVertex(T.label, "cloud-region", T.id, "8", "aai-node-type",
+ "cloud-region", "cloud-region-id", "clouduuid", "cloud-region-owner", "cloudOwnername");
+
+ Vertex vnf3 = graph.addVertex(T.label, "generic-vnf", T.id, "9", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid3", "vnf-name", "sample");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addEdge(g, pserver1, vnf1);
+ rules.addEdge(g, pserver1, vnf2);
+ rules.addEdge(g, pserver1, vnf3);
+
+ rules.addTreeEdge(g, tenant, cloudregion);
+ rules.addTreeEdge(g, vserver, tenant);
+ rules.addEdge(g, vserver, pserver3);
+ rules.addEdge(g, vserver, vnf2);
+
+ // expectedResult.add(vnf2);
+ expectedResult.add(vnf1);
+ // expectedResult.add(vnf3);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "vnfs-fromPserver";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ // g.has("vnf-id", "vnfid2");
+ g.has("aai-node-type", "generic-vnf").has("vnf-id", "vnfid1").has("vnf-name", "sample");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("hostname", "pservername1");
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfsFromServiceInstanceTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfsFromServiceInstanceTest.java
index 09fd515..708286d 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfsFromServiceInstanceTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfsFromServiceInstanceTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -30,49 +30,61 @@ import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class VnfsFromServiceInstanceTest extends QueryTest {
- public VnfsFromServiceInstanceTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
-
- //Set up the test graph
- Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name", "service-instance-name-1");
- Vertex servicesubscription = graph.addVertex(T.label, "service-subscription", T.id, "2", "aai-node-type", "service-subscription", "service-subscription-id", "service-subscription-id-1","service-subscription-name","service-subscription-name1");
- Vertex customer = graph.addVertex(T.label, "customer", T.id, "3", "aai-node-type", "customer", "customer-id", "customer-id-1", "customer-name", "customer-name1");
- Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type", "generic-vnf", "vnf-id", "vnfid1", "vnf-name", "vnfname1", "vnf-type", "vnftype1");
- Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "5", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2", "service-instance-name", "service-instance-name-2");
- Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "6", "aai-node-type", "generic-vnf", "vnf-id", "vnfid2", "vnf-name", "vnfname2", "vnf-type", "vnftype1");
-
- GraphTraversalSource g = graph.traversal();
+ public VnfsFromServiceInstanceTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- rules.addEdge(g, vnf1, serviceinstance);//true
- rules.addEdge(g, vnf2, serviceinstance2);
+ @Test
+ public void run() {
+ super.run();
+ }
- rules.addTreeEdge(g, serviceinstance, servicesubscription);//true
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+
+ // Set up the test graph
+ Vertex serviceinstance = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
+ Vertex servicesubscription = graph.addVertex(T.label, "service-subscription", T.id, "2",
+ "aai-node-type", "service-subscription", "service-subscription-id",
+ "service-subscription-id-1", "service-subscription-name", "service-subscription-name1");
+ Vertex customer = graph.addVertex(T.label, "customer", T.id, "3", "aai-node-type",
+ "customer", "customer-id", "customer-id-1", "customer-name", "customer-name1");
+ Vertex vnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "4", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid1", "vnf-name", "vnfname1", "vnf-type", "vnftype1");
+ Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "5",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-2",
+ "service-instance-name", "service-instance-name-2");
+ Vertex vnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "6", "aai-node-type",
+ "generic-vnf", "vnf-id", "vnfid2", "vnf-name", "vnfname2", "vnf-type", "vnftype1");
+
+ GraphTraversalSource g = graph.traversal();
+
+ rules.addEdge(g, vnf1, serviceinstance);// true
+ rules.addEdge(g, vnf2, serviceinstance2);
+
+ rules.addTreeEdge(g, serviceinstance, servicesubscription);// true
rules.addTreeEdge(g, serviceinstance2, servicesubscription);
- rules.addTreeEdge(g, servicesubscription, customer);//true
-
- expectedResult.add(vnf1);
+ rules.addTreeEdge(g, servicesubscription, customer);// true
+
+ expectedResult.add(vnf1);
+
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "vnfs-fromServiceInstance";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "service-instance").has("service-instance-id",
+ "service-instance-id-1");
+ }
- }
- @Override
- protected String getQueryName() {
- return "vnfs-fromServiceInstance";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "service-instance").has("service-instance-id", "service-instance-id-1");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfsVlansFromServiceInstanceTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfsVlansFromServiceInstanceTest.java
index f7c517e..936c361 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfsVlansFromServiceInstanceTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VnfsVlansFromServiceInstanceTest.java
@@ -1,103 +1,123 @@
package org.onap.aai.rest.search; /**
- * ============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=========================================================
- */
+ * ============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.search;
-
-import java.util.Map;
-
-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.T;
-import org.apache.tinkerpop.gremlin.structure.Vertex;
-import org.junit.Test;
-import org.onap.aai.exceptions.AAIException;
-import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-
-public class VnfsVlansFromServiceInstanceTest extends QueryTest {
- public VnfsVlansFromServiceInstanceTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
-
- @Test
- public void run() {
- super.run();
- }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
-
-
- //Set up the test graph
- Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "0", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name",
- "service-instance-name-1");
-
- Vertex config1 = graph.addVertex(T.label, "configuration", T.id, "1", "aai-node-type", "configuration", "configuration-id", "configuration1");
-
- Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type", "generic-vnf",
- "vnf-id", "gvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
-
- Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "3", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0","network-name","networkName0");
-
- Vertex vlan1 = graph.addVertex(T.label, "vlan", T.id, "4", "aai-node-type", "vlan", "vlan-interface", "vlan-interface1");
-
-
- Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "5", "aai-node-type",
- "service-instance", "service-instance-id", "service-instance-id-2", "service-instance-name",
- "service-instance-name-1");
-
- Vertex config2 = graph.addVertex(T.label, "configuration", T.id, "6", "aai-node-type", "configuration", "configuration-id", "configuration2");
-
- Vertex gvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "7", "aai-node-type", "generic-vnf",
- "vnf-id", "gvnf2", "vnf-name", "genvnfname2", "nf-type", "sample-nf-type");
-
- Vertex linterface2 = graph.addVertex(T.label, "l-interface", T.id, "8", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id2", "l-interface-name", "l-interface-name2","network-name","networkName1");
-
- Vertex vlan2 = graph.addVertex(T.label, "vlan", T.id, "9", "aai-node-type", "vlan", "vlan-interface", "vlan-interface2");
-
- GraphTraversalSource g = graph.traversal();
-
- rules.addEdge(g, serviceinstance1, config1); // True
- rules.addEdge(g, config1, gvnf1); // True
- rules.addEdge(g, config1, linterface1); // True
- rules.addTreeEdge(g, linterface1, vlan1); // True
-
- rules.addEdge(g, serviceinstance2, config2); // False
- rules.addEdge(g, config2, gvnf2); // False
- rules.addEdge(g, config2, linterface2);// False
- rules.addTreeEdge(g, linterface2, vlan2); // False
-
- expectedResult.add(gvnf1);
- expectedResult.add(vlan1);
-
- }
- @Override
- protected String getQueryName() {
- return "vnfs-vlans-fromServiceInstance";
- }
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "service-instance").has("service-instance-id", "service-instance-id-1");
- }
-
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
-}*/ \ No newline at end of file
+ * package org.onap.aai.rest.search;
+ *
+ * import java.util.Map;
+ *
+ * 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.T;
+ * import org.apache.tinkerpop.gremlin.structure.Vertex;
+ * import org.junit.Test;
+ * import org.onap.aai.exceptions.AAIException;
+ * import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
+ *
+ * public class VnfsVlansFromServiceInstanceTest extends QueryTest {
+ * public VnfsVlansFromServiceInstanceTest() throws AAIException, NoEdgeRuleFoundException {
+ * super();
+ * }
+ *
+ * @Test
+ * public void run() {
+ * super.run();
+ * }
+ *
+ * @Override
+ * protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ *
+ *
+ * //Set up the test graph
+ * Vertex serviceinstance1 = graph.addVertex(T.label, "service-instance", T.id, "0",
+ * "aai-node-type",
+ * "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name",
+ * "service-instance-name-1");
+ *
+ * Vertex config1 = graph.addVertex(T.label, "configuration", T.id, "1", "aai-node-type",
+ * "configuration", "configuration-id", "configuration1");
+ *
+ * Vertex gvnf1 = graph.addVertex(T.label, "generic-vnf", T.id, "2", "aai-node-type", "generic-vnf",
+ * "vnf-id", "gvnf1", "vnf-name", "genvnfname1", "nf-type", "sample-nf-type");
+ *
+ * Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "3", "aai-node-type",
+ * "l-interface", "l-interface-id", "l-interface-id0", "l-interface-name",
+ * "l-interface-name0","network-name","networkName0");
+ *
+ * Vertex vlan1 = graph.addVertex(T.label, "vlan", T.id, "4", "aai-node-type", "vlan",
+ * "vlan-interface", "vlan-interface1");
+ *
+ *
+ * Vertex serviceinstance2 = graph.addVertex(T.label, "service-instance", T.id, "5",
+ * "aai-node-type",
+ * "service-instance", "service-instance-id", "service-instance-id-2", "service-instance-name",
+ * "service-instance-name-1");
+ *
+ * Vertex config2 = graph.addVertex(T.label, "configuration", T.id, "6", "aai-node-type",
+ * "configuration", "configuration-id", "configuration2");
+ *
+ * Vertex gvnf2 = graph.addVertex(T.label, "generic-vnf", T.id, "7", "aai-node-type", "generic-vnf",
+ * "vnf-id", "gvnf2", "vnf-name", "genvnfname2", "nf-type", "sample-nf-type");
+ *
+ * Vertex linterface2 = graph.addVertex(T.label, "l-interface", T.id, "8", "aai-node-type",
+ * "l-interface", "l-interface-id", "l-interface-id2", "l-interface-name",
+ * "l-interface-name2","network-name","networkName1");
+ *
+ * Vertex vlan2 = graph.addVertex(T.label, "vlan", T.id, "9", "aai-node-type", "vlan",
+ * "vlan-interface", "vlan-interface2");
+ *
+ * GraphTraversalSource g = graph.traversal();
+ *
+ * rules.addEdge(g, serviceinstance1, config1); // True
+ * rules.addEdge(g, config1, gvnf1); // True
+ * rules.addEdge(g, config1, linterface1); // True
+ * rules.addTreeEdge(g, linterface1, vlan1); // True
+ *
+ * rules.addEdge(g, serviceinstance2, config2); // False
+ * rules.addEdge(g, config2, gvnf2); // False
+ * rules.addEdge(g, config2, linterface2);// False
+ * rules.addTreeEdge(g, linterface2, vlan2); // False
+ *
+ * expectedResult.add(gvnf1);
+ * expectedResult.add(vlan1);
+ *
+ * }
+ *
+ * @Override
+ * protected String getQueryName() {
+ * return "vnfs-vlans-fromServiceInstance";
+ * }
+ *
+ * @Override
+ * protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ * g.has("aai-node-type", "service-instance").has("service-instance-id", "service-instance-id-1");
+ * }
+ *
+ * @Override
+ * protected void addParam(Map<String, Object> params) {
+ * return;
+ * }
+ * }
+ */
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverFromPserverTreeTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverFromPserverTreeTest.java
index 79d070a..6b9ea12 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverFromPserverTreeTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverFromPserverTreeTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,11 @@
*/
package org.onap.aai.rest.search;
+import static org.junit.Assert.assertFalse;
+import static org.junit.Assert.assertTrue;
+
+import java.util.Map;
+
import org.apache.tinkerpop.gremlin.process.traversal.dsl.graph.GraphTraversal;
import org.apache.tinkerpop.gremlin.process.traversal.step.util.Tree;
import org.apache.tinkerpop.gremlin.structure.T;
@@ -27,11 +32,6 @@ import org.junit.Test;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-
-import static org.junit.Assert.assertFalse;
-import static org.junit.Assert.assertTrue;
-
public class VserverFromPserverTreeTest extends TreeQueryTest {
public VserverFromPserverTreeTest() throws AAIException, NoEdgeRuleFoundException {
@@ -40,11 +40,19 @@ public class VserverFromPserverTreeTest extends TreeQueryTest {
@Override
protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex p1 = graph.addVertex(T.label, "pserver", T.id, "0", "aai-node-type", "pserver", "hostname", "pserver-name-1");
- Vertex p2 = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver", "hostname", "pserver-name-2");
- Vertex v1 = graph.addVertex(T.label, "vserver", T.id, "2", "aai-node-type", "vserver", "vserver-id", "vservId-1", "vserver-name", "vserv-name-1", "vserver-selflink", "me/self");
- Vertex v2 = graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id", "vservId-2", "vserver-name", "vserv-name-2", "vserver-selflink", "me/self");
- Vertex v3 = graph.addVertex(T.label, "vserver", T.id, "4", "aai-node-type", "vserver", "vserver-id", "vservId-3", "vserver-name", "vserv-name-3", "vserver-selflink", "me/self");
+ Vertex p1 = graph.addVertex(T.label, "pserver", T.id, "0", "aai-node-type", "pserver",
+ "hostname", "pserver-name-1");
+ Vertex p2 = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver",
+ "hostname", "pserver-name-2");
+ Vertex v1 =
+ graph.addVertex(T.label, "vserver", T.id, "2", "aai-node-type", "vserver", "vserver-id",
+ "vservId-1", "vserver-name", "vserv-name-1", "vserver-selflink", "me/self");
+ Vertex v2 =
+ graph.addVertex(T.label, "vserver", T.id, "3", "aai-node-type", "vserver", "vserver-id",
+ "vservId-2", "vserver-name", "vserv-name-2", "vserver-selflink", "me/self");
+ Vertex v3 =
+ graph.addVertex(T.label, "vserver", T.id, "4", "aai-node-type", "vserver", "vserver-id",
+ "vservId-3", "vserver-name", "vserv-name-3", "vserver-selflink", "me/self");
rules.addEdge(gts, p1, v1);
rules.addEdge(gts, p1, v2);
@@ -56,11 +64,16 @@ public class VserverFromPserverTreeTest extends TreeQueryTest {
super.run();
Tree tree = treeList.get(0);
- Vertex p1 = graph.traversal().V().has("aai-node-type","pserver").has("hostname","pserver-name-1").next();
- Vertex p2 = graph.traversal().V().has("aai-node-type","pserver").has("hostname","pserver-name-2").next();
- Vertex v1 = graph.traversal().V().has("aai-node-type", "vserver").has("vserver-id","vservId-1").next();
- Vertex v2 = graph.traversal().V().has("aai-node-type", "vserver").has("vserver-id","vservId-2").next();
- Vertex v3 = graph.traversal().V().has("aai-node-type", "vserver").has("vserver-id","vservId-3").next();
+ Vertex p1 = graph.traversal().V().has("aai-node-type", "pserver")
+ .has("hostname", "pserver-name-1").next();
+ Vertex p2 = graph.traversal().V().has("aai-node-type", "pserver")
+ .has("hostname", "pserver-name-2").next();
+ Vertex v1 = graph.traversal().V().has("aai-node-type", "vserver")
+ .has("vserver-id", "vservId-1").next();
+ Vertex v2 = graph.traversal().V().has("aai-node-type", "vserver")
+ .has("vserver-id", "vservId-2").next();
+ Vertex v3 = graph.traversal().V().has("aai-node-type", "vserver")
+ .has("vserver-id", "vservId-3").next();
assertTrue(tree.containsKey(p1));
assertTrue(((Tree) tree.get(p1)).containsKey(v1));
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverFromVnfQueryTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverFromVnfQueryTest.java
index 3dd7b25..26972ba 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverFromVnfQueryTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverFromVnfQueryTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -31,70 +31,76 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class VserverFromVnfQueryTest extends QueryTest {
- public VserverFromVnfQueryTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public VserverFromVnfQueryTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex gv = graph.addVertex(T.id, "00", "aai-node-type", "generic-vnf", "vnf-id", "gvId", "vnf-name", "gvName", "vnf-type", "some-type");
- Vertex vnfc = graph.addVertex(T.id, "10", "aai-node-type", "vnfc",
- "vnfc-name", "vnfcName1", "nfc-naming-code", "blue", "nfc-function", "correct-function");
- Vertex vserv = graph.addVertex(T.id, "20", "aai-node-type", "vserver",
- "vserver-id", "vservId", "vserver-name", "vservName", "vserver-selflink", "me/self");
- Vertex lint = graph.addVertex(T.id, "30", "aai-node-type", "l-interface", "interface-name", "lintName");
- Vertex ipv4 = graph.addVertex(T.id, "40", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "0.0.0.0");
- Vertex ipv6 = graph.addVertex(T.id, "50", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "0.0.0.0");
-
-
- Vertex gv1 = graph.addVertex(T.id, "60", "aai-node-type", "generic-vnf", "vnf-id", "gvId1", "vnf-name", "gvName1", "vnf-type", "some-type1");
- Vertex vnfc1 = graph.addVertex(T.id, "70", "aai-node-type", "vnfc",
- "vnfc-name", "vnfcName11", "nfc-naming-code", "blue1", "nfc-function", "correct-function1");
- Vertex vserv1 = graph.addVertex(T.id, "80", "aai-node-type", "vserver",
- "vserver-id", "vservId1", "vserver-name", "vservName1", "vserver-selflink", "me/self1");
- Vertex lint1 = graph.addVertex(T.id, "90", "aai-node-type", "l-interface", "interface-name", "lintName1");
- Vertex ipv41 = graph.addVertex(T.id, "1", "aai-node-type", "l3-interface-ipv4-address-list", "l3-interface-ipv4-address", "0.0.0.0.1");
- Vertex ipv61 = graph.addVertex(T.id, "2", "aai-node-type", "l3-interface-ipv6-address-list", "l3-interface-ipv6-address", "0.0.0.0.1");
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex gv = graph.addVertex(T.id, "00", "aai-node-type", "generic-vnf", "vnf-id", "gvId",
+ "vnf-name", "gvName", "vnf-type", "some-type");
+ Vertex vnfc = graph.addVertex(T.id, "10", "aai-node-type", "vnfc", "vnfc-name", "vnfcName1",
+ "nfc-naming-code", "blue", "nfc-function", "correct-function");
+ Vertex vserv = graph.addVertex(T.id, "20", "aai-node-type", "vserver", "vserver-id",
+ "vservId", "vserver-name", "vservName", "vserver-selflink", "me/self");
+ Vertex lint = graph.addVertex(T.id, "30", "aai-node-type", "l-interface", "interface-name",
+ "lintName");
+ Vertex ipv4 = graph.addVertex(T.id, "40", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "0.0.0.0");
+ Vertex ipv6 = graph.addVertex(T.id, "50", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "0.0.0.0");
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, gv, vnfc);
- rules.addEdge(g, vserv, vnfc);
- rules.addTreeEdge(g, vserv, lint);
- rules.addTreeEdge(g, lint, ipv4);
- rules.addTreeEdge(g, lint, ipv6);
-
- rules.addEdge(g, gv1, vnfc1);//false
- rules.addEdge(g, vserv1, vnfc1);//false
- rules.addTreeEdge(g, vserv1, lint1);//false
- rules.addTreeEdge(g, lint1, ipv41);//false
- rules.addTreeEdge(g, lint1, ipv61);//false
-
- expectedResult.add(vserv);
- expectedResult.add(lint);
- expectedResult.add(ipv4);
- expectedResult.add(ipv6);
- expectedResult.add(vnfc);
- }
+ Vertex gv1 = graph.addVertex(T.id, "60", "aai-node-type", "generic-vnf", "vnf-id", "gvId1",
+ "vnf-name", "gvName1", "vnf-type", "some-type1");
+ Vertex vnfc1 = graph.addVertex(T.id, "70", "aai-node-type", "vnfc", "vnfc-name",
+ "vnfcName11", "nfc-naming-code", "blue1", "nfc-function", "correct-function1");
+ Vertex vserv1 = graph.addVertex(T.id, "80", "aai-node-type", "vserver", "vserver-id",
+ "vservId1", "vserver-name", "vservName1", "vserver-selflink", "me/self1");
+ Vertex lint1 = graph.addVertex(T.id, "90", "aai-node-type", "l-interface", "interface-name",
+ "lintName1");
+ Vertex ipv41 = graph.addVertex(T.id, "1", "aai-node-type", "l3-interface-ipv4-address-list",
+ "l3-interface-ipv4-address", "0.0.0.0.1");
+ Vertex ipv61 = graph.addVertex(T.id, "2", "aai-node-type", "l3-interface-ipv6-address-list",
+ "l3-interface-ipv6-address", "0.0.0.0.1");
- @Override
- protected String getQueryName() {
- return "vserver-fromVnf";
- }
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, gv, vnfc);
+ rules.addEdge(g, vserv, vnfc);
+ rules.addTreeEdge(g, vserv, lint);
+ rules.addTreeEdge(g, lint, ipv4);
+ rules.addTreeEdge(g, lint, ipv6);
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "generic-vnf").has("vnf-id", "gvId");
- }
+ rules.addEdge(g, gv1, vnfc1);// false
+ rules.addEdge(g, vserv1, vnfc1);// false
+ rules.addTreeEdge(g, vserv1, lint1);// false
+ rules.addTreeEdge(g, lint1, ipv41);// false
+ rules.addTreeEdge(g, lint1, ipv61);// false
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("nfcNamingCode", "blue");
- }
+ expectedResult.add(vserv);
+ expectedResult.add(lint);
+ expectedResult.add(ipv4);
+ expectedResult.add(ipv6);
+ expectedResult.add(vnfc);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "vserver-fromVnf";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "generic-vnf").has("vnf-id", "gvId");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("nfcNamingCode", "blue");
+ }
-
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverLinterfacesFromVnfcTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverLinterfacesFromVnfcTest.java
index 2c1a0ea..d272273 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverLinterfacesFromVnfcTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverLinterfacesFromVnfcTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -33,66 +33,76 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class VserverLinterfacesFromVnfcTest extends QueryTest {
- public VserverLinterfacesFromVnfcTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public VserverLinterfacesFromVnfcTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void run() {
- super.run();
- }
+ @Test
+ public void run() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- Vertex vnfc = graph.addVertex(T.label, "vnfc",T.id, "0", "aai-node-type", "vnfc",
- "vnfc-name", "vnfcName1", "nfc-naming-code", "blue", "nfc-function", "correct-function");
- Vertex vserv = graph.addVertex(T.label, "vserver",T.id, "1", "aai-node-type", "vserver",
- "vserver-id", "vservId", "vserver-name", "vservName", "vserver-selflink", "me/self");
- Vertex linterface = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id0", "l-interface-name", "l-interface-name0","network-name","networkName0");
- Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "3", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id1", "l-interface-name", "l-interface-name1","network-name","networkName1");
- Vertex vlan = graph.addVertex(T.label, "vlan", T.id, "4", "aai-node-type", "vlan", "vlan-interface", "vlan-interface0");
-
-
- Vertex vnfc1 = graph.addVertex(T.label, "vnfc",T.id, "10", "aai-node-type", "vnfc",
- "vnfc-name", "vnfcName2", "nfc-naming-code", "blue-1", "nfc-function", "correct-function-1");
- Vertex vserv1 = graph.addVertex(T.label, "vserver",T.id, "11", "aai-node-type", "vserver",
- "vserver-id", "vservId1", "vserver-name", "vservName1", "vserver-selflink", "me/self-1");
- Vertex linterface2 = graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id2", "l-interface-name", "l-interface-name2","network-name","networkName2");
- Vertex linterface21 = graph.addVertex(T.label, "l-interface", T.id, "13", "aai-node-type", "l-interface", "l-interface-id", "l-interface-id21", "l-interface-name", "l-interface-name21","network-name","networkName21");
- Vertex vlan1 = graph.addVertex(T.label, "vlan", T.id, "14", "aai-node-type", "vlan", "vlan-interface", "vlan-interface1");
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ Vertex vnfc =
+ graph.addVertex(T.label, "vnfc", T.id, "0", "aai-node-type", "vnfc", "vnfc-name",
+ "vnfcName1", "nfc-naming-code", "blue", "nfc-function", "correct-function");
+ Vertex vserv = graph.addVertex(T.label, "vserver", T.id, "1", "aai-node-type", "vserver",
+ "vserver-id", "vservId", "vserver-name", "vservName", "vserver-selflink", "me/self");
+ Vertex linterface = graph.addVertex(T.label, "l-interface", T.id, "2", "aai-node-type",
+ "l-interface", "l-interface-id", "l-interface-id0", "l-interface-name",
+ "l-interface-name0", "network-name", "networkName0");
+ Vertex linterface1 = graph.addVertex(T.label, "l-interface", T.id, "3", "aai-node-type",
+ "l-interface", "l-interface-id", "l-interface-id1", "l-interface-name",
+ "l-interface-name1", "network-name", "networkName1");
+ Vertex vlan = graph.addVertex(T.label, "vlan", T.id, "4", "aai-node-type", "vlan",
+ "vlan-interface", "vlan-interface0");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, vnfc,vserv);
- rules.addTreeEdge(g, vserv, linterface);
- rules.addTreeEdge(g, linterface, linterface1);
- rules.addTreeEdge(g, linterface1, vlan);
-
- rules.addEdge(g, vnfc1,vserv1);//false
- rules.addTreeEdge(g, vserv1, linterface2);//false
- rules.addTreeEdge(g, linterface2, linterface21);//false
- rules.addTreeEdge(g, linterface21, vlan1);//false
-
- expectedResult.add(vserv);
- expectedResult.add(linterface);
- expectedResult.add(linterface1);
- expectedResult.add(vlan);
- }
+ Vertex vnfc1 =
+ graph.addVertex(T.label, "vnfc", T.id, "10", "aai-node-type", "vnfc", "vnfc-name",
+ "vnfcName2", "nfc-naming-code", "blue-1", "nfc-function", "correct-function-1");
+ Vertex vserv1 = graph.addVertex(T.label, "vserver", T.id, "11", "aai-node-type", "vserver",
+ "vserver-id", "vservId1", "vserver-name", "vservName1", "vserver-selflink",
+ "me/self-1");
+ Vertex linterface2 = graph.addVertex(T.label, "l-interface", T.id, "12", "aai-node-type",
+ "l-interface", "l-interface-id", "l-interface-id2", "l-interface-name",
+ "l-interface-name2", "network-name", "networkName2");
+ Vertex linterface21 = graph.addVertex(T.label, "l-interface", T.id, "13", "aai-node-type",
+ "l-interface", "l-interface-id", "l-interface-id21", "l-interface-name",
+ "l-interface-name21", "network-name", "networkName21");
+ Vertex vlan1 = graph.addVertex(T.label, "vlan", T.id, "14", "aai-node-type", "vlan",
+ "vlan-interface", "vlan-interface1");
- @Override
- protected String getQueryName() {
- return "vserver-l-interfaces-fromVnfc";
- }
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, vnfc, vserv);
+ rules.addTreeEdge(g, vserv, linterface);
+ rules.addTreeEdge(g, linterface, linterface1);
+ rules.addTreeEdge(g, linterface1, vlan);
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "vnfc").has("vnfc-name", "vnfcName1");
- }
+ rules.addEdge(g, vnfc1, vserv1);// false
+ rules.addTreeEdge(g, vserv1, linterface2);// false
+ rules.addTreeEdge(g, linterface2, linterface21);// false
+ rules.addTreeEdge(g, linterface21, vlan1);// false
- @Override
- protected void addParam(Map<String, Object> params) {
- params.put("networkName", "networkName0");
- }
+ expectedResult.add(vserv);
+ expectedResult.add(linterface);
+ expectedResult.add(linterface1);
+ expectedResult.add(vlan);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "vserver-l-interfaces-fromVnfc";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("aai-node-type", "vnfc").has("vnfc-name", "vnfcName1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ params.put("networkName", "networkName0");
+ }
-
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverLogicallinkFromPServerTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverLogicallinkFromPServerTest.java
index 03a7757..aa3a9d1 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverLogicallinkFromPServerTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/VserverLogicallinkFromPServerTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -33,54 +33,62 @@ import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
public class VserverLogicallinkFromPServerTest extends QueryTest {
- public VserverLogicallinkFromPServerTest() throws AAIException, NoEdgeRuleFoundException {
- super();
- }
+ public VserverLogicallinkFromPServerTest() throws AAIException, NoEdgeRuleFoundException {
+ super();
+ }
- @Test
- public void test() {
- super.run();
- }
+ @Test
+ public void test() {
+ super.run();
+ }
- @Override
- protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
- //Set up the test graph
- Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver", "hostname", "hostname-1");
- Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "2", "aai-node-type", "vserver", "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
- Vertex lInterface1 = graph.addVertex(T.label, "l-interface", T.id, "3", "aai-node-type", "l-interface", "interface-name", "interface-name-1");
- Vertex logicalLink1 = graph.addVertex(T.label, "l", T.id, "4", "aai-node-type", "logical-link", "link-name", "link-name-1");
-
- Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver", "hostname", "hostname-2");
- Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "6", "aai-node-type", "vserver", "vserver-id", "vserver-id-2", "vserver-name", "vserver-name-2");
- Vertex lInterface2 = graph.addVertex(T.label, "l-interface", T.id, "7", "aai-node-type", "l-interface", "interface-name", "interface-name-2");
- Vertex logicalLink2 = graph.addVertex(T.label, "l", T.id, "8", "aai-node-type", "logical-link", "link-name", "link-name-2");
-
- GraphTraversalSource g = graph.traversal();
- rules.addEdge(g, pserver1, vserver1);
- rules.addTreeEdge(g, vserver1, lInterface1);
- rules.addEdge(g, lInterface1, logicalLink1);
-
- rules.addEdge(g, pserver2, vserver2);
- rules.addTreeEdge(g, vserver2, lInterface2);
- rules.addEdge(g, lInterface2, logicalLink2);
-
- expectedResult.add(vserver1);
- expectedResult.add(logicalLink1);
- }
+ @Override
+ protected void createGraph() throws AAIException, NoEdgeRuleFoundException {
+ // Set up the test graph
+ Vertex pserver1 = graph.addVertex(T.label, "pserver", T.id, "1", "aai-node-type", "pserver",
+ "hostname", "hostname-1");
+ Vertex vserver1 = graph.addVertex(T.label, "vserver", T.id, "2", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-1", "vserver-name", "vserver-name-1");
+ Vertex lInterface1 = graph.addVertex(T.label, "l-interface", T.id, "3", "aai-node-type",
+ "l-interface", "interface-name", "interface-name-1");
+ Vertex logicalLink1 = graph.addVertex(T.label, "l", T.id, "4", "aai-node-type",
+ "logical-link", "link-name", "link-name-1");
- @Override
- protected String getQueryName() {
- return "vserverlogicallink-frompServer";
- }
+ Vertex pserver2 = graph.addVertex(T.label, "pserver", T.id, "5", "aai-node-type", "pserver",
+ "hostname", "hostname-2");
+ Vertex vserver2 = graph.addVertex(T.label, "vserver", T.id, "6", "aai-node-type", "vserver",
+ "vserver-id", "vserver-id-2", "vserver-name", "vserver-name-2");
+ Vertex lInterface2 = graph.addVertex(T.label, "l-interface", T.id, "7", "aai-node-type",
+ "l-interface", "interface-name", "interface-name-2");
+ Vertex logicalLink2 = graph.addVertex(T.label, "l", T.id, "8", "aai-node-type",
+ "logical-link", "link-name", "link-name-2");
- @Override
- protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("hostname", "hostname-1");
- }
+ GraphTraversalSource g = graph.traversal();
+ rules.addEdge(g, pserver1, vserver1);
+ rules.addTreeEdge(g, vserver1, lInterface1);
+ rules.addEdge(g, lInterface1, logicalLink1);
- @Override
- protected void addParam(Map<String, Object> params) {
- return;
- }
+ rules.addEdge(g, pserver2, vserver2);
+ rules.addTreeEdge(g, vserver2, lInterface2);
+ rules.addEdge(g, lInterface2, logicalLink2);
+
+ expectedResult.add(vserver1);
+ expectedResult.add(logicalLink1);
+ }
+
+ @Override
+ protected String getQueryName() {
+ return "vserverlogicallink-frompServer";
+ }
+
+ @Override
+ protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
+ g.has("hostname", "hostname-1");
+ }
+
+ @Override
+ protected void addParam(Map<String, Object> params) {
+ return;
+ }
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/search/getSvcSubscriberModelInfoTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/search/getSvcSubscriberModelInfoTest.java
index c854f43..2414d5a 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/search/getSvcSubscriberModelInfoTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/search/getSvcSubscriberModelInfoTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,6 +19,8 @@
*/
package org.onap.aai.rest.search;
+import java.util.Map;
+
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.T;
@@ -29,30 +31,32 @@ import org.onap.aai.edges.exceptions.EdgeRuleNotFoundException;
import org.onap.aai.exceptions.AAIException;
import org.onap.aai.serialization.db.exceptions.NoEdgeRuleFoundException;
-import java.util.Map;
-
public class getSvcSubscriberModelInfoTest extends QueryTest {
public getSvcSubscriberModelInfoTest() throws AAIException, NoEdgeRuleFoundException {
super();
}
+
@Test
public void run() {
super.run();
}
-
-
@Override
- protected void createGraph() throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
+ protected void createGraph()
+ throws AAIException, EdgeRuleNotFoundException, AmbiguousRuleChoiceException {
- Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "1", "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1", "service-instance-name", "service-instance-name-1");
- Vertex serviceSubscription = graph.addVertex(T.label, "service-subscription", T.id, "2", "aai-node-type", "service-subscription", "service-type", "service-subcription-1");
- Vertex modelver = graph.addVertex(T.label, "model-ver", T.id, "3", "aai-node-type", "model-ver");
+ Vertex serviceInstance = graph.addVertex(T.label, "service-instance", T.id, "1",
+ "aai-node-type", "service-instance", "service-instance-id", "service-instance-id-1",
+ "service-instance-name", "service-instance-name-1");
+ Vertex serviceSubscription = graph.addVertex(T.label, "service-subscription", T.id, "2",
+ "aai-node-type", "service-subscription", "service-type", "service-subcription-1");
+ Vertex modelver =
+ graph.addVertex(T.label, "model-ver", T.id, "3", "aai-node-type", "model-ver");
GraphTraversalSource g = graph.traversal();
rules.addTreeEdge(g, serviceInstance, serviceSubscription);
- rules.addPrivateEdge(g, serviceInstance, modelver,null);
+ rules.addPrivateEdge(g, serviceInstance, modelver, null);
expectedResult.add(serviceInstance);
expectedResult.add(serviceSubscription);
@@ -60,15 +64,17 @@ public class getSvcSubscriberModelInfoTest extends QueryTest {
}
-
@Override
protected String getQueryName() {
- return "getSvcSubscriberModelInfo";
+ return "getSvcSubscriberModelInfo";
}
+
@Override
protected void addStartNode(GraphTraversal<Vertex, Vertex> g) {
- g.has("aai-node-type", "service-instance").has("service-instance-id", "service-instance-id-1");
+ g.has("aai-node-type", "service-instance").has("service-instance-id",
+ "service-instance-id-1");
}
+
@Override
protected void addParam(Map<String, Object> params) {
return;
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/util/ConvertQueryPropertiesToJsonTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/util/ConvertQueryPropertiesToJsonTest.java
index d15545f..c7e550e 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/util/ConvertQueryPropertiesToJsonTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/util/ConvertQueryPropertiesToJsonTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -27,23 +27,27 @@ import org.junit.Test;
public class ConvertQueryPropertiesToJsonTest {
@Test
- public void testRqdProperty(){
+ public void testRqdProperty() {
ConvertQueryPropertiesToJson convert = new ConvertQueryPropertiesToJson();
Properties props = new Properties();
- props.setProperty("queryName1", "builder.getVerticesByProperty('rqdProp', rqdPropId).getVerticesByProperty('rqdProp2', rqdPropId2).createEdgeTraversal(EdgeType.TREE, 'node1', 'child-node1')");
- props.setProperty("lastQueryName", "builder.getVerticesByProperty('notRqdProp', \"OUT\").createEdgeTraversal(EdgeType.TREE, 'node2', 'child-node2')");
+ props.setProperty("queryName1",
+ "builder.getVerticesByProperty('rqdProp', rqdPropId).getVerticesByProperty('rqdProp2', rqdPropId2).createEdgeTraversal(EdgeType.TREE, 'node1', 'child-node1')");
+ props.setProperty("lastQueryName",
+ "builder.getVerticesByProperty('notRqdProp', \"OUT\").createEdgeTraversal(EdgeType.TREE, 'node2', 'child-node2')");
String json = convert.convertProperties(props);
assertNotNull(json);
}
-
+
@Test
- public void testLastQueryRqdProperty(){
+ public void testLastQueryRqdProperty() {
ConvertQueryPropertiesToJson convert = new ConvertQueryPropertiesToJson();
Properties props = new Properties();
- props.setProperty("queryName1", "builder.createEdgeTraversal(EdgeType.TREE, 'node1', 'child-node1')");
- props.setProperty("lastQueryName", "builder.getVerticesByProperty('rqdProp', rqdPropId).createEdgeTraversal(EdgeType.TREE, 'node2', 'child-node2')");
+ props.setProperty("queryName1",
+ "builder.createEdgeTraversal(EdgeType.TREE, 'node1', 'child-node1')");
+ props.setProperty("lastQueryName",
+ "builder.getVerticesByProperty('rqdProp', rqdPropId).createEdgeTraversal(EdgeType.TREE, 'node2', 'child-node2')");
String json = convert.convertProperties(props);
assertNotNull(json);
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/util/EchoResponseTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/util/EchoResponseTest.java
index a07dfa6..46ff650 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/util/EchoResponseTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/util/EchoResponseTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,22 +19,24 @@
*/
package org.onap.aai.rest.util;
-import org.slf4j.Logger;
-import org.slf4j.LoggerFactory;
-import com.att.eelf.configuration.EELFManager;
-import org.junit.Before;
-import org.junit.Test;
-import org.mockito.Mockito;
-
-import javax.ws.rs.core.*;
-import java.util.*;
-
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.mockito.Matchers.anyObject;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
+import com.att.eelf.configuration.EELFManager;
+
+import java.util.*;
+
+import javax.ws.rs.core.*;
+
+import org.junit.Before;
+import org.junit.Test;
+import org.mockito.Mockito;
+import org.slf4j.Logger;
+import org.slf4j.LoggerFactory;
+
public class EchoResponseTest {
protected static final MediaType APPLICATION_JSON = MediaType.valueOf("application/json");
@@ -63,15 +65,15 @@ public class EchoResponseTest {
private static final Logger logger = LoggerFactory.getLogger(EchoResponseTest.class.getName());
@Before
- public void setup(){
+ public void setup() {
logger.info("Starting the setup for the integration tests of Rest Endpoints");
- echoResponse = new EchoResponse();
- httpHeaders = mock(HttpHeaders.class);
- uriInfo = mock(UriInfo.class);
+ echoResponse = new EchoResponse();
+ httpHeaders = mock(HttpHeaders.class);
+ uriInfo = mock(UriInfo.class);
- headersMultiMap = new MultivaluedHashMap<>();
- queryParameters = Mockito.spy(new MultivaluedHashMap<>());
+ headersMultiMap = new MultivaluedHashMap<>();
+ queryParameters = Mockito.spy(new MultivaluedHashMap<>());
headersMultiMap.add("X-FromAppId", "JUNIT");
headersMultiMap.add("X-TransactionId", UUID.randomUUID().toString());
@@ -92,11 +94,11 @@ public class EchoResponseTest {
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
+ // 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);
@@ -125,11 +127,11 @@ public class EchoResponseTest {
public void testEchoResultWhenValidHeadersButMediaTypeWrong() throws Exception {
when(httpHeaders.getAcceptableMediaTypes()).thenThrow(new IllegalStateException())
- .thenReturn(outputMediaTypes);
+ .thenReturn(outputMediaTypes);
Response response = echoResponse.echoResult(httpHeaders, null, "");
assertNotNull(response);
assertEquals(Response.Status.INTERNAL_SERVER_ERROR.getStatusCode(), response.getStatus());
}
-} \ No newline at end of file
+}
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java
index f17257b..44b72a5 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/util/LogFormatToolsTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,14 +19,14 @@
*/
package org.onap.aai.rest.util;
-import org.junit.Test;
-
import static org.junit.Assert.assertNotNull;
+import org.junit.Test;
+
public class LogFormatToolsTest {
@Test
- public void testLogFormatTools(){
+ public void testLogFormatTools() {
String dateTime = new LogFormatTools().getCurrentDateTime();
assertNotNull(dateTime);
diff --git a/aai-traversal/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java b/aai-traversal/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java
index bf7612b..d627072 100644
--- a/aai-traversal/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/rest/util/ValidateEncodingTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -32,82 +32,83 @@ import org.mockito.Mockito;
public class ValidateEncodingTest {
-
- @Test
- public void badPath() throws UnsupportedEncodingException {
- String badPath = "/aai/v6/network/vces/vce/blahh::blach/others/other/jklfea{}";
- UriInfo mockUriInfo = getMockUriInfo(badPath, new MultivaluedHashMap<String, String>());
- ValidateEncoding validator = ValidateEncoding.getInstance();
-
- assertEquals(false, validator.validate(mockUriInfo));
- }
-
- @Test
- public void goodPath() throws UnsupportedEncodingException {
- String goodPath = "/aai/v6/network/vces/vce/blahh%3A%3Ablach/others/other/jklfea%7B%7D";
- UriInfo mockUriInfo = getMockUriInfo(goodPath, new MultivaluedHashMap<String, String>());
- ValidateEncoding validator = ValidateEncoding.getInstance();
-
- assertEquals(true, validator.validate(mockUriInfo));
- }
-
- @Test
- public void badQueryParamsKey() throws UnsupportedEncodingException {
- MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>();
- map.putSingle("blahblah", "test");
- map.putSingle("blahblah", "test2");
- map.putSingle("bad::bad", "test3");
- UriInfo mockUriInfo = getMockUriInfo("", map);
-
- ValidateEncoding validator = ValidateEncoding.getInstance();
-
- assertEquals(false, validator.validate(mockUriInfo));
-
- }
- @Test
- public void badQueryParamsValue() throws UnsupportedEncodingException {
- MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>();
- map.putSingle("blahblah", "test");
- map.putSingle("blahblah", "test//:2");
- map.putSingle("badbad", "test3");
- UriInfo mockUriInfo = getMockUriInfo("", map);
-
- ValidateEncoding validator = ValidateEncoding.getInstance();
-
- assertEquals(false, validator.validate(mockUriInfo));
- }
-
- @Test
- public void goodQueryParams() throws UnsupportedEncodingException {
- MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>();
- map.putSingle("blahblah", "test");
- map.putSingle("blahblah", "test2");
- map.putSingle("badbad", "~test%2F%2F%3A3");
- UriInfo mockUriInfo = getMockUriInfo("", map);
-
- ValidateEncoding validator = ValidateEncoding.getInstance();
-
- assertEquals(true, validator.validate(mockUriInfo));
- }
-
- @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);
- Mockito.when(mockUriInfo.getPath(false)).thenReturn(path);
- Mockito.when(mockUriInfo.getQueryParameters(false)).thenReturn(map);
-
- return mockUriInfo;
- }
-
+ @Test
+ public void badPath() throws UnsupportedEncodingException {
+ String badPath = "/aai/v6/network/vces/vce/blahh::blach/others/other/jklfea{}";
+ UriInfo mockUriInfo = getMockUriInfo(badPath, new MultivaluedHashMap<String, String>());
+ ValidateEncoding validator = ValidateEncoding.getInstance();
+
+ assertEquals(false, validator.validate(mockUriInfo));
+ }
+
+ @Test
+ public void goodPath() throws UnsupportedEncodingException {
+ String goodPath = "/aai/v6/network/vces/vce/blahh%3A%3Ablach/others/other/jklfea%7B%7D";
+ UriInfo mockUriInfo = getMockUriInfo(goodPath, new MultivaluedHashMap<String, String>());
+ ValidateEncoding validator = ValidateEncoding.getInstance();
+
+ assertEquals(true, validator.validate(mockUriInfo));
+ }
+
+ @Test
+ public void badQueryParamsKey() throws UnsupportedEncodingException {
+ MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>();
+ map.putSingle("blahblah", "test");
+ map.putSingle("blahblah", "test2");
+ map.putSingle("bad::bad", "test3");
+ UriInfo mockUriInfo = getMockUriInfo("", map);
+
+ ValidateEncoding validator = ValidateEncoding.getInstance();
+
+ assertEquals(false, validator.validate(mockUriInfo));
+
+ }
+
+ @Test
+ public void badQueryParamsValue() throws UnsupportedEncodingException {
+ MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>();
+ map.putSingle("blahblah", "test");
+ map.putSingle("blahblah", "test//:2");
+ map.putSingle("badbad", "test3");
+ UriInfo mockUriInfo = getMockUriInfo("", map);
+
+ ValidateEncoding validator = ValidateEncoding.getInstance();
+
+ assertEquals(false, validator.validate(mockUriInfo));
+ }
+
+ @Test
+ public void goodQueryParams() throws UnsupportedEncodingException {
+ MultivaluedHashMap<String, String> map = new MultivaluedHashMap<String, String>();
+ map.putSingle("blahblah", "test");
+ map.putSingle("blahblah", "test2");
+ map.putSingle("badbad", "~test%2F%2F%3A3");
+ UriInfo mockUriInfo = getMockUriInfo("", map);
+
+ ValidateEncoding validator = ValidateEncoding.getInstance();
+
+ assertEquals(true, validator.validate(mockUriInfo));
+ }
+
+ @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);
+ Mockito.when(mockUriInfo.getPath(false)).thenReturn(path);
+ Mockito.when(mockUriInfo.getQueryParameters(false)).thenReturn(map);
+
+ return mockUriInfo;
+ }
+
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/transforms/JoltTestUtil.java b/aai-traversal/src/test/java/org/onap/aai/transforms/JoltTestUtil.java
index 78f7471..d07fd97 100644
--- a/aai-traversal/src/test/java/org/onap/aai/transforms/JoltTestUtil.java
+++ b/aai-traversal/src/test/java/org/onap/aai/transforms/JoltTestUtil.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,42 +19,45 @@
*/
package org.onap.aai.transforms;
+import com.bazaarvoice.jolt.ArrayOrderObliviousDiffy;
+import com.bazaarvoice.jolt.Diffy;
+import com.bazaarvoice.jolt.JsonUtils;
import java.io.IOException;
import org.junit.Assert;
-import com.bazaarvoice.jolt.ArrayOrderObliviousDiffy;
-import com.bazaarvoice.jolt.Diffy;
-import com.bazaarvoice.jolt.JsonUtils;
-
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(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 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(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 );
+ 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 );
+ 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());
+ Assert.fail("\nActual object\n" + actualObject + "\n" + failureMessage
+ + "\nDiffy output\n" + result.toString());
}
}
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverterTest.java b/aai-traversal/src/test/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverterTest.java
index 2f7d336..f8b4613 100644
--- a/aai-traversal/src/test/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverterTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/transforms/LowerHyphenToLowerCamelConverterTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,15 +19,15 @@
*/
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 static org.junit.Assert.*;
import java.util.Arrays;
import java.util.Collection;
-import static org.junit.Assert.*;
+import org.junit.Test;
+import org.junit.runner.RunWith;
+import org.junit.runners.Parameterized;
+import org.junit.runners.Parameterized.Parameters;
@RunWith(Parameterized.class)
public class LowerHyphenToLowerCamelConverterTest {
@@ -37,35 +37,32 @@ public class LowerHyphenToLowerCamelConverterTest {
private String input;
private String expected;
- public LowerHyphenToLowerCamelConverterTest(String input, String expected){
- this.input = input;
+ 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(){
+ 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"},
- });
+ 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(){
+ public void testIfInputSuccessfullyModified() {
String actual = converter.convert(input);
assertEquals(expected, actual);
}
diff --git a/aai-traversal/src/test/java/org/onap/aai/transforms/MapTraverserTest.java b/aai-traversal/src/test/java/org/onap/aai/transforms/MapTraverserTest.java
index bfaeb8f..5ae5603 100644
--- a/aai-traversal/src/test/java/org/onap/aai/transforms/MapTraverserTest.java
+++ b/aai-traversal/src/test/java/org/onap/aai/transforms/MapTraverserTest.java
@@ -8,7 +8,7 @@
* 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
+ * 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,
@@ -19,23 +19,24 @@
*/
package org.onap.aai.transforms;
-import org.onap.aai.transforms.LowerCamelToLowerHyphenConverter;
-import org.onap.aai.transforms.MapTraverser;
import com.bazaarvoice.jolt.JsonUtils;
-import org.junit.Test;
import java.io.IOException;
import java.util.Map;
+import org.junit.Test;
+import org.onap.aai.transforms.LowerCamelToLowerHyphenConverter;
+import org.onap.aai.transforms.MapTraverser;
+
public class MapTraverserTest {
private final String testResources = "src/test/resources/maputils/testcases/";
- private String[] testCases = { "TestCase1.json", "TestCase2.json" };
+ private String[] testCases = {"TestCase1.json", "TestCase2.json"};
private MapTraverser traverser = new MapTraverser(new LowerCamelToLowerHyphenConverter());
@Test(expected = NullPointerException.class)
- public void testIfMapIsNullThrowNullPointerException(){
+ public void testIfMapIsNullThrowNullPointerException() {
Map<String, Object> map = null;
traverser.convertKeys(map);
}
@@ -43,13 +44,13 @@ public class MapTraverserTest {
@Test
public void runTestCases() throws IOException {
- for(String testCase : testCases){
+ 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 actual = traverser.convertKeys((Map<String, Object>) input);
Object output = values.get("output");
- JoltTestUtil.runArrayOrderObliviousDiffy( "failed case " + testCase, output, actual );
+ JoltTestUtil.runArrayOrderObliviousDiffy("failed case " + testCase, output, actual);
}
}
}